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::internal::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 // ...but do keep inlining and removing empty lines for non-block extern "C" 266 // functions. 267 verifyFormat("extern \"C\" int f() { return 42; }", getGoogleStyle()); 268 EXPECT_EQ("extern \"C\" int f() {\n" 269 " int i = 42;\n" 270 " return i;\n" 271 "}", 272 format("extern \"C\" int f() {\n" 273 "\n" 274 " int i = 42;\n" 275 " return i;\n" 276 "}", 277 getGoogleStyle())); 278 279 // Remove empty lines at the beginning and end of blocks. 280 EXPECT_EQ("void f() {\n" 281 "\n" 282 " if (a) {\n" 283 "\n" 284 " f();\n" 285 " }\n" 286 "}", 287 format("void f() {\n" 288 "\n" 289 " if (a) {\n" 290 "\n" 291 " f();\n" 292 "\n" 293 " }\n" 294 "\n" 295 "}", 296 getLLVMStyle())); 297 EXPECT_EQ("void f() {\n" 298 " if (a) {\n" 299 " f();\n" 300 " }\n" 301 "}", 302 format("void f() {\n" 303 "\n" 304 " if (a) {\n" 305 "\n" 306 " f();\n" 307 "\n" 308 " }\n" 309 "\n" 310 "}", 311 getGoogleStyle())); 312 313 // Don't remove empty lines in more complex control statements. 314 EXPECT_EQ("void f() {\n" 315 " if (a) {\n" 316 " f();\n" 317 "\n" 318 " } else if (b) {\n" 319 " f();\n" 320 " }\n" 321 "}", 322 format("void f() {\n" 323 " if (a) {\n" 324 " f();\n" 325 "\n" 326 " } else if (b) {\n" 327 " f();\n" 328 "\n" 329 " }\n" 330 "\n" 331 "}")); 332 333 // Don't remove empty lines before namespace endings. 334 FormatStyle LLVMWithNoNamespaceFix = getLLVMStyle(); 335 LLVMWithNoNamespaceFix.FixNamespaceComments = false; 336 EXPECT_EQ("namespace {\n" 337 "int i;\n" 338 "\n" 339 "}", 340 format("namespace {\n" 341 "int i;\n" 342 "\n" 343 "}", 344 LLVMWithNoNamespaceFix)); 345 EXPECT_EQ("namespace {\n" 346 "int i;\n" 347 "}", 348 format("namespace {\n" 349 "int i;\n" 350 "}", 351 LLVMWithNoNamespaceFix)); 352 EXPECT_EQ("namespace {\n" 353 "int i;\n" 354 "\n" 355 "};", 356 format("namespace {\n" 357 "int i;\n" 358 "\n" 359 "};", 360 LLVMWithNoNamespaceFix)); 361 EXPECT_EQ("namespace {\n" 362 "int i;\n" 363 "};", 364 format("namespace {\n" 365 "int i;\n" 366 "};", 367 LLVMWithNoNamespaceFix)); 368 EXPECT_EQ("namespace {\n" 369 "int i;\n" 370 "\n" 371 "}", 372 format("namespace {\n" 373 "int i;\n" 374 "\n" 375 "}")); 376 EXPECT_EQ("namespace {\n" 377 "int i;\n" 378 "\n" 379 "} // namespace", 380 format("namespace {\n" 381 "int i;\n" 382 "\n" 383 "} // namespace")); 384 385 FormatStyle Style = getLLVMStyle(); 386 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All; 387 Style.MaxEmptyLinesToKeep = 2; 388 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 389 Style.BraceWrapping.AfterClass = true; 390 Style.BraceWrapping.AfterFunction = true; 391 Style.KeepEmptyLinesAtTheStartOfBlocks = false; 392 393 EXPECT_EQ("class Foo\n" 394 "{\n" 395 " Foo() {}\n" 396 "\n" 397 " void funk() {}\n" 398 "};", 399 format("class Foo\n" 400 "{\n" 401 " Foo()\n" 402 " {\n" 403 " }\n" 404 "\n" 405 " void funk() {}\n" 406 "};", 407 Style)); 408 } 409 410 TEST_F(FormatTest, RecognizesBinaryOperatorKeywords) { 411 verifyFormat("x = (a) and (b);"); 412 verifyFormat("x = (a) or (b);"); 413 verifyFormat("x = (a) bitand (b);"); 414 verifyFormat("x = (a) bitor (b);"); 415 verifyFormat("x = (a) not_eq (b);"); 416 verifyFormat("x = (a) and_eq (b);"); 417 verifyFormat("x = (a) or_eq (b);"); 418 verifyFormat("x = (a) xor (b);"); 419 } 420 421 TEST_F(FormatTest, RecognizesUnaryOperatorKeywords) { 422 verifyFormat("x = compl(a);"); 423 verifyFormat("x = not(a);"); 424 verifyFormat("x = bitand(a);"); 425 // Unary operator must not be merged with the next identifier 426 verifyFormat("x = compl a;"); 427 verifyFormat("x = not a;"); 428 verifyFormat("x = bitand a;"); 429 } 430 431 //===----------------------------------------------------------------------===// 432 // Tests for control statements. 433 //===----------------------------------------------------------------------===// 434 435 TEST_F(FormatTest, FormatIfWithoutCompoundStatement) { 436 verifyFormat("if (true)\n f();\ng();"); 437 verifyFormat("if (a)\n if (b)\n if (c)\n g();\nh();"); 438 verifyFormat("if (a)\n if (b) {\n f();\n }\ng();"); 439 verifyFormat("if constexpr (true)\n" 440 " f();\ng();"); 441 verifyFormat("if CONSTEXPR (true)\n" 442 " f();\ng();"); 443 verifyFormat("if constexpr (a)\n" 444 " if constexpr (b)\n" 445 " if constexpr (c)\n" 446 " g();\n" 447 "h();"); 448 verifyFormat("if CONSTEXPR (a)\n" 449 " if CONSTEXPR (b)\n" 450 " if CONSTEXPR (c)\n" 451 " g();\n" 452 "h();"); 453 verifyFormat("if constexpr (a)\n" 454 " if constexpr (b) {\n" 455 " f();\n" 456 " }\n" 457 "g();"); 458 verifyFormat("if CONSTEXPR (a)\n" 459 " if CONSTEXPR (b) {\n" 460 " f();\n" 461 " }\n" 462 "g();"); 463 464 verifyFormat("if (a)\n" 465 " g();"); 466 verifyFormat("if (a) {\n" 467 " g()\n" 468 "};"); 469 verifyFormat("if (a)\n" 470 " g();\n" 471 "else\n" 472 " g();"); 473 verifyFormat("if (a) {\n" 474 " g();\n" 475 "} else\n" 476 " g();"); 477 verifyFormat("if (a)\n" 478 " g();\n" 479 "else {\n" 480 " g();\n" 481 "}"); 482 verifyFormat("if (a) {\n" 483 " g();\n" 484 "} else {\n" 485 " g();\n" 486 "}"); 487 verifyFormat("if (a)\n" 488 " g();\n" 489 "else if (b)\n" 490 " g();\n" 491 "else\n" 492 " g();"); 493 verifyFormat("if (a) {\n" 494 " g();\n" 495 "} else if (b)\n" 496 " g();\n" 497 "else\n" 498 " g();"); 499 verifyFormat("if (a)\n" 500 " g();\n" 501 "else if (b) {\n" 502 " g();\n" 503 "} else\n" 504 " g();"); 505 verifyFormat("if (a)\n" 506 " g();\n" 507 "else if (b)\n" 508 " g();\n" 509 "else {\n" 510 " g();\n" 511 "}"); 512 verifyFormat("if (a)\n" 513 " g();\n" 514 "else if (b) {\n" 515 " g();\n" 516 "} else {\n" 517 " g();\n" 518 "}"); 519 verifyFormat("if (a) {\n" 520 " g();\n" 521 "} else if (b) {\n" 522 " g();\n" 523 "} else {\n" 524 " g();\n" 525 "}"); 526 527 FormatStyle AllowsMergedIf = getLLVMStyle(); 528 AllowsMergedIf.AlignEscapedNewlines = FormatStyle::ENAS_Left; 529 AllowsMergedIf.AllowShortIfStatementsOnASingleLine = 530 FormatStyle::SIS_WithoutElse; 531 verifyFormat("if (a)\n" 532 " // comment\n" 533 " f();", 534 AllowsMergedIf); 535 verifyFormat("{\n" 536 " if (a)\n" 537 " label:\n" 538 " f();\n" 539 "}", 540 AllowsMergedIf); 541 verifyFormat("#define A \\\n" 542 " if (a) \\\n" 543 " label: \\\n" 544 " f()", 545 AllowsMergedIf); 546 verifyFormat("if (a)\n" 547 " ;", 548 AllowsMergedIf); 549 verifyFormat("if (a)\n" 550 " if (b) return;", 551 AllowsMergedIf); 552 553 verifyFormat("if (a) // Can't merge this\n" 554 " f();\n", 555 AllowsMergedIf); 556 verifyFormat("if (a) /* still don't merge */\n" 557 " f();", 558 AllowsMergedIf); 559 verifyFormat("if (a) { // Never merge this\n" 560 " f();\n" 561 "}", 562 AllowsMergedIf); 563 verifyFormat("if (a) { /* Never merge this */\n" 564 " f();\n" 565 "}", 566 AllowsMergedIf); 567 568 AllowsMergedIf.ColumnLimit = 14; 569 verifyFormat("if (a) return;", AllowsMergedIf); 570 verifyFormat("if (aaaaaaaaa)\n" 571 " return;", 572 AllowsMergedIf); 573 574 AllowsMergedIf.ColumnLimit = 13; 575 verifyFormat("if (a)\n return;", AllowsMergedIf); 576 577 FormatStyle AllowsMergedIfElse = getLLVMStyle(); 578 AllowsMergedIfElse.AllowShortIfStatementsOnASingleLine = 579 FormatStyle::SIS_AllIfsAndElse; 580 verifyFormat("if (a)\n" 581 " // comment\n" 582 " f();\n" 583 "else\n" 584 " // comment\n" 585 " f();", 586 AllowsMergedIfElse); 587 verifyFormat("{\n" 588 " if (a)\n" 589 " label:\n" 590 " f();\n" 591 " else\n" 592 " label:\n" 593 " f();\n" 594 "}", 595 AllowsMergedIfElse); 596 verifyFormat("if (a)\n" 597 " ;\n" 598 "else\n" 599 " ;", 600 AllowsMergedIfElse); 601 verifyFormat("if (a) {\n" 602 "} else {\n" 603 "}", 604 AllowsMergedIfElse); 605 verifyFormat("if (a) return;\n" 606 "else if (b) return;\n" 607 "else return;", 608 AllowsMergedIfElse); 609 verifyFormat("if (a) {\n" 610 "} else return;", 611 AllowsMergedIfElse); 612 verifyFormat("if (a) {\n" 613 "} else if (b) return;\n" 614 "else return;", 615 AllowsMergedIfElse); 616 verifyFormat("if (a) return;\n" 617 "else if (b) {\n" 618 "} else return;", 619 AllowsMergedIfElse); 620 verifyFormat("if (a)\n" 621 " if (b) return;\n" 622 " else return;", 623 AllowsMergedIfElse); 624 verifyFormat("if constexpr (a)\n" 625 " if constexpr (b) return;\n" 626 " else if constexpr (c) return;\n" 627 " else return;", 628 AllowsMergedIfElse); 629 } 630 631 TEST_F(FormatTest, FormatIfWithoutCompoundStatementButElseWith) { 632 FormatStyle AllowsMergedIf = getLLVMStyle(); 633 AllowsMergedIf.AlignEscapedNewlines = FormatStyle::ENAS_Left; 634 AllowsMergedIf.AllowShortIfStatementsOnASingleLine = 635 FormatStyle::SIS_WithoutElse; 636 verifyFormat("if (a)\n" 637 " f();\n" 638 "else {\n" 639 " g();\n" 640 "}", 641 AllowsMergedIf); 642 verifyFormat("if (a)\n" 643 " f();\n" 644 "else\n" 645 " g();\n", 646 AllowsMergedIf); 647 648 verifyFormat("if (a) g();", AllowsMergedIf); 649 verifyFormat("if (a) {\n" 650 " g()\n" 651 "};", 652 AllowsMergedIf); 653 verifyFormat("if (a)\n" 654 " g();\n" 655 "else\n" 656 " g();", 657 AllowsMergedIf); 658 verifyFormat("if (a) {\n" 659 " g();\n" 660 "} else\n" 661 " g();", 662 AllowsMergedIf); 663 verifyFormat("if (a)\n" 664 " g();\n" 665 "else {\n" 666 " g();\n" 667 "}", 668 AllowsMergedIf); 669 verifyFormat("if (a) {\n" 670 " g();\n" 671 "} else {\n" 672 " g();\n" 673 "}", 674 AllowsMergedIf); 675 verifyFormat("if (a)\n" 676 " g();\n" 677 "else if (b)\n" 678 " g();\n" 679 "else\n" 680 " g();", 681 AllowsMergedIf); 682 verifyFormat("if (a) {\n" 683 " g();\n" 684 "} else if (b)\n" 685 " g();\n" 686 "else\n" 687 " g();", 688 AllowsMergedIf); 689 verifyFormat("if (a)\n" 690 " g();\n" 691 "else if (b) {\n" 692 " g();\n" 693 "} else\n" 694 " g();", 695 AllowsMergedIf); 696 verifyFormat("if (a)\n" 697 " g();\n" 698 "else if (b)\n" 699 " g();\n" 700 "else {\n" 701 " g();\n" 702 "}", 703 AllowsMergedIf); 704 verifyFormat("if (a)\n" 705 " g();\n" 706 "else if (b) {\n" 707 " g();\n" 708 "} else {\n" 709 " g();\n" 710 "}", 711 AllowsMergedIf); 712 verifyFormat("if (a) {\n" 713 " g();\n" 714 "} else if (b) {\n" 715 " g();\n" 716 "} else {\n" 717 " g();\n" 718 "}", 719 AllowsMergedIf); 720 721 AllowsMergedIf.AllowShortIfStatementsOnASingleLine = 722 FormatStyle::SIS_OnlyFirstIf; 723 724 verifyFormat("if (a) f();\n" 725 "else {\n" 726 " g();\n" 727 "}", 728 AllowsMergedIf); 729 verifyFormat("if (a) f();\n" 730 "else {\n" 731 " if (a) f();\n" 732 " else {\n" 733 " g();\n" 734 " }\n" 735 " g();\n" 736 "}", 737 AllowsMergedIf); 738 739 verifyFormat("if (a) g();", AllowsMergedIf); 740 verifyFormat("if (a) {\n" 741 " g()\n" 742 "};", 743 AllowsMergedIf); 744 verifyFormat("if (a) g();\n" 745 "else\n" 746 " g();", 747 AllowsMergedIf); 748 verifyFormat("if (a) {\n" 749 " g();\n" 750 "} else\n" 751 " g();", 752 AllowsMergedIf); 753 verifyFormat("if (a) g();\n" 754 "else {\n" 755 " g();\n" 756 "}", 757 AllowsMergedIf); 758 verifyFormat("if (a) {\n" 759 " g();\n" 760 "} else {\n" 761 " g();\n" 762 "}", 763 AllowsMergedIf); 764 verifyFormat("if (a) g();\n" 765 "else if (b)\n" 766 " g();\n" 767 "else\n" 768 " g();", 769 AllowsMergedIf); 770 verifyFormat("if (a) {\n" 771 " g();\n" 772 "} else if (b)\n" 773 " g();\n" 774 "else\n" 775 " g();", 776 AllowsMergedIf); 777 verifyFormat("if (a) g();\n" 778 "else if (b) {\n" 779 " g();\n" 780 "} else\n" 781 " g();", 782 AllowsMergedIf); 783 verifyFormat("if (a) g();\n" 784 "else if (b)\n" 785 " g();\n" 786 "else {\n" 787 " g();\n" 788 "}", 789 AllowsMergedIf); 790 verifyFormat("if (a) g();\n" 791 "else if (b) {\n" 792 " g();\n" 793 "} else {\n" 794 " g();\n" 795 "}", 796 AllowsMergedIf); 797 verifyFormat("if (a) {\n" 798 " g();\n" 799 "} else if (b) {\n" 800 " g();\n" 801 "} else {\n" 802 " g();\n" 803 "}", 804 AllowsMergedIf); 805 806 AllowsMergedIf.AllowShortIfStatementsOnASingleLine = 807 FormatStyle::SIS_AllIfsAndElse; 808 809 verifyFormat("if (a) f();\n" 810 "else {\n" 811 " g();\n" 812 "}", 813 AllowsMergedIf); 814 verifyFormat("if (a) f();\n" 815 "else {\n" 816 " if (a) f();\n" 817 " else {\n" 818 " g();\n" 819 " }\n" 820 " g();\n" 821 "}", 822 AllowsMergedIf); 823 824 verifyFormat("if (a) g();", AllowsMergedIf); 825 verifyFormat("if (a) {\n" 826 " g()\n" 827 "};", 828 AllowsMergedIf); 829 verifyFormat("if (a) g();\n" 830 "else g();", 831 AllowsMergedIf); 832 verifyFormat("if (a) {\n" 833 " g();\n" 834 "} else g();", 835 AllowsMergedIf); 836 verifyFormat("if (a) g();\n" 837 "else {\n" 838 " g();\n" 839 "}", 840 AllowsMergedIf); 841 verifyFormat("if (a) {\n" 842 " g();\n" 843 "} else {\n" 844 " g();\n" 845 "}", 846 AllowsMergedIf); 847 verifyFormat("if (a) g();\n" 848 "else if (b) g();\n" 849 "else g();", 850 AllowsMergedIf); 851 verifyFormat("if (a) {\n" 852 " g();\n" 853 "} else if (b) g();\n" 854 "else g();", 855 AllowsMergedIf); 856 verifyFormat("if (a) g();\n" 857 "else if (b) {\n" 858 " g();\n" 859 "} else g();", 860 AllowsMergedIf); 861 verifyFormat("if (a) g();\n" 862 "else if (b) g();\n" 863 "else {\n" 864 " g();\n" 865 "}", 866 AllowsMergedIf); 867 verifyFormat("if (a) g();\n" 868 "else if (b) {\n" 869 " g();\n" 870 "} else {\n" 871 " g();\n" 872 "}", 873 AllowsMergedIf); 874 verifyFormat("if (a) {\n" 875 " g();\n" 876 "} else if (b) {\n" 877 " g();\n" 878 "} else {\n" 879 " g();\n" 880 "}", 881 AllowsMergedIf); 882 } 883 884 TEST_F(FormatTest, FormatLoopsWithoutCompoundStatement) { 885 FormatStyle AllowsMergedLoops = getLLVMStyle(); 886 AllowsMergedLoops.AllowShortLoopsOnASingleLine = true; 887 verifyFormat("while (true) continue;", AllowsMergedLoops); 888 verifyFormat("for (;;) continue;", AllowsMergedLoops); 889 verifyFormat("for (int &v : vec) v *= 2;", AllowsMergedLoops); 890 verifyFormat("while (true)\n" 891 " ;", 892 AllowsMergedLoops); 893 verifyFormat("for (;;)\n" 894 " ;", 895 AllowsMergedLoops); 896 verifyFormat("for (;;)\n" 897 " for (;;) continue;", 898 AllowsMergedLoops); 899 verifyFormat("for (;;) // Can't merge this\n" 900 " continue;", 901 AllowsMergedLoops); 902 verifyFormat("for (;;) /* still don't merge */\n" 903 " continue;", 904 AllowsMergedLoops); 905 verifyFormat("do a++;\n" 906 "while (true);", 907 AllowsMergedLoops); 908 verifyFormat("do /* Don't merge */\n" 909 " a++;\n" 910 "while (true);", 911 AllowsMergedLoops); 912 verifyFormat("do // Don't merge\n" 913 " a++;\n" 914 "while (true);", 915 AllowsMergedLoops); 916 verifyFormat("do\n" 917 " // Don't merge\n" 918 " a++;\n" 919 "while (true);", 920 AllowsMergedLoops); 921 // Without braces labels are interpreted differently. 922 verifyFormat("{\n" 923 " do\n" 924 " label:\n" 925 " a++;\n" 926 " while (true);\n" 927 "}", 928 AllowsMergedLoops); 929 } 930 931 TEST_F(FormatTest, FormatShortBracedStatements) { 932 FormatStyle AllowSimpleBracedStatements = getLLVMStyle(); 933 AllowSimpleBracedStatements.ColumnLimit = 40; 934 AllowSimpleBracedStatements.AllowShortBlocksOnASingleLine = 935 FormatStyle::SBS_Always; 936 937 AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine = 938 FormatStyle::SIS_WithoutElse; 939 AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = true; 940 941 AllowSimpleBracedStatements.BreakBeforeBraces = FormatStyle::BS_Custom; 942 AllowSimpleBracedStatements.BraceWrapping.AfterFunction = true; 943 AllowSimpleBracedStatements.BraceWrapping.SplitEmptyRecord = false; 944 945 verifyFormat("if (true) {}", AllowSimpleBracedStatements); 946 verifyFormat("if constexpr (true) {}", AllowSimpleBracedStatements); 947 verifyFormat("if CONSTEXPR (true) {}", AllowSimpleBracedStatements); 948 verifyFormat("while (true) {}", AllowSimpleBracedStatements); 949 verifyFormat("for (;;) {}", AllowSimpleBracedStatements); 950 verifyFormat("if (true) { f(); }", AllowSimpleBracedStatements); 951 verifyFormat("if constexpr (true) { f(); }", AllowSimpleBracedStatements); 952 verifyFormat("if CONSTEXPR (true) { f(); }", AllowSimpleBracedStatements); 953 verifyFormat("while (true) { f(); }", AllowSimpleBracedStatements); 954 verifyFormat("for (;;) { f(); }", AllowSimpleBracedStatements); 955 verifyFormat("if (true) { fffffffffffffffffffffff(); }", 956 AllowSimpleBracedStatements); 957 verifyFormat("if (true) {\n" 958 " ffffffffffffffffffffffff();\n" 959 "}", 960 AllowSimpleBracedStatements); 961 verifyFormat("if (true) {\n" 962 " ffffffffffffffffffffffffffffffffffffffffffffffffffffff();\n" 963 "}", 964 AllowSimpleBracedStatements); 965 verifyFormat("if (true) { //\n" 966 " f();\n" 967 "}", 968 AllowSimpleBracedStatements); 969 verifyFormat("if (true) {\n" 970 " f();\n" 971 " f();\n" 972 "}", 973 AllowSimpleBracedStatements); 974 verifyFormat("if (true) {\n" 975 " f();\n" 976 "} else {\n" 977 " f();\n" 978 "}", 979 AllowSimpleBracedStatements); 980 981 verifyFormat("struct A2 {\n" 982 " int X;\n" 983 "};", 984 AllowSimpleBracedStatements); 985 verifyFormat("typedef struct A2 {\n" 986 " int X;\n" 987 "} A2_t;", 988 AllowSimpleBracedStatements); 989 verifyFormat("template <int> struct A2 {\n" 990 " struct B {};\n" 991 "};", 992 AllowSimpleBracedStatements); 993 994 AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine = 995 FormatStyle::SIS_Never; 996 verifyFormat("if (true) {}", AllowSimpleBracedStatements); 997 verifyFormat("if (true) {\n" 998 " f();\n" 999 "}", 1000 AllowSimpleBracedStatements); 1001 verifyFormat("if (true) {\n" 1002 " f();\n" 1003 "} else {\n" 1004 " f();\n" 1005 "}", 1006 AllowSimpleBracedStatements); 1007 1008 AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = false; 1009 verifyFormat("while (true) {}", AllowSimpleBracedStatements); 1010 verifyFormat("while (true) {\n" 1011 " f();\n" 1012 "}", 1013 AllowSimpleBracedStatements); 1014 verifyFormat("for (;;) {}", AllowSimpleBracedStatements); 1015 verifyFormat("for (;;) {\n" 1016 " f();\n" 1017 "}", 1018 AllowSimpleBracedStatements); 1019 1020 AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine = 1021 FormatStyle::SIS_WithoutElse; 1022 AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = true; 1023 AllowSimpleBracedStatements.BraceWrapping.AfterControlStatement = 1024 FormatStyle::BWACS_Always; 1025 1026 verifyFormat("if (true) {}", AllowSimpleBracedStatements); 1027 verifyFormat("if constexpr (true) {}", AllowSimpleBracedStatements); 1028 verifyFormat("if CONSTEXPR (true) {}", AllowSimpleBracedStatements); 1029 verifyFormat("while (true) {}", AllowSimpleBracedStatements); 1030 verifyFormat("for (;;) {}", AllowSimpleBracedStatements); 1031 verifyFormat("if (true) { f(); }", AllowSimpleBracedStatements); 1032 verifyFormat("if constexpr (true) { f(); }", AllowSimpleBracedStatements); 1033 verifyFormat("if CONSTEXPR (true) { f(); }", AllowSimpleBracedStatements); 1034 verifyFormat("while (true) { f(); }", AllowSimpleBracedStatements); 1035 verifyFormat("for (;;) { f(); }", AllowSimpleBracedStatements); 1036 verifyFormat("if (true) { fffffffffffffffffffffff(); }", 1037 AllowSimpleBracedStatements); 1038 verifyFormat("if (true)\n" 1039 "{\n" 1040 " ffffffffffffffffffffffff();\n" 1041 "}", 1042 AllowSimpleBracedStatements); 1043 verifyFormat("if (true)\n" 1044 "{\n" 1045 " ffffffffffffffffffffffffffffffffffffffffffffffffffffff();\n" 1046 "}", 1047 AllowSimpleBracedStatements); 1048 verifyFormat("if (true)\n" 1049 "{ //\n" 1050 " f();\n" 1051 "}", 1052 AllowSimpleBracedStatements); 1053 verifyFormat("if (true)\n" 1054 "{\n" 1055 " f();\n" 1056 " f();\n" 1057 "}", 1058 AllowSimpleBracedStatements); 1059 verifyFormat("if (true)\n" 1060 "{\n" 1061 " f();\n" 1062 "} else\n" 1063 "{\n" 1064 " f();\n" 1065 "}", 1066 AllowSimpleBracedStatements); 1067 1068 AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine = 1069 FormatStyle::SIS_Never; 1070 verifyFormat("if (true) {}", AllowSimpleBracedStatements); 1071 verifyFormat("if (true)\n" 1072 "{\n" 1073 " f();\n" 1074 "}", 1075 AllowSimpleBracedStatements); 1076 verifyFormat("if (true)\n" 1077 "{\n" 1078 " f();\n" 1079 "} else\n" 1080 "{\n" 1081 " f();\n" 1082 "}", 1083 AllowSimpleBracedStatements); 1084 1085 AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = false; 1086 verifyFormat("while (true) {}", AllowSimpleBracedStatements); 1087 verifyFormat("while (true)\n" 1088 "{\n" 1089 " f();\n" 1090 "}", 1091 AllowSimpleBracedStatements); 1092 verifyFormat("for (;;) {}", AllowSimpleBracedStatements); 1093 verifyFormat("for (;;)\n" 1094 "{\n" 1095 " f();\n" 1096 "}", 1097 AllowSimpleBracedStatements); 1098 } 1099 1100 TEST_F(FormatTest, ShortBlocksInMacrosDontMergeWithCodeAfterMacro) { 1101 FormatStyle Style = getLLVMStyleWithColumns(60); 1102 Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always; 1103 Style.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_WithoutElse; 1104 Style.BreakBeforeBraces = FormatStyle::BS_Allman; 1105 EXPECT_EQ("#define A \\\n" 1106 " if (HANDLEwernufrnuLwrmviferuvnierv) \\\n" 1107 " { \\\n" 1108 " RET_ERR1_ANUIREUINERUIFNIOAerwfwrvnuier; \\\n" 1109 " }\n" 1110 "X;", 1111 format("#define A \\\n" 1112 " if (HANDLEwernufrnuLwrmviferuvnierv) { \\\n" 1113 " RET_ERR1_ANUIREUINERUIFNIOAerwfwrvnuier; \\\n" 1114 " }\n" 1115 "X;", 1116 Style)); 1117 } 1118 1119 TEST_F(FormatTest, ParseIfElse) { 1120 verifyFormat("if (true)\n" 1121 " if (true)\n" 1122 " if (true)\n" 1123 " f();\n" 1124 " else\n" 1125 " g();\n" 1126 " else\n" 1127 " h();\n" 1128 "else\n" 1129 " i();"); 1130 verifyFormat("if (true)\n" 1131 " if (true)\n" 1132 " if (true) {\n" 1133 " if (true)\n" 1134 " f();\n" 1135 " } else {\n" 1136 " g();\n" 1137 " }\n" 1138 " else\n" 1139 " h();\n" 1140 "else {\n" 1141 " i();\n" 1142 "}"); 1143 verifyFormat("if (true)\n" 1144 " if constexpr (true)\n" 1145 " if (true) {\n" 1146 " if constexpr (true)\n" 1147 " f();\n" 1148 " } else {\n" 1149 " g();\n" 1150 " }\n" 1151 " else\n" 1152 " h();\n" 1153 "else {\n" 1154 " i();\n" 1155 "}"); 1156 verifyFormat("if (true)\n" 1157 " if CONSTEXPR (true)\n" 1158 " if (true) {\n" 1159 " if CONSTEXPR (true)\n" 1160 " f();\n" 1161 " } else {\n" 1162 " g();\n" 1163 " }\n" 1164 " else\n" 1165 " h();\n" 1166 "else {\n" 1167 " i();\n" 1168 "}"); 1169 verifyFormat("void f() {\n" 1170 " if (a) {\n" 1171 " } else {\n" 1172 " }\n" 1173 "}"); 1174 } 1175 1176 TEST_F(FormatTest, ElseIf) { 1177 verifyFormat("if (a) {\n} else if (b) {\n}"); 1178 verifyFormat("if (a)\n" 1179 " f();\n" 1180 "else if (b)\n" 1181 " g();\n" 1182 "else\n" 1183 " h();"); 1184 verifyFormat("if constexpr (a)\n" 1185 " f();\n" 1186 "else if constexpr (b)\n" 1187 " g();\n" 1188 "else\n" 1189 " h();"); 1190 verifyFormat("if CONSTEXPR (a)\n" 1191 " f();\n" 1192 "else if CONSTEXPR (b)\n" 1193 " g();\n" 1194 "else\n" 1195 " h();"); 1196 verifyFormat("if (a) {\n" 1197 " f();\n" 1198 "}\n" 1199 "// or else ..\n" 1200 "else {\n" 1201 " g()\n" 1202 "}"); 1203 1204 verifyFormat("if (a) {\n" 1205 "} else if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 1206 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n" 1207 "}"); 1208 verifyFormat("if (a) {\n" 1209 "} else if constexpr (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 1210 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n" 1211 "}"); 1212 verifyFormat("if (a) {\n" 1213 "} else if CONSTEXPR (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 1214 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n" 1215 "}"); 1216 verifyFormat("if (a) {\n" 1217 "} else if (\n" 1218 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n" 1219 "}", 1220 getLLVMStyleWithColumns(62)); 1221 verifyFormat("if (a) {\n" 1222 "} else if constexpr (\n" 1223 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n" 1224 "}", 1225 getLLVMStyleWithColumns(62)); 1226 verifyFormat("if (a) {\n" 1227 "} else if CONSTEXPR (\n" 1228 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n" 1229 "}", 1230 getLLVMStyleWithColumns(62)); 1231 } 1232 1233 TEST_F(FormatTest, FormatsForLoop) { 1234 verifyFormat( 1235 "for (int VeryVeryLongLoopVariable = 0; VeryVeryLongLoopVariable < 10;\n" 1236 " ++VeryVeryLongLoopVariable)\n" 1237 " ;"); 1238 verifyFormat("for (;;)\n" 1239 " f();"); 1240 verifyFormat("for (;;) {\n}"); 1241 verifyFormat("for (;;) {\n" 1242 " f();\n" 1243 "}"); 1244 verifyFormat("for (int i = 0; (i < 10); ++i) {\n}"); 1245 1246 verifyFormat( 1247 "for (std::vector<UnwrappedLine>::iterator I = UnwrappedLines.begin(),\n" 1248 " E = UnwrappedLines.end();\n" 1249 " I != E; ++I) {\n}"); 1250 1251 verifyFormat( 1252 "for (MachineFun::iterator IIII = PrevIt, EEEE = F.end(); IIII != EEEE;\n" 1253 " ++IIIII) {\n}"); 1254 verifyFormat("for (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaa =\n" 1255 " aaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa;\n" 1256 " aaaaaaaaaaa != aaaaaaaaaaaaaaaaaaa; ++aaaaaaaaaaa) {\n}"); 1257 verifyFormat("for (llvm::ArrayRef<NamedDecl *>::iterator\n" 1258 " I = FD->getDeclsInPrototypeScope().begin(),\n" 1259 " E = FD->getDeclsInPrototypeScope().end();\n" 1260 " I != E; ++I) {\n}"); 1261 verifyFormat("for (SmallVectorImpl<TemplateIdAnnotationn *>::iterator\n" 1262 " I = Container.begin(),\n" 1263 " E = Container.end();\n" 1264 " I != E; ++I) {\n}", 1265 getLLVMStyleWithColumns(76)); 1266 1267 verifyFormat( 1268 "for (aaaaaaaaaaaaaaaaa aaaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;\n" 1269 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa !=\n" 1270 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 1271 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n" 1272 " ++aaaaaaaaaaa) {\n}"); 1273 verifyFormat("for (int i = 0; i < aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n" 1274 " bbbbbbbbbbbbbbbbbbbb < ccccccccccccccc;\n" 1275 " ++i) {\n}"); 1276 verifyFormat("for (int aaaaaaaaaaa = 1; aaaaaaaaaaa <= bbbbbbbbbbbbbbb;\n" 1277 " aaaaaaaaaaa++, bbbbbbbbbbbbbbbbb++) {\n" 1278 "}"); 1279 verifyFormat("for (some_namespace::SomeIterator iter( // force break\n" 1280 " aaaaaaaaaa);\n" 1281 " iter; ++iter) {\n" 1282 "}"); 1283 verifyFormat("for (auto aaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 1284 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n" 1285 " aaaaaaaaaaaaaaaaaaaaaaaaaaa != bbbbbbbbbbbbbbbbbbbbbbb;\n" 1286 " ++aaaaaaaaaaaaaaaaaaaaaaaaaaa) {"); 1287 1288 // These should not be formatted as Objective-C for-in loops. 1289 verifyFormat("for (Foo *x = 0; x != in; x++) {\n}"); 1290 verifyFormat("Foo *x;\nfor (x = 0; x != in; x++) {\n}"); 1291 verifyFormat("Foo *x;\nfor (x in y) {\n}"); 1292 verifyFormat( 1293 "for (const Foo<Bar> &baz = in.value(); !baz.at_end(); ++baz) {\n}"); 1294 1295 FormatStyle NoBinPacking = getLLVMStyle(); 1296 NoBinPacking.BinPackParameters = false; 1297 verifyFormat("for (int aaaaaaaaaaa = 1;\n" 1298 " aaaaaaaaaaa <= aaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaa,\n" 1299 " aaaaaaaaaaaaaaaa,\n" 1300 " aaaaaaaaaaaaaaaa,\n" 1301 " aaaaaaaaaaaaaaaa);\n" 1302 " aaaaaaaaaaa++, bbbbbbbbbbbbbbbbb++) {\n" 1303 "}", 1304 NoBinPacking); 1305 verifyFormat( 1306 "for (std::vector<UnwrappedLine>::iterator I = UnwrappedLines.begin(),\n" 1307 " E = UnwrappedLines.end();\n" 1308 " I != E;\n" 1309 " ++I) {\n}", 1310 NoBinPacking); 1311 1312 FormatStyle AlignLeft = getLLVMStyle(); 1313 AlignLeft.PointerAlignment = FormatStyle::PAS_Left; 1314 verifyFormat("for (A* a = start; a < end; ++a, ++value) {\n}", AlignLeft); 1315 } 1316 1317 TEST_F(FormatTest, RangeBasedForLoops) { 1318 verifyFormat("for (auto aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n" 1319 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}"); 1320 verifyFormat("for (auto aaaaaaaaaaaaaaaaaaaaa :\n" 1321 " aaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaa, aaaaaaaaaaaaa)) {\n}"); 1322 verifyFormat("for (const aaaaaaaaaaaaaaaaaaaaa &aaaaaaaaa :\n" 1323 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}"); 1324 verifyFormat("for (aaaaaaaaa aaaaaaaaaaaaaaaaaaaaa :\n" 1325 " aaaaaaaaaaaa.aaaaaaaaaaaa().aaaaaaaaa().a()) {\n}"); 1326 } 1327 1328 TEST_F(FormatTest, ForEachLoops) { 1329 verifyFormat("void f() {\n" 1330 " foreach (Item *item, itemlist) {}\n" 1331 " Q_FOREACH (Item *item, itemlist) {}\n" 1332 " BOOST_FOREACH (Item *item, itemlist) {}\n" 1333 " UNKNOWN_FORACH(Item * item, itemlist) {}\n" 1334 "}"); 1335 1336 FormatStyle Style = getLLVMStyle(); 1337 Style.SpaceBeforeParens = 1338 FormatStyle::SBPO_ControlStatementsExceptForEachMacros; 1339 verifyFormat("void f() {\n" 1340 " foreach(Item *item, itemlist) {}\n" 1341 " Q_FOREACH(Item *item, itemlist) {}\n" 1342 " BOOST_FOREACH(Item *item, itemlist) {}\n" 1343 " UNKNOWN_FORACH(Item * item, itemlist) {}\n" 1344 "}", 1345 Style); 1346 1347 // As function-like macros. 1348 verifyFormat("#define foreach(x, y)\n" 1349 "#define Q_FOREACH(x, y)\n" 1350 "#define BOOST_FOREACH(x, y)\n" 1351 "#define UNKNOWN_FOREACH(x, y)\n"); 1352 1353 // Not as function-like macros. 1354 verifyFormat("#define foreach (x, y)\n" 1355 "#define Q_FOREACH (x, y)\n" 1356 "#define BOOST_FOREACH (x, y)\n" 1357 "#define UNKNOWN_FOREACH (x, y)\n"); 1358 1359 // handle microsoft non standard extension 1360 verifyFormat("for each (char c in x->MyStringProperty)"); 1361 } 1362 1363 TEST_F(FormatTest, FormatsWhileLoop) { 1364 verifyFormat("while (true) {\n}"); 1365 verifyFormat("while (true)\n" 1366 " f();"); 1367 verifyFormat("while () {\n}"); 1368 verifyFormat("while () {\n" 1369 " f();\n" 1370 "}"); 1371 } 1372 1373 TEST_F(FormatTest, FormatsDoWhile) { 1374 verifyFormat("do {\n" 1375 " do_something();\n" 1376 "} while (something());"); 1377 verifyFormat("do\n" 1378 " do_something();\n" 1379 "while (something());"); 1380 } 1381 1382 TEST_F(FormatTest, FormatsSwitchStatement) { 1383 verifyFormat("switch (x) {\n" 1384 "case 1:\n" 1385 " f();\n" 1386 " break;\n" 1387 "case kFoo:\n" 1388 "case ns::kBar:\n" 1389 "case kBaz:\n" 1390 " break;\n" 1391 "default:\n" 1392 " g();\n" 1393 " break;\n" 1394 "}"); 1395 verifyFormat("switch (x) {\n" 1396 "case 1: {\n" 1397 " f();\n" 1398 " break;\n" 1399 "}\n" 1400 "case 2: {\n" 1401 " break;\n" 1402 "}\n" 1403 "}"); 1404 verifyFormat("switch (x) {\n" 1405 "case 1: {\n" 1406 " f();\n" 1407 " {\n" 1408 " g();\n" 1409 " h();\n" 1410 " }\n" 1411 " break;\n" 1412 "}\n" 1413 "}"); 1414 verifyFormat("switch (x) {\n" 1415 "case 1: {\n" 1416 " f();\n" 1417 " if (foo) {\n" 1418 " g();\n" 1419 " h();\n" 1420 " }\n" 1421 " break;\n" 1422 "}\n" 1423 "}"); 1424 verifyFormat("switch (x) {\n" 1425 "case 1: {\n" 1426 " f();\n" 1427 " g();\n" 1428 "} break;\n" 1429 "}"); 1430 verifyFormat("switch (test)\n" 1431 " ;"); 1432 verifyFormat("switch (x) {\n" 1433 "default: {\n" 1434 " // Do nothing.\n" 1435 "}\n" 1436 "}"); 1437 verifyFormat("switch (x) {\n" 1438 "// comment\n" 1439 "// if 1, do f()\n" 1440 "case 1:\n" 1441 " f();\n" 1442 "}"); 1443 verifyFormat("switch (x) {\n" 1444 "case 1:\n" 1445 " // Do amazing stuff\n" 1446 " {\n" 1447 " f();\n" 1448 " g();\n" 1449 " }\n" 1450 " break;\n" 1451 "}"); 1452 verifyFormat("#define A \\\n" 1453 " switch (x) { \\\n" 1454 " case a: \\\n" 1455 " foo = b; \\\n" 1456 " }", 1457 getLLVMStyleWithColumns(20)); 1458 verifyFormat("#define OPERATION_CASE(name) \\\n" 1459 " case OP_name: \\\n" 1460 " return operations::Operation##name\n", 1461 getLLVMStyleWithColumns(40)); 1462 verifyFormat("switch (x) {\n" 1463 "case 1:;\n" 1464 "default:;\n" 1465 " int i;\n" 1466 "}"); 1467 1468 verifyGoogleFormat("switch (x) {\n" 1469 " case 1:\n" 1470 " f();\n" 1471 " break;\n" 1472 " case kFoo:\n" 1473 " case ns::kBar:\n" 1474 " case kBaz:\n" 1475 " break;\n" 1476 " default:\n" 1477 " g();\n" 1478 " break;\n" 1479 "}"); 1480 verifyGoogleFormat("switch (x) {\n" 1481 " case 1: {\n" 1482 " f();\n" 1483 " break;\n" 1484 " }\n" 1485 "}"); 1486 verifyGoogleFormat("switch (test)\n" 1487 " ;"); 1488 1489 verifyGoogleFormat("#define OPERATION_CASE(name) \\\n" 1490 " case OP_name: \\\n" 1491 " return operations::Operation##name\n"); 1492 verifyGoogleFormat("Operation codeToOperation(OperationCode OpCode) {\n" 1493 " // Get the correction operation class.\n" 1494 " switch (OpCode) {\n" 1495 " CASE(Add);\n" 1496 " CASE(Subtract);\n" 1497 " default:\n" 1498 " return operations::Unknown;\n" 1499 " }\n" 1500 "#undef OPERATION_CASE\n" 1501 "}"); 1502 verifyFormat("DEBUG({\n" 1503 " switch (x) {\n" 1504 " case A:\n" 1505 " f();\n" 1506 " break;\n" 1507 " // fallthrough\n" 1508 " case B:\n" 1509 " g();\n" 1510 " break;\n" 1511 " }\n" 1512 "});"); 1513 EXPECT_EQ("DEBUG({\n" 1514 " switch (x) {\n" 1515 " case A:\n" 1516 " f();\n" 1517 " break;\n" 1518 " // On B:\n" 1519 " case B:\n" 1520 " g();\n" 1521 " break;\n" 1522 " }\n" 1523 "});", 1524 format("DEBUG({\n" 1525 " switch (x) {\n" 1526 " case A:\n" 1527 " f();\n" 1528 " break;\n" 1529 " // On B:\n" 1530 " case B:\n" 1531 " g();\n" 1532 " break;\n" 1533 " }\n" 1534 "});", 1535 getLLVMStyle())); 1536 EXPECT_EQ("switch (n) {\n" 1537 "case 0: {\n" 1538 " return false;\n" 1539 "}\n" 1540 "default: {\n" 1541 " return true;\n" 1542 "}\n" 1543 "}", 1544 format("switch (n)\n" 1545 "{\n" 1546 "case 0: {\n" 1547 " return false;\n" 1548 "}\n" 1549 "default: {\n" 1550 " return true;\n" 1551 "}\n" 1552 "}", 1553 getLLVMStyle())); 1554 verifyFormat("switch (a) {\n" 1555 "case (b):\n" 1556 " return;\n" 1557 "}"); 1558 1559 verifyFormat("switch (a) {\n" 1560 "case some_namespace::\n" 1561 " some_constant:\n" 1562 " return;\n" 1563 "}", 1564 getLLVMStyleWithColumns(34)); 1565 1566 FormatStyle Style = getLLVMStyle(); 1567 Style.IndentCaseLabels = true; 1568 Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Never; 1569 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 1570 Style.BraceWrapping.AfterCaseLabel = true; 1571 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always; 1572 EXPECT_EQ("switch (n)\n" 1573 "{\n" 1574 " case 0:\n" 1575 " {\n" 1576 " return false;\n" 1577 " }\n" 1578 " default:\n" 1579 " {\n" 1580 " return true;\n" 1581 " }\n" 1582 "}", 1583 format("switch (n) {\n" 1584 " case 0: {\n" 1585 " return false;\n" 1586 " }\n" 1587 " default: {\n" 1588 " return true;\n" 1589 " }\n" 1590 "}", 1591 Style)); 1592 Style.BraceWrapping.AfterCaseLabel = false; 1593 EXPECT_EQ("switch (n)\n" 1594 "{\n" 1595 " case 0: {\n" 1596 " return false;\n" 1597 " }\n" 1598 " default: {\n" 1599 " return true;\n" 1600 " }\n" 1601 "}", 1602 format("switch (n) {\n" 1603 " case 0:\n" 1604 " {\n" 1605 " return false;\n" 1606 " }\n" 1607 " default:\n" 1608 " {\n" 1609 " return true;\n" 1610 " }\n" 1611 "}", 1612 Style)); 1613 Style.IndentCaseLabels = false; 1614 Style.IndentCaseBlocks = true; 1615 EXPECT_EQ("switch (n)\n" 1616 "{\n" 1617 "case 0:\n" 1618 " {\n" 1619 " return false;\n" 1620 " }\n" 1621 "case 1:\n" 1622 " break;\n" 1623 "default:\n" 1624 " {\n" 1625 " return true;\n" 1626 " }\n" 1627 "}", 1628 format("switch (n) {\n" 1629 "case 0: {\n" 1630 " return false;\n" 1631 "}\n" 1632 "case 1:\n" 1633 " break;\n" 1634 "default: {\n" 1635 " return true;\n" 1636 "}\n" 1637 "}", 1638 Style)); 1639 Style.IndentCaseLabels = true; 1640 Style.IndentCaseBlocks = true; 1641 EXPECT_EQ("switch (n)\n" 1642 "{\n" 1643 " case 0:\n" 1644 " {\n" 1645 " return false;\n" 1646 " }\n" 1647 " case 1:\n" 1648 " break;\n" 1649 " default:\n" 1650 " {\n" 1651 " return true;\n" 1652 " }\n" 1653 "}", 1654 format("switch (n) {\n" 1655 "case 0: {\n" 1656 " return false;\n" 1657 "}\n" 1658 "case 1:\n" 1659 " break;\n" 1660 "default: {\n" 1661 " return true;\n" 1662 "}\n" 1663 "}", 1664 Style)); 1665 } 1666 1667 TEST_F(FormatTest, CaseRanges) { 1668 verifyFormat("switch (x) {\n" 1669 "case 'A' ... 'Z':\n" 1670 "case 1 ... 5:\n" 1671 "case a ... b:\n" 1672 " break;\n" 1673 "}"); 1674 } 1675 1676 TEST_F(FormatTest, ShortEnums) { 1677 FormatStyle Style = getLLVMStyle(); 1678 Style.AllowShortEnumsOnASingleLine = true; 1679 verifyFormat("enum { A, B, C } ShortEnum1, ShortEnum2;", Style); 1680 Style.AllowShortEnumsOnASingleLine = false; 1681 verifyFormat("enum\n" 1682 "{\n" 1683 " A,\n" 1684 " B,\n" 1685 " C\n" 1686 "} ShortEnum1, ShortEnum2;", 1687 Style); 1688 } 1689 1690 TEST_F(FormatTest, ShortCaseLabels) { 1691 FormatStyle Style = getLLVMStyle(); 1692 Style.AllowShortCaseLabelsOnASingleLine = true; 1693 verifyFormat("switch (a) {\n" 1694 "case 1: x = 1; break;\n" 1695 "case 2: return;\n" 1696 "case 3:\n" 1697 "case 4:\n" 1698 "case 5: return;\n" 1699 "case 6: // comment\n" 1700 " return;\n" 1701 "case 7:\n" 1702 " // comment\n" 1703 " return;\n" 1704 "case 8:\n" 1705 " x = 8; // comment\n" 1706 " break;\n" 1707 "default: y = 1; break;\n" 1708 "}", 1709 Style); 1710 verifyFormat("switch (a) {\n" 1711 "case 0: return; // comment\n" 1712 "case 1: break; // comment\n" 1713 "case 2: return;\n" 1714 "// comment\n" 1715 "case 3: return;\n" 1716 "// comment 1\n" 1717 "// comment 2\n" 1718 "// comment 3\n" 1719 "case 4: break; /* comment */\n" 1720 "case 5:\n" 1721 " // comment\n" 1722 " break;\n" 1723 "case 6: /* comment */ x = 1; break;\n" 1724 "case 7: x = /* comment */ 1; break;\n" 1725 "case 8:\n" 1726 " x = 1; /* comment */\n" 1727 " break;\n" 1728 "case 9:\n" 1729 " break; // comment line 1\n" 1730 " // comment line 2\n" 1731 "}", 1732 Style); 1733 EXPECT_EQ("switch (a) {\n" 1734 "case 1:\n" 1735 " x = 8;\n" 1736 " // fall through\n" 1737 "case 2: x = 8;\n" 1738 "// comment\n" 1739 "case 3:\n" 1740 " return; /* comment line 1\n" 1741 " * comment line 2 */\n" 1742 "case 4: i = 8;\n" 1743 "// something else\n" 1744 "#if FOO\n" 1745 "case 5: break;\n" 1746 "#endif\n" 1747 "}", 1748 format("switch (a) {\n" 1749 "case 1: x = 8;\n" 1750 " // fall through\n" 1751 "case 2:\n" 1752 " x = 8;\n" 1753 "// comment\n" 1754 "case 3:\n" 1755 " return; /* comment line 1\n" 1756 " * comment line 2 */\n" 1757 "case 4:\n" 1758 " i = 8;\n" 1759 "// something else\n" 1760 "#if FOO\n" 1761 "case 5: break;\n" 1762 "#endif\n" 1763 "}", 1764 Style)); 1765 EXPECT_EQ("switch (a) {\n" 1766 "case 0:\n" 1767 " return; // long long long long long long long long long long " 1768 "long long comment\n" 1769 " // line\n" 1770 "}", 1771 format("switch (a) {\n" 1772 "case 0: return; // long long long long long long long long " 1773 "long long long long comment line\n" 1774 "}", 1775 Style)); 1776 EXPECT_EQ("switch (a) {\n" 1777 "case 0:\n" 1778 " return; /* long long long long long long long long long long " 1779 "long long comment\n" 1780 " line */\n" 1781 "}", 1782 format("switch (a) {\n" 1783 "case 0: return; /* long long long long long long long long " 1784 "long long long long comment line */\n" 1785 "}", 1786 Style)); 1787 verifyFormat("switch (a) {\n" 1788 "#if FOO\n" 1789 "case 0: return 0;\n" 1790 "#endif\n" 1791 "}", 1792 Style); 1793 verifyFormat("switch (a) {\n" 1794 "case 1: {\n" 1795 "}\n" 1796 "case 2: {\n" 1797 " return;\n" 1798 "}\n" 1799 "case 3: {\n" 1800 " x = 1;\n" 1801 " return;\n" 1802 "}\n" 1803 "case 4:\n" 1804 " if (x)\n" 1805 " return;\n" 1806 "}", 1807 Style); 1808 Style.ColumnLimit = 21; 1809 verifyFormat("switch (a) {\n" 1810 "case 1: x = 1; break;\n" 1811 "case 2: return;\n" 1812 "case 3:\n" 1813 "case 4:\n" 1814 "case 5: return;\n" 1815 "default:\n" 1816 " y = 1;\n" 1817 " break;\n" 1818 "}", 1819 Style); 1820 Style.ColumnLimit = 80; 1821 Style.AllowShortCaseLabelsOnASingleLine = false; 1822 Style.IndentCaseLabels = true; 1823 EXPECT_EQ("switch (n) {\n" 1824 " default /*comments*/:\n" 1825 " return true;\n" 1826 " case 0:\n" 1827 " return false;\n" 1828 "}", 1829 format("switch (n) {\n" 1830 "default/*comments*/:\n" 1831 " return true;\n" 1832 "case 0:\n" 1833 " return false;\n" 1834 "}", 1835 Style)); 1836 Style.AllowShortCaseLabelsOnASingleLine = true; 1837 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 1838 Style.BraceWrapping.AfterCaseLabel = true; 1839 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always; 1840 EXPECT_EQ("switch (n)\n" 1841 "{\n" 1842 " case 0:\n" 1843 " {\n" 1844 " return false;\n" 1845 " }\n" 1846 " default:\n" 1847 " {\n" 1848 " return true;\n" 1849 " }\n" 1850 "}", 1851 format("switch (n) {\n" 1852 " case 0: {\n" 1853 " return false;\n" 1854 " }\n" 1855 " default:\n" 1856 " {\n" 1857 " return true;\n" 1858 " }\n" 1859 "}", 1860 Style)); 1861 } 1862 1863 TEST_F(FormatTest, FormatsLabels) { 1864 verifyFormat("void f() {\n" 1865 " some_code();\n" 1866 "test_label:\n" 1867 " some_other_code();\n" 1868 " {\n" 1869 " some_more_code();\n" 1870 " another_label:\n" 1871 " some_more_code();\n" 1872 " }\n" 1873 "}"); 1874 verifyFormat("{\n" 1875 " some_code();\n" 1876 "test_label:\n" 1877 " some_other_code();\n" 1878 "}"); 1879 verifyFormat("{\n" 1880 " some_code();\n" 1881 "test_label:;\n" 1882 " int i = 0;\n" 1883 "}"); 1884 FormatStyle Style = getLLVMStyle(); 1885 Style.IndentGotoLabels = false; 1886 verifyFormat("void f() {\n" 1887 " some_code();\n" 1888 "test_label:\n" 1889 " some_other_code();\n" 1890 " {\n" 1891 " some_more_code();\n" 1892 "another_label:\n" 1893 " some_more_code();\n" 1894 " }\n" 1895 "}", 1896 Style); 1897 verifyFormat("{\n" 1898 " some_code();\n" 1899 "test_label:\n" 1900 " some_other_code();\n" 1901 "}", 1902 Style); 1903 verifyFormat("{\n" 1904 " some_code();\n" 1905 "test_label:;\n" 1906 " int i = 0;\n" 1907 "}"); 1908 } 1909 1910 TEST_F(FormatTest, MultiLineControlStatements) { 1911 FormatStyle Style = getLLVMStyle(); 1912 Style.BreakBeforeBraces = FormatStyle::BraceBreakingStyle::BS_Custom; 1913 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_MultiLine; 1914 Style.ColumnLimit = 20; 1915 // Short lines should keep opening brace on same line. 1916 EXPECT_EQ("if (foo) {\n" 1917 " bar();\n" 1918 "}", 1919 format("if(foo){bar();}", Style)); 1920 EXPECT_EQ("if (foo) {\n" 1921 " bar();\n" 1922 "} else {\n" 1923 " baz();\n" 1924 "}", 1925 format("if(foo){bar();}else{baz();}", Style)); 1926 EXPECT_EQ("if (foo && bar) {\n" 1927 " baz();\n" 1928 "}", 1929 format("if(foo&&bar){baz();}", Style)); 1930 EXPECT_EQ("if (foo) {\n" 1931 " bar();\n" 1932 "} else if (baz) {\n" 1933 " quux();\n" 1934 "}", 1935 format("if(foo){bar();}else if(baz){quux();}", Style)); 1936 EXPECT_EQ( 1937 "if (foo) {\n" 1938 " bar();\n" 1939 "} else if (baz) {\n" 1940 " quux();\n" 1941 "} else {\n" 1942 " foobar();\n" 1943 "}", 1944 format("if(foo){bar();}else if(baz){quux();}else{foobar();}", Style)); 1945 EXPECT_EQ("for (;;) {\n" 1946 " foo();\n" 1947 "}", 1948 format("for(;;){foo();}")); 1949 EXPECT_EQ("while (1) {\n" 1950 " foo();\n" 1951 "}", 1952 format("while(1){foo();}", Style)); 1953 EXPECT_EQ("switch (foo) {\n" 1954 "case bar:\n" 1955 " return;\n" 1956 "}", 1957 format("switch(foo){case bar:return;}", Style)); 1958 EXPECT_EQ("try {\n" 1959 " foo();\n" 1960 "} catch (...) {\n" 1961 " bar();\n" 1962 "}", 1963 format("try{foo();}catch(...){bar();}", Style)); 1964 EXPECT_EQ("do {\n" 1965 " foo();\n" 1966 "} while (bar &&\n" 1967 " baz);", 1968 format("do{foo();}while(bar&&baz);", Style)); 1969 // Long lines should put opening brace on new line. 1970 EXPECT_EQ("if (foo && bar &&\n" 1971 " baz)\n" 1972 "{\n" 1973 " quux();\n" 1974 "}", 1975 format("if(foo&&bar&&baz){quux();}", Style)); 1976 EXPECT_EQ("if (foo && bar &&\n" 1977 " baz)\n" 1978 "{\n" 1979 " quux();\n" 1980 "}", 1981 format("if (foo && bar &&\n" 1982 " baz) {\n" 1983 " quux();\n" 1984 "}", 1985 Style)); 1986 EXPECT_EQ("if (foo) {\n" 1987 " bar();\n" 1988 "} else if (baz ||\n" 1989 " quux)\n" 1990 "{\n" 1991 " foobar();\n" 1992 "}", 1993 format("if(foo){bar();}else if(baz||quux){foobar();}", Style)); 1994 EXPECT_EQ( 1995 "if (foo) {\n" 1996 " bar();\n" 1997 "} else if (baz ||\n" 1998 " quux)\n" 1999 "{\n" 2000 " foobar();\n" 2001 "} else {\n" 2002 " barbaz();\n" 2003 "}", 2004 format("if(foo){bar();}else if(baz||quux){foobar();}else{barbaz();}", 2005 Style)); 2006 EXPECT_EQ("for (int i = 0;\n" 2007 " i < 10; ++i)\n" 2008 "{\n" 2009 " foo();\n" 2010 "}", 2011 format("for(int i=0;i<10;++i){foo();}", Style)); 2012 EXPECT_EQ("foreach (int i,\n" 2013 " list)\n" 2014 "{\n" 2015 " foo();\n" 2016 "}", 2017 format("foreach(int i, list){foo();}", Style)); 2018 Style.ColumnLimit = 2019 40; // to concentrate at brace wrapping, not line wrap due to column limit 2020 EXPECT_EQ("foreach (int i, list) {\n" 2021 " foo();\n" 2022 "}", 2023 format("foreach(int i, list){foo();}", Style)); 2024 Style.ColumnLimit = 2025 20; // to concentrate at brace wrapping, not line wrap due to column limit 2026 EXPECT_EQ("while (foo || bar ||\n" 2027 " baz)\n" 2028 "{\n" 2029 " quux();\n" 2030 "}", 2031 format("while(foo||bar||baz){quux();}", Style)); 2032 EXPECT_EQ("switch (\n" 2033 " foo = barbaz)\n" 2034 "{\n" 2035 "case quux:\n" 2036 " return;\n" 2037 "}", 2038 format("switch(foo=barbaz){case quux:return;}", Style)); 2039 EXPECT_EQ("try {\n" 2040 " foo();\n" 2041 "} catch (\n" 2042 " Exception &bar)\n" 2043 "{\n" 2044 " baz();\n" 2045 "}", 2046 format("try{foo();}catch(Exception&bar){baz();}", Style)); 2047 Style.ColumnLimit = 2048 40; // to concentrate at brace wrapping, not line wrap due to column limit 2049 EXPECT_EQ("try {\n" 2050 " foo();\n" 2051 "} catch (Exception &bar) {\n" 2052 " baz();\n" 2053 "}", 2054 format("try{foo();}catch(Exception&bar){baz();}", Style)); 2055 Style.ColumnLimit = 2056 20; // to concentrate at brace wrapping, not line wrap due to column limit 2057 2058 Style.BraceWrapping.BeforeElse = true; 2059 EXPECT_EQ( 2060 "if (foo) {\n" 2061 " bar();\n" 2062 "}\n" 2063 "else if (baz ||\n" 2064 " quux)\n" 2065 "{\n" 2066 " foobar();\n" 2067 "}\n" 2068 "else {\n" 2069 " barbaz();\n" 2070 "}", 2071 format("if(foo){bar();}else if(baz||quux){foobar();}else{barbaz();}", 2072 Style)); 2073 2074 Style.BraceWrapping.BeforeCatch = true; 2075 EXPECT_EQ("try {\n" 2076 " foo();\n" 2077 "}\n" 2078 "catch (...) {\n" 2079 " baz();\n" 2080 "}", 2081 format("try{foo();}catch(...){baz();}", Style)); 2082 } 2083 2084 TEST_F(FormatTest, BeforeWhile) { 2085 FormatStyle Style = getLLVMStyle(); 2086 Style.BreakBeforeBraces = FormatStyle::BraceBreakingStyle::BS_Custom; 2087 2088 verifyFormat("do {\n" 2089 " foo();\n" 2090 "} while (1);", 2091 Style); 2092 Style.BraceWrapping.BeforeWhile = true; 2093 verifyFormat("do {\n" 2094 " foo();\n" 2095 "}\n" 2096 "while (1);", 2097 Style); 2098 } 2099 2100 //===----------------------------------------------------------------------===// 2101 // Tests for classes, namespaces, etc. 2102 //===----------------------------------------------------------------------===// 2103 2104 TEST_F(FormatTest, DoesNotBreakSemiAfterClassDecl) { 2105 verifyFormat("class A {};"); 2106 } 2107 2108 TEST_F(FormatTest, UnderstandsAccessSpecifiers) { 2109 verifyFormat("class A {\n" 2110 "public:\n" 2111 "public: // comment\n" 2112 "protected:\n" 2113 "private:\n" 2114 " void f() {}\n" 2115 "};"); 2116 verifyFormat("export class A {\n" 2117 "public:\n" 2118 "public: // comment\n" 2119 "protected:\n" 2120 "private:\n" 2121 " void f() {}\n" 2122 "};"); 2123 verifyGoogleFormat("class A {\n" 2124 " public:\n" 2125 " protected:\n" 2126 " private:\n" 2127 " void f() {}\n" 2128 "};"); 2129 verifyGoogleFormat("export class A {\n" 2130 " public:\n" 2131 " protected:\n" 2132 " private:\n" 2133 " void f() {}\n" 2134 "};"); 2135 verifyFormat("class A {\n" 2136 "public slots:\n" 2137 " void f1() {}\n" 2138 "public Q_SLOTS:\n" 2139 " void f2() {}\n" 2140 "protected slots:\n" 2141 " void f3() {}\n" 2142 "protected Q_SLOTS:\n" 2143 " void f4() {}\n" 2144 "private slots:\n" 2145 " void f5() {}\n" 2146 "private Q_SLOTS:\n" 2147 " void f6() {}\n" 2148 "signals:\n" 2149 " void g1();\n" 2150 "Q_SIGNALS:\n" 2151 " void g2();\n" 2152 "};"); 2153 2154 // Don't interpret 'signals' the wrong way. 2155 verifyFormat("signals.set();"); 2156 verifyFormat("for (Signals signals : f()) {\n}"); 2157 verifyFormat("{\n" 2158 " signals.set(); // This needs indentation.\n" 2159 "}"); 2160 verifyFormat("void f() {\n" 2161 "label:\n" 2162 " signals.baz();\n" 2163 "}"); 2164 } 2165 2166 TEST_F(FormatTest, SeparatesLogicalBlocks) { 2167 EXPECT_EQ("class A {\n" 2168 "public:\n" 2169 " void f();\n" 2170 "\n" 2171 "private:\n" 2172 " void g() {}\n" 2173 " // test\n" 2174 "protected:\n" 2175 " int h;\n" 2176 "};", 2177 format("class A {\n" 2178 "public:\n" 2179 "void f();\n" 2180 "private:\n" 2181 "void g() {}\n" 2182 "// test\n" 2183 "protected:\n" 2184 "int h;\n" 2185 "};")); 2186 EXPECT_EQ("class A {\n" 2187 "protected:\n" 2188 "public:\n" 2189 " void f();\n" 2190 "};", 2191 format("class A {\n" 2192 "protected:\n" 2193 "\n" 2194 "public:\n" 2195 "\n" 2196 " void f();\n" 2197 "};")); 2198 2199 // Even ensure proper spacing inside macros. 2200 EXPECT_EQ("#define B \\\n" 2201 " class A { \\\n" 2202 " protected: \\\n" 2203 " public: \\\n" 2204 " void f(); \\\n" 2205 " };", 2206 format("#define B \\\n" 2207 " class A { \\\n" 2208 " protected: \\\n" 2209 " \\\n" 2210 " public: \\\n" 2211 " \\\n" 2212 " void f(); \\\n" 2213 " };", 2214 getGoogleStyle())); 2215 // But don't remove empty lines after macros ending in access specifiers. 2216 EXPECT_EQ("#define A private:\n" 2217 "\n" 2218 "int i;", 2219 format("#define A private:\n" 2220 "\n" 2221 "int i;")); 2222 } 2223 2224 TEST_F(FormatTest, FormatsClasses) { 2225 verifyFormat("class A : public B {};"); 2226 verifyFormat("class A : public ::B {};"); 2227 2228 verifyFormat( 2229 "class AAAAAAAAAAAAAAAAAAAA : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n" 2230 " public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};"); 2231 verifyFormat("class AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\n" 2232 " : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n" 2233 " public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};"); 2234 verifyFormat( 2235 "class A : public B, public C, public D, public E, public F {};"); 2236 verifyFormat("class AAAAAAAAAAAA : public B,\n" 2237 " public C,\n" 2238 " public D,\n" 2239 " public E,\n" 2240 " public F,\n" 2241 " public G {};"); 2242 2243 verifyFormat("class\n" 2244 " ReallyReallyLongClassName {\n" 2245 " int i;\n" 2246 "};", 2247 getLLVMStyleWithColumns(32)); 2248 verifyFormat("struct aaaaaaaaaaaaa : public aaaaaaaaaaaaaaaaaaa< // break\n" 2249 " aaaaaaaaaaaaaaaa> {};"); 2250 verifyFormat("struct aaaaaaaaaaaaaaaaaaaa\n" 2251 " : public aaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaa,\n" 2252 " aaaaaaaaaaaaaaaaaaaaaa> {};"); 2253 verifyFormat("template <class R, class C>\n" 2254 "struct Aaaaaaaaaaaaaaaaa<R (C::*)(int) const>\n" 2255 " : Aaaaaaaaaaaaaaaaa<R (C::*)(int)> {};"); 2256 verifyFormat("class ::A::B {};"); 2257 } 2258 2259 TEST_F(FormatTest, BreakInheritanceStyle) { 2260 FormatStyle StyleWithInheritanceBreakBeforeComma = getLLVMStyle(); 2261 StyleWithInheritanceBreakBeforeComma.BreakInheritanceList = 2262 FormatStyle::BILS_BeforeComma; 2263 verifyFormat("class MyClass : public X {};", 2264 StyleWithInheritanceBreakBeforeComma); 2265 verifyFormat("class MyClass\n" 2266 " : public X\n" 2267 " , public Y {};", 2268 StyleWithInheritanceBreakBeforeComma); 2269 verifyFormat("class AAAAAAAAAAAAAAAAAAAAAA\n" 2270 " : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB\n" 2271 " , public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};", 2272 StyleWithInheritanceBreakBeforeComma); 2273 verifyFormat("struct aaaaaaaaaaaaa\n" 2274 " : public aaaaaaaaaaaaaaaaaaa< // break\n" 2275 " aaaaaaaaaaaaaaaa> {};", 2276 StyleWithInheritanceBreakBeforeComma); 2277 2278 FormatStyle StyleWithInheritanceBreakAfterColon = getLLVMStyle(); 2279 StyleWithInheritanceBreakAfterColon.BreakInheritanceList = 2280 FormatStyle::BILS_AfterColon; 2281 verifyFormat("class MyClass : public X {};", 2282 StyleWithInheritanceBreakAfterColon); 2283 verifyFormat("class MyClass : public X, public Y {};", 2284 StyleWithInheritanceBreakAfterColon); 2285 verifyFormat("class AAAAAAAAAAAAAAAAAAAAAA :\n" 2286 " public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n" 2287 " public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};", 2288 StyleWithInheritanceBreakAfterColon); 2289 verifyFormat("struct aaaaaaaaaaaaa :\n" 2290 " public aaaaaaaaaaaaaaaaaaa< // break\n" 2291 " aaaaaaaaaaaaaaaa> {};", 2292 StyleWithInheritanceBreakAfterColon); 2293 } 2294 2295 TEST_F(FormatTest, FormatsVariableDeclarationsAfterStructOrClass) { 2296 verifyFormat("class A {\n} a, b;"); 2297 verifyFormat("struct A {\n} a, b;"); 2298 verifyFormat("union A {\n} a;"); 2299 } 2300 2301 TEST_F(FormatTest, FormatsEnum) { 2302 verifyFormat("enum {\n" 2303 " Zero,\n" 2304 " One = 1,\n" 2305 " Two = One + 1,\n" 2306 " Three = (One + Two),\n" 2307 " Four = (Zero && (One ^ Two)) | (One << Two),\n" 2308 " Five = (One, Two, Three, Four, 5)\n" 2309 "};"); 2310 verifyGoogleFormat("enum {\n" 2311 " Zero,\n" 2312 " One = 1,\n" 2313 " Two = One + 1,\n" 2314 " Three = (One + Two),\n" 2315 " Four = (Zero && (One ^ Two)) | (One << Two),\n" 2316 " Five = (One, Two, Three, Four, 5)\n" 2317 "};"); 2318 verifyFormat("enum Enum {};"); 2319 verifyFormat("enum {};"); 2320 verifyFormat("enum X E {} d;"); 2321 verifyFormat("enum __attribute__((...)) E {} d;"); 2322 verifyFormat("enum __declspec__((...)) E {} d;"); 2323 verifyFormat("enum {\n" 2324 " Bar = Foo<int, int>::value\n" 2325 "};", 2326 getLLVMStyleWithColumns(30)); 2327 2328 verifyFormat("enum ShortEnum { A, B, C };"); 2329 verifyGoogleFormat("enum ShortEnum { A, B, C };"); 2330 2331 EXPECT_EQ("enum KeepEmptyLines {\n" 2332 " ONE,\n" 2333 "\n" 2334 " TWO,\n" 2335 "\n" 2336 " THREE\n" 2337 "}", 2338 format("enum KeepEmptyLines {\n" 2339 " ONE,\n" 2340 "\n" 2341 " TWO,\n" 2342 "\n" 2343 "\n" 2344 " THREE\n" 2345 "}")); 2346 verifyFormat("enum E { // comment\n" 2347 " ONE,\n" 2348 " TWO\n" 2349 "};\n" 2350 "int i;"); 2351 2352 FormatStyle EightIndent = getLLVMStyle(); 2353 EightIndent.IndentWidth = 8; 2354 verifyFormat("enum {\n" 2355 " VOID,\n" 2356 " CHAR,\n" 2357 " SHORT,\n" 2358 " INT,\n" 2359 " LONG,\n" 2360 " SIGNED,\n" 2361 " UNSIGNED,\n" 2362 " BOOL,\n" 2363 " FLOAT,\n" 2364 " DOUBLE,\n" 2365 " COMPLEX\n" 2366 "};", 2367 EightIndent); 2368 2369 // Not enums. 2370 verifyFormat("enum X f() {\n" 2371 " a();\n" 2372 " return 42;\n" 2373 "}"); 2374 verifyFormat("enum X Type::f() {\n" 2375 " a();\n" 2376 " return 42;\n" 2377 "}"); 2378 verifyFormat("enum ::X f() {\n" 2379 " a();\n" 2380 " return 42;\n" 2381 "}"); 2382 verifyFormat("enum ns::X f() {\n" 2383 " a();\n" 2384 " return 42;\n" 2385 "}"); 2386 } 2387 2388 TEST_F(FormatTest, FormatsEnumsWithErrors) { 2389 verifyFormat("enum Type {\n" 2390 " One = 0; // These semicolons should be commas.\n" 2391 " Two = 1;\n" 2392 "};"); 2393 verifyFormat("namespace n {\n" 2394 "enum Type {\n" 2395 " One,\n" 2396 " Two, // missing };\n" 2397 " int i;\n" 2398 "}\n" 2399 "void g() {}"); 2400 } 2401 2402 TEST_F(FormatTest, FormatsEnumStruct) { 2403 verifyFormat("enum struct {\n" 2404 " Zero,\n" 2405 " One = 1,\n" 2406 " Two = One + 1,\n" 2407 " Three = (One + Two),\n" 2408 " Four = (Zero && (One ^ Two)) | (One << Two),\n" 2409 " Five = (One, Two, Three, Four, 5)\n" 2410 "};"); 2411 verifyFormat("enum struct Enum {};"); 2412 verifyFormat("enum struct {};"); 2413 verifyFormat("enum struct X E {} d;"); 2414 verifyFormat("enum struct __attribute__((...)) E {} d;"); 2415 verifyFormat("enum struct __declspec__((...)) E {} d;"); 2416 verifyFormat("enum struct X f() {\n a();\n return 42;\n}"); 2417 } 2418 2419 TEST_F(FormatTest, FormatsEnumClass) { 2420 verifyFormat("enum class {\n" 2421 " Zero,\n" 2422 " One = 1,\n" 2423 " Two = One + 1,\n" 2424 " Three = (One + Two),\n" 2425 " Four = (Zero && (One ^ Two)) | (One << Two),\n" 2426 " Five = (One, Two, Three, Four, 5)\n" 2427 "};"); 2428 verifyFormat("enum class Enum {};"); 2429 verifyFormat("enum class {};"); 2430 verifyFormat("enum class X E {} d;"); 2431 verifyFormat("enum class __attribute__((...)) E {} d;"); 2432 verifyFormat("enum class __declspec__((...)) E {} d;"); 2433 verifyFormat("enum class X f() {\n a();\n return 42;\n}"); 2434 } 2435 2436 TEST_F(FormatTest, FormatsEnumTypes) { 2437 verifyFormat("enum X : int {\n" 2438 " A, // Force multiple lines.\n" 2439 " B\n" 2440 "};"); 2441 verifyFormat("enum X : int { A, B };"); 2442 verifyFormat("enum X : std::uint32_t { A, B };"); 2443 } 2444 2445 TEST_F(FormatTest, FormatsTypedefEnum) { 2446 FormatStyle Style = getLLVMStyle(); 2447 Style.ColumnLimit = 40; 2448 verifyFormat("typedef enum {} EmptyEnum;"); 2449 verifyFormat("typedef enum { A, B, C } ShortEnum;"); 2450 verifyFormat("typedef enum {\n" 2451 " ZERO = 0,\n" 2452 " ONE = 1,\n" 2453 " TWO = 2,\n" 2454 " THREE = 3\n" 2455 "} LongEnum;", 2456 Style); 2457 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 2458 Style.BraceWrapping.AfterEnum = true; 2459 verifyFormat("typedef enum {} EmptyEnum;"); 2460 verifyFormat("typedef enum { A, B, C } ShortEnum;"); 2461 verifyFormat("typedef enum\n" 2462 "{\n" 2463 " ZERO = 0,\n" 2464 " ONE = 1,\n" 2465 " TWO = 2,\n" 2466 " THREE = 3\n" 2467 "} LongEnum;", 2468 Style); 2469 } 2470 2471 TEST_F(FormatTest, FormatsNSEnums) { 2472 verifyGoogleFormat("typedef NS_ENUM(NSInteger, SomeName) { AAA, BBB }"); 2473 verifyGoogleFormat( 2474 "typedef NS_CLOSED_ENUM(NSInteger, SomeName) { AAA, BBB }"); 2475 verifyGoogleFormat("typedef NS_ENUM(NSInteger, MyType) {\n" 2476 " // Information about someDecentlyLongValue.\n" 2477 " someDecentlyLongValue,\n" 2478 " // Information about anotherDecentlyLongValue.\n" 2479 " anotherDecentlyLongValue,\n" 2480 " // Information about aThirdDecentlyLongValue.\n" 2481 " aThirdDecentlyLongValue\n" 2482 "};"); 2483 verifyGoogleFormat("typedef NS_CLOSED_ENUM(NSInteger, MyType) {\n" 2484 " // Information about someDecentlyLongValue.\n" 2485 " someDecentlyLongValue,\n" 2486 " // Information about anotherDecentlyLongValue.\n" 2487 " anotherDecentlyLongValue,\n" 2488 " // Information about aThirdDecentlyLongValue.\n" 2489 " aThirdDecentlyLongValue\n" 2490 "};"); 2491 verifyGoogleFormat("typedef NS_OPTIONS(NSInteger, MyType) {\n" 2492 " a = 1,\n" 2493 " b = 2,\n" 2494 " c = 3,\n" 2495 "};"); 2496 verifyGoogleFormat("typedef CF_ENUM(NSInteger, MyType) {\n" 2497 " a = 1,\n" 2498 " b = 2,\n" 2499 " c = 3,\n" 2500 "};"); 2501 verifyGoogleFormat("typedef CF_CLOSED_ENUM(NSInteger, MyType) {\n" 2502 " a = 1,\n" 2503 " b = 2,\n" 2504 " c = 3,\n" 2505 "};"); 2506 verifyGoogleFormat("typedef CF_OPTIONS(NSInteger, MyType) {\n" 2507 " a = 1,\n" 2508 " b = 2,\n" 2509 " c = 3,\n" 2510 "};"); 2511 } 2512 2513 TEST_F(FormatTest, FormatsBitfields) { 2514 verifyFormat("struct Bitfields {\n" 2515 " unsigned sClass : 8;\n" 2516 " unsigned ValueKind : 2;\n" 2517 "};"); 2518 verifyFormat("struct A {\n" 2519 " int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa : 1,\n" 2520 " bbbbbbbbbbbbbbbbbbbbbbbbb;\n" 2521 "};"); 2522 verifyFormat("struct MyStruct {\n" 2523 " uchar data;\n" 2524 " uchar : 8;\n" 2525 " uchar : 8;\n" 2526 " uchar other;\n" 2527 "};"); 2528 FormatStyle Style = getLLVMStyle(); 2529 Style.BitFieldColonSpacing = FormatStyle::BFCS_None; 2530 verifyFormat("struct Bitfields {\n" 2531 " unsigned sClass:8;\n" 2532 " unsigned ValueKind:2;\n" 2533 " uchar other;\n" 2534 "};", 2535 Style); 2536 verifyFormat("struct A {\n" 2537 " int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa:1,\n" 2538 " bbbbbbbbbbbbbbbbbbbbbbbbb:2;\n" 2539 "};", 2540 Style); 2541 Style.BitFieldColonSpacing = FormatStyle::BFCS_Before; 2542 verifyFormat("struct Bitfields {\n" 2543 " unsigned sClass :8;\n" 2544 " unsigned ValueKind :2;\n" 2545 " uchar other;\n" 2546 "};", 2547 Style); 2548 Style.BitFieldColonSpacing = FormatStyle::BFCS_After; 2549 verifyFormat("struct Bitfields {\n" 2550 " unsigned sClass: 8;\n" 2551 " unsigned ValueKind: 2;\n" 2552 " uchar other;\n" 2553 "};", 2554 Style); 2555 } 2556 2557 TEST_F(FormatTest, FormatsNamespaces) { 2558 FormatStyle LLVMWithNoNamespaceFix = getLLVMStyle(); 2559 LLVMWithNoNamespaceFix.FixNamespaceComments = false; 2560 2561 verifyFormat("namespace some_namespace {\n" 2562 "class A {};\n" 2563 "void f() { f(); }\n" 2564 "}", 2565 LLVMWithNoNamespaceFix); 2566 verifyFormat("namespace N::inline D {\n" 2567 "class A {};\n" 2568 "void f() { f(); }\n" 2569 "}", 2570 LLVMWithNoNamespaceFix); 2571 verifyFormat("namespace N::inline D::E {\n" 2572 "class A {};\n" 2573 "void f() { f(); }\n" 2574 "}", 2575 LLVMWithNoNamespaceFix); 2576 verifyFormat("namespace [[deprecated(\"foo[bar\")]] some_namespace {\n" 2577 "class A {};\n" 2578 "void f() { f(); }\n" 2579 "}", 2580 LLVMWithNoNamespaceFix); 2581 verifyFormat("/* something */ namespace some_namespace {\n" 2582 "class A {};\n" 2583 "void f() { f(); }\n" 2584 "}", 2585 LLVMWithNoNamespaceFix); 2586 verifyFormat("namespace {\n" 2587 "class A {};\n" 2588 "void f() { f(); }\n" 2589 "}", 2590 LLVMWithNoNamespaceFix); 2591 verifyFormat("/* something */ namespace {\n" 2592 "class A {};\n" 2593 "void f() { f(); }\n" 2594 "}", 2595 LLVMWithNoNamespaceFix); 2596 verifyFormat("inline namespace X {\n" 2597 "class A {};\n" 2598 "void f() { f(); }\n" 2599 "}", 2600 LLVMWithNoNamespaceFix); 2601 verifyFormat("/* something */ inline namespace X {\n" 2602 "class A {};\n" 2603 "void f() { f(); }\n" 2604 "}", 2605 LLVMWithNoNamespaceFix); 2606 verifyFormat("export namespace X {\n" 2607 "class A {};\n" 2608 "void f() { f(); }\n" 2609 "}", 2610 LLVMWithNoNamespaceFix); 2611 verifyFormat("using namespace some_namespace;\n" 2612 "class A {};\n" 2613 "void f() { f(); }", 2614 LLVMWithNoNamespaceFix); 2615 2616 // This code is more common than we thought; if we 2617 // layout this correctly the semicolon will go into 2618 // its own line, which is undesirable. 2619 verifyFormat("namespace {};", LLVMWithNoNamespaceFix); 2620 verifyFormat("namespace {\n" 2621 "class A {};\n" 2622 "};", 2623 LLVMWithNoNamespaceFix); 2624 2625 verifyFormat("namespace {\n" 2626 "int SomeVariable = 0; // comment\n" 2627 "} // namespace", 2628 LLVMWithNoNamespaceFix); 2629 EXPECT_EQ("#ifndef HEADER_GUARD\n" 2630 "#define HEADER_GUARD\n" 2631 "namespace my_namespace {\n" 2632 "int i;\n" 2633 "} // my_namespace\n" 2634 "#endif // HEADER_GUARD", 2635 format("#ifndef HEADER_GUARD\n" 2636 " #define HEADER_GUARD\n" 2637 " namespace my_namespace {\n" 2638 "int i;\n" 2639 "} // my_namespace\n" 2640 "#endif // HEADER_GUARD", 2641 LLVMWithNoNamespaceFix)); 2642 2643 EXPECT_EQ("namespace A::B {\n" 2644 "class C {};\n" 2645 "}", 2646 format("namespace A::B {\n" 2647 "class C {};\n" 2648 "}", 2649 LLVMWithNoNamespaceFix)); 2650 2651 FormatStyle Style = getLLVMStyle(); 2652 Style.NamespaceIndentation = FormatStyle::NI_All; 2653 EXPECT_EQ("namespace out {\n" 2654 " int i;\n" 2655 " namespace in {\n" 2656 " int i;\n" 2657 " } // namespace in\n" 2658 "} // namespace out", 2659 format("namespace out {\n" 2660 "int i;\n" 2661 "namespace in {\n" 2662 "int i;\n" 2663 "} // namespace in\n" 2664 "} // namespace out", 2665 Style)); 2666 2667 Style.NamespaceIndentation = FormatStyle::NI_Inner; 2668 EXPECT_EQ("namespace out {\n" 2669 "int i;\n" 2670 "namespace in {\n" 2671 " int i;\n" 2672 "} // namespace in\n" 2673 "} // namespace out", 2674 format("namespace out {\n" 2675 "int i;\n" 2676 "namespace in {\n" 2677 "int i;\n" 2678 "} // namespace in\n" 2679 "} // namespace out", 2680 Style)); 2681 } 2682 2683 TEST_F(FormatTest, NamespaceMacros) { 2684 FormatStyle Style = getLLVMStyle(); 2685 Style.NamespaceMacros.push_back("TESTSUITE"); 2686 2687 verifyFormat("TESTSUITE(A) {\n" 2688 "int foo();\n" 2689 "} // TESTSUITE(A)", 2690 Style); 2691 2692 verifyFormat("TESTSUITE(A, B) {\n" 2693 "int foo();\n" 2694 "} // TESTSUITE(A)", 2695 Style); 2696 2697 // Properly indent according to NamespaceIndentation style 2698 Style.NamespaceIndentation = FormatStyle::NI_All; 2699 verifyFormat("TESTSUITE(A) {\n" 2700 " int foo();\n" 2701 "} // TESTSUITE(A)", 2702 Style); 2703 verifyFormat("TESTSUITE(A) {\n" 2704 " namespace B {\n" 2705 " int foo();\n" 2706 " } // namespace B\n" 2707 "} // TESTSUITE(A)", 2708 Style); 2709 verifyFormat("namespace A {\n" 2710 " TESTSUITE(B) {\n" 2711 " int foo();\n" 2712 " } // TESTSUITE(B)\n" 2713 "} // namespace A", 2714 Style); 2715 2716 Style.NamespaceIndentation = FormatStyle::NI_Inner; 2717 verifyFormat("TESTSUITE(A) {\n" 2718 "TESTSUITE(B) {\n" 2719 " int foo();\n" 2720 "} // TESTSUITE(B)\n" 2721 "} // TESTSUITE(A)", 2722 Style); 2723 verifyFormat("TESTSUITE(A) {\n" 2724 "namespace B {\n" 2725 " int foo();\n" 2726 "} // namespace B\n" 2727 "} // TESTSUITE(A)", 2728 Style); 2729 verifyFormat("namespace A {\n" 2730 "TESTSUITE(B) {\n" 2731 " int foo();\n" 2732 "} // TESTSUITE(B)\n" 2733 "} // namespace A", 2734 Style); 2735 2736 // Properly merge namespace-macros blocks in CompactNamespaces mode 2737 Style.NamespaceIndentation = FormatStyle::NI_None; 2738 Style.CompactNamespaces = true; 2739 verifyFormat("TESTSUITE(A) { TESTSUITE(B) {\n" 2740 "}} // TESTSUITE(A::B)", 2741 Style); 2742 2743 EXPECT_EQ("TESTSUITE(out) { TESTSUITE(in) {\n" 2744 "}} // TESTSUITE(out::in)", 2745 format("TESTSUITE(out) {\n" 2746 "TESTSUITE(in) {\n" 2747 "} // TESTSUITE(in)\n" 2748 "} // TESTSUITE(out)", 2749 Style)); 2750 2751 EXPECT_EQ("TESTSUITE(out) { TESTSUITE(in) {\n" 2752 "}} // TESTSUITE(out::in)", 2753 format("TESTSUITE(out) {\n" 2754 "TESTSUITE(in) {\n" 2755 "} // TESTSUITE(in)\n" 2756 "} // TESTSUITE(out)", 2757 Style)); 2758 2759 // Do not merge different namespaces/macros 2760 EXPECT_EQ("namespace out {\n" 2761 "TESTSUITE(in) {\n" 2762 "} // TESTSUITE(in)\n" 2763 "} // namespace out", 2764 format("namespace out {\n" 2765 "TESTSUITE(in) {\n" 2766 "} // TESTSUITE(in)\n" 2767 "} // namespace out", 2768 Style)); 2769 EXPECT_EQ("TESTSUITE(out) {\n" 2770 "namespace in {\n" 2771 "} // namespace in\n" 2772 "} // TESTSUITE(out)", 2773 format("TESTSUITE(out) {\n" 2774 "namespace in {\n" 2775 "} // namespace in\n" 2776 "} // TESTSUITE(out)", 2777 Style)); 2778 Style.NamespaceMacros.push_back("FOOBAR"); 2779 EXPECT_EQ("TESTSUITE(out) {\n" 2780 "FOOBAR(in) {\n" 2781 "} // FOOBAR(in)\n" 2782 "} // TESTSUITE(out)", 2783 format("TESTSUITE(out) {\n" 2784 "FOOBAR(in) {\n" 2785 "} // FOOBAR(in)\n" 2786 "} // TESTSUITE(out)", 2787 Style)); 2788 } 2789 2790 TEST_F(FormatTest, FormatsCompactNamespaces) { 2791 FormatStyle Style = getLLVMStyle(); 2792 Style.CompactNamespaces = true; 2793 Style.NamespaceMacros.push_back("TESTSUITE"); 2794 2795 verifyFormat("namespace A { namespace B {\n" 2796 "}} // namespace A::B", 2797 Style); 2798 2799 EXPECT_EQ("namespace out { namespace in {\n" 2800 "}} // namespace out::in", 2801 format("namespace out {\n" 2802 "namespace in {\n" 2803 "} // namespace in\n" 2804 "} // namespace out", 2805 Style)); 2806 2807 // Only namespaces which have both consecutive opening and end get compacted 2808 EXPECT_EQ("namespace out {\n" 2809 "namespace in1 {\n" 2810 "} // namespace in1\n" 2811 "namespace in2 {\n" 2812 "} // namespace in2\n" 2813 "} // namespace out", 2814 format("namespace out {\n" 2815 "namespace in1 {\n" 2816 "} // namespace in1\n" 2817 "namespace in2 {\n" 2818 "} // namespace in2\n" 2819 "} // namespace out", 2820 Style)); 2821 2822 EXPECT_EQ("namespace out {\n" 2823 "int i;\n" 2824 "namespace in {\n" 2825 "int j;\n" 2826 "} // namespace in\n" 2827 "int k;\n" 2828 "} // namespace out", 2829 format("namespace out { int i;\n" 2830 "namespace in { int j; } // namespace in\n" 2831 "int k; } // namespace out", 2832 Style)); 2833 2834 EXPECT_EQ("namespace A { namespace B { namespace C {\n" 2835 "}}} // namespace A::B::C\n", 2836 format("namespace A { namespace B {\n" 2837 "namespace C {\n" 2838 "}} // namespace B::C\n" 2839 "} // namespace A\n", 2840 Style)); 2841 2842 Style.ColumnLimit = 40; 2843 EXPECT_EQ("namespace aaaaaaaaaa {\n" 2844 "namespace bbbbbbbbbb {\n" 2845 "}} // namespace aaaaaaaaaa::bbbbbbbbbb", 2846 format("namespace aaaaaaaaaa {\n" 2847 "namespace bbbbbbbbbb {\n" 2848 "} // namespace bbbbbbbbbb\n" 2849 "} // namespace aaaaaaaaaa", 2850 Style)); 2851 2852 EXPECT_EQ("namespace aaaaaa { namespace bbbbbb {\n" 2853 "namespace cccccc {\n" 2854 "}}} // namespace aaaaaa::bbbbbb::cccccc", 2855 format("namespace aaaaaa {\n" 2856 "namespace bbbbbb {\n" 2857 "namespace cccccc {\n" 2858 "} // namespace cccccc\n" 2859 "} // namespace bbbbbb\n" 2860 "} // namespace aaaaaa", 2861 Style)); 2862 Style.ColumnLimit = 80; 2863 2864 // Extra semicolon after 'inner' closing brace prevents merging 2865 EXPECT_EQ("namespace out { namespace in {\n" 2866 "}; } // namespace out::in", 2867 format("namespace out {\n" 2868 "namespace in {\n" 2869 "}; // namespace in\n" 2870 "} // namespace out", 2871 Style)); 2872 2873 // Extra semicolon after 'outer' closing brace is conserved 2874 EXPECT_EQ("namespace out { namespace in {\n" 2875 "}}; // namespace out::in", 2876 format("namespace out {\n" 2877 "namespace in {\n" 2878 "} // namespace in\n" 2879 "}; // namespace out", 2880 Style)); 2881 2882 Style.NamespaceIndentation = FormatStyle::NI_All; 2883 EXPECT_EQ("namespace out { namespace in {\n" 2884 " int i;\n" 2885 "}} // namespace out::in", 2886 format("namespace out {\n" 2887 "namespace in {\n" 2888 "int i;\n" 2889 "} // namespace in\n" 2890 "} // namespace out", 2891 Style)); 2892 EXPECT_EQ("namespace out { namespace mid {\n" 2893 " namespace in {\n" 2894 " int j;\n" 2895 " } // namespace in\n" 2896 " int k;\n" 2897 "}} // namespace out::mid", 2898 format("namespace out { namespace mid {\n" 2899 "namespace in { int j; } // namespace in\n" 2900 "int k; }} // namespace out::mid", 2901 Style)); 2902 2903 Style.NamespaceIndentation = FormatStyle::NI_Inner; 2904 EXPECT_EQ("namespace out { namespace in {\n" 2905 " int i;\n" 2906 "}} // namespace out::in", 2907 format("namespace out {\n" 2908 "namespace in {\n" 2909 "int i;\n" 2910 "} // namespace in\n" 2911 "} // namespace out", 2912 Style)); 2913 EXPECT_EQ("namespace out { namespace mid { namespace in {\n" 2914 " int i;\n" 2915 "}}} // namespace out::mid::in", 2916 format("namespace out {\n" 2917 "namespace mid {\n" 2918 "namespace in {\n" 2919 "int i;\n" 2920 "} // namespace in\n" 2921 "} // namespace mid\n" 2922 "} // namespace out", 2923 Style)); 2924 } 2925 2926 TEST_F(FormatTest, FormatsExternC) { 2927 verifyFormat("extern \"C\" {\nint a;"); 2928 verifyFormat("extern \"C\" {}"); 2929 verifyFormat("extern \"C\" {\n" 2930 "int foo();\n" 2931 "}"); 2932 verifyFormat("extern \"C\" int foo() {}"); 2933 verifyFormat("extern \"C\" int foo();"); 2934 verifyFormat("extern \"C\" int foo() {\n" 2935 " int i = 42;\n" 2936 " return i;\n" 2937 "}"); 2938 2939 FormatStyle Style = getLLVMStyle(); 2940 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 2941 Style.BraceWrapping.AfterFunction = true; 2942 verifyFormat("extern \"C\" int foo() {}", Style); 2943 verifyFormat("extern \"C\" int foo();", Style); 2944 verifyFormat("extern \"C\" int foo()\n" 2945 "{\n" 2946 " int i = 42;\n" 2947 " return i;\n" 2948 "}", 2949 Style); 2950 2951 Style.BraceWrapping.AfterExternBlock = true; 2952 Style.BraceWrapping.SplitEmptyRecord = false; 2953 verifyFormat("extern \"C\"\n" 2954 "{}", 2955 Style); 2956 verifyFormat("extern \"C\"\n" 2957 "{\n" 2958 " int foo();\n" 2959 "}", 2960 Style); 2961 } 2962 2963 TEST_F(FormatTest, IndentExternBlockStyle) { 2964 FormatStyle Style = getLLVMStyle(); 2965 Style.IndentWidth = 2; 2966 2967 Style.IndentExternBlock = FormatStyle::IEBS_Indent; 2968 verifyFormat("extern \"C\" { /*9*/\n}", Style); 2969 verifyFormat("extern \"C\" {\n" 2970 " int foo10();\n" 2971 "}", 2972 Style); 2973 2974 Style.IndentExternBlock = FormatStyle::IEBS_NoIndent; 2975 verifyFormat("extern \"C\" { /*11*/\n}", Style); 2976 verifyFormat("extern \"C\" {\n" 2977 "int foo12();\n" 2978 "}", 2979 Style); 2980 2981 Style.IndentExternBlock = FormatStyle::IEBS_AfterExternBlock; 2982 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 2983 Style.BraceWrapping.AfterExternBlock = true; 2984 verifyFormat("extern \"C\"\n{ /*13*/\n}", Style); 2985 verifyFormat("extern \"C\"\n{\n" 2986 " int foo14();\n" 2987 "}", 2988 Style); 2989 2990 Style.IndentExternBlock = FormatStyle::IEBS_AfterExternBlock; 2991 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 2992 Style.BraceWrapping.AfterExternBlock = false; 2993 verifyFormat("extern \"C\" { /*15*/\n}", Style); 2994 verifyFormat("extern \"C\" {\n" 2995 "int foo16();\n" 2996 "}", 2997 Style); 2998 } 2999 3000 TEST_F(FormatTest, FormatsInlineASM) { 3001 verifyFormat("asm(\"xyz\" : \"=a\"(a), \"=d\"(b) : \"a\"(data));"); 3002 verifyFormat("asm(\"nop\" ::: \"memory\");"); 3003 verifyFormat( 3004 "asm(\"movq\\t%%rbx, %%rsi\\n\\t\"\n" 3005 " \"cpuid\\n\\t\"\n" 3006 " \"xchgq\\t%%rbx, %%rsi\\n\\t\"\n" 3007 " : \"=a\"(*rEAX), \"=S\"(*rEBX), \"=c\"(*rECX), \"=d\"(*rEDX)\n" 3008 " : \"a\"(value));"); 3009 EXPECT_EQ( 3010 "void NS_InvokeByIndex(void *that, unsigned int methodIndex) {\n" 3011 " __asm {\n" 3012 " mov edx,[that] // vtable in edx\n" 3013 " mov eax,methodIndex\n" 3014 " call [edx][eax*4] // stdcall\n" 3015 " }\n" 3016 "}", 3017 format("void NS_InvokeByIndex(void *that, unsigned int methodIndex) {\n" 3018 " __asm {\n" 3019 " mov edx,[that] // vtable in edx\n" 3020 " mov eax,methodIndex\n" 3021 " call [edx][eax*4] // stdcall\n" 3022 " }\n" 3023 "}")); 3024 EXPECT_EQ("_asm {\n" 3025 " xor eax, eax;\n" 3026 " cpuid;\n" 3027 "}", 3028 format("_asm {\n" 3029 " xor eax, eax;\n" 3030 " cpuid;\n" 3031 "}")); 3032 verifyFormat("void function() {\n" 3033 " // comment\n" 3034 " asm(\"\");\n" 3035 "}"); 3036 EXPECT_EQ("__asm {\n" 3037 "}\n" 3038 "int i;", 3039 format("__asm {\n" 3040 "}\n" 3041 "int i;")); 3042 } 3043 3044 TEST_F(FormatTest, FormatTryCatch) { 3045 verifyFormat("try {\n" 3046 " throw a * b;\n" 3047 "} catch (int a) {\n" 3048 " // Do nothing.\n" 3049 "} catch (...) {\n" 3050 " exit(42);\n" 3051 "}"); 3052 3053 // Function-level try statements. 3054 verifyFormat("int f() try { return 4; } catch (...) {\n" 3055 " return 5;\n" 3056 "}"); 3057 verifyFormat("class A {\n" 3058 " int a;\n" 3059 " A() try : a(0) {\n" 3060 " } catch (...) {\n" 3061 " throw;\n" 3062 " }\n" 3063 "};\n"); 3064 verifyFormat("class A {\n" 3065 " int a;\n" 3066 " A() try : a(0), b{1} {\n" 3067 " } catch (...) {\n" 3068 " throw;\n" 3069 " }\n" 3070 "};\n"); 3071 verifyFormat("class A {\n" 3072 " int a;\n" 3073 " A() try : a(0), b{1}, c{2} {\n" 3074 " } catch (...) {\n" 3075 " throw;\n" 3076 " }\n" 3077 "};\n"); 3078 verifyFormat("class A {\n" 3079 " int a;\n" 3080 " A() try : a(0), b{1}, c{2} {\n" 3081 " { // New scope.\n" 3082 " }\n" 3083 " } catch (...) {\n" 3084 " throw;\n" 3085 " }\n" 3086 "};\n"); 3087 3088 // Incomplete try-catch blocks. 3089 verifyIncompleteFormat("try {} catch ("); 3090 } 3091 3092 TEST_F(FormatTest, FormatTryAsAVariable) { 3093 verifyFormat("int try;"); 3094 verifyFormat("int try, size;"); 3095 verifyFormat("try = foo();"); 3096 verifyFormat("if (try < size) {\n return true;\n}"); 3097 3098 verifyFormat("int catch;"); 3099 verifyFormat("int catch, size;"); 3100 verifyFormat("catch = foo();"); 3101 verifyFormat("if (catch < size) {\n return true;\n}"); 3102 3103 FormatStyle Style = getLLVMStyle(); 3104 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 3105 Style.BraceWrapping.AfterFunction = true; 3106 Style.BraceWrapping.BeforeCatch = true; 3107 verifyFormat("try {\n" 3108 " int bar = 1;\n" 3109 "}\n" 3110 "catch (...) {\n" 3111 " int bar = 1;\n" 3112 "}", 3113 Style); 3114 verifyFormat("#if NO_EX\n" 3115 "try\n" 3116 "#endif\n" 3117 "{\n" 3118 "}\n" 3119 "#if NO_EX\n" 3120 "catch (...) {\n" 3121 "}", 3122 Style); 3123 verifyFormat("try /* abc */ {\n" 3124 " int bar = 1;\n" 3125 "}\n" 3126 "catch (...) {\n" 3127 " int bar = 1;\n" 3128 "}", 3129 Style); 3130 verifyFormat("try\n" 3131 "// abc\n" 3132 "{\n" 3133 " int bar = 1;\n" 3134 "}\n" 3135 "catch (...) {\n" 3136 " int bar = 1;\n" 3137 "}", 3138 Style); 3139 } 3140 3141 TEST_F(FormatTest, FormatSEHTryCatch) { 3142 verifyFormat("__try {\n" 3143 " int a = b * c;\n" 3144 "} __except (EXCEPTION_EXECUTE_HANDLER) {\n" 3145 " // Do nothing.\n" 3146 "}"); 3147 3148 verifyFormat("__try {\n" 3149 " int a = b * c;\n" 3150 "} __finally {\n" 3151 " // Do nothing.\n" 3152 "}"); 3153 3154 verifyFormat("DEBUG({\n" 3155 " __try {\n" 3156 " } __finally {\n" 3157 " }\n" 3158 "});\n"); 3159 } 3160 3161 TEST_F(FormatTest, IncompleteTryCatchBlocks) { 3162 verifyFormat("try {\n" 3163 " f();\n" 3164 "} catch {\n" 3165 " g();\n" 3166 "}"); 3167 verifyFormat("try {\n" 3168 " f();\n" 3169 "} catch (A a) MACRO(x) {\n" 3170 " g();\n" 3171 "} catch (B b) MACRO(x) {\n" 3172 " g();\n" 3173 "}"); 3174 } 3175 3176 TEST_F(FormatTest, FormatTryCatchBraceStyles) { 3177 FormatStyle Style = getLLVMStyle(); 3178 for (auto BraceStyle : {FormatStyle::BS_Attach, FormatStyle::BS_Mozilla, 3179 FormatStyle::BS_WebKit}) { 3180 Style.BreakBeforeBraces = BraceStyle; 3181 verifyFormat("try {\n" 3182 " // something\n" 3183 "} catch (...) {\n" 3184 " // something\n" 3185 "}", 3186 Style); 3187 } 3188 Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup; 3189 verifyFormat("try {\n" 3190 " // something\n" 3191 "}\n" 3192 "catch (...) {\n" 3193 " // something\n" 3194 "}", 3195 Style); 3196 verifyFormat("__try {\n" 3197 " // something\n" 3198 "}\n" 3199 "__finally {\n" 3200 " // something\n" 3201 "}", 3202 Style); 3203 verifyFormat("@try {\n" 3204 " // something\n" 3205 "}\n" 3206 "@finally {\n" 3207 " // something\n" 3208 "}", 3209 Style); 3210 Style.BreakBeforeBraces = FormatStyle::BS_Allman; 3211 verifyFormat("try\n" 3212 "{\n" 3213 " // something\n" 3214 "}\n" 3215 "catch (...)\n" 3216 "{\n" 3217 " // something\n" 3218 "}", 3219 Style); 3220 Style.BreakBeforeBraces = FormatStyle::BS_Whitesmiths; 3221 verifyFormat("try\n" 3222 " {\n" 3223 " // something white\n" 3224 " }\n" 3225 "catch (...)\n" 3226 " {\n" 3227 " // something white\n" 3228 " }", 3229 Style); 3230 Style.BreakBeforeBraces = FormatStyle::BS_GNU; 3231 verifyFormat("try\n" 3232 " {\n" 3233 " // something\n" 3234 " }\n" 3235 "catch (...)\n" 3236 " {\n" 3237 " // something\n" 3238 " }", 3239 Style); 3240 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 3241 Style.BraceWrapping.BeforeCatch = true; 3242 verifyFormat("try {\n" 3243 " // something\n" 3244 "}\n" 3245 "catch (...) {\n" 3246 " // something\n" 3247 "}", 3248 Style); 3249 } 3250 3251 TEST_F(FormatTest, StaticInitializers) { 3252 verifyFormat("static SomeClass SC = {1, 'a'};"); 3253 3254 verifyFormat("static SomeClass WithALoooooooooooooooooooongName = {\n" 3255 " 100000000, " 3256 "\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"};"); 3257 3258 // Here, everything other than the "}" would fit on a line. 3259 verifyFormat("static int LooooooooooooooooooooooooongVariable[1] = {\n" 3260 " 10000000000000000000000000};"); 3261 EXPECT_EQ("S s = {a,\n" 3262 "\n" 3263 " b};", 3264 format("S s = {\n" 3265 " a,\n" 3266 "\n" 3267 " b\n" 3268 "};")); 3269 3270 // FIXME: This would fit into the column limit if we'd fit "{ {" on the first 3271 // line. However, the formatting looks a bit off and this probably doesn't 3272 // happen often in practice. 3273 verifyFormat("static int Variable[1] = {\n" 3274 " {1000000000000000000000000000000000000}};", 3275 getLLVMStyleWithColumns(40)); 3276 } 3277 3278 TEST_F(FormatTest, DesignatedInitializers) { 3279 verifyFormat("const struct A a = {.a = 1, .b = 2};"); 3280 verifyFormat("const struct A a = {.aaaaaaaaaa = 1,\n" 3281 " .bbbbbbbbbb = 2,\n" 3282 " .cccccccccc = 3,\n" 3283 " .dddddddddd = 4,\n" 3284 " .eeeeeeeeee = 5};"); 3285 verifyFormat("const struct Aaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaa = {\n" 3286 " .aaaaaaaaaaaaaaaaaaaaaaaaaaa = 1,\n" 3287 " .bbbbbbbbbbbbbbbbbbbbbbbbbbb = 2,\n" 3288 " .ccccccccccccccccccccccccccc = 3,\n" 3289 " .ddddddddddddddddddddddddddd = 4,\n" 3290 " .eeeeeeeeeeeeeeeeeeeeeeeeeee = 5};"); 3291 3292 verifyGoogleFormat("const struct A a = {.a = 1, .b = 2};"); 3293 3294 verifyFormat("const struct A a = {[0] = 1, [1] = 2};"); 3295 verifyFormat("const struct A a = {[1] = aaaaaaaaaa,\n" 3296 " [2] = bbbbbbbbbb,\n" 3297 " [3] = cccccccccc,\n" 3298 " [4] = dddddddddd,\n" 3299 " [5] = eeeeeeeeee};"); 3300 verifyFormat("const struct Aaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaa = {\n" 3301 " [1] = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 3302 " [2] = bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb,\n" 3303 " [3] = cccccccccccccccccccccccccccccccccccccc,\n" 3304 " [4] = dddddddddddddddddddddddddddddddddddddd,\n" 3305 " [5] = eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee};"); 3306 } 3307 3308 TEST_F(FormatTest, NestedStaticInitializers) { 3309 verifyFormat("static A x = {{{}}};\n"); 3310 verifyFormat("static A x = {{{init1, init2, init3, init4},\n" 3311 " {init1, init2, init3, init4}}};", 3312 getLLVMStyleWithColumns(50)); 3313 3314 verifyFormat("somes Status::global_reps[3] = {\n" 3315 " {kGlobalRef, OK_CODE, NULL, NULL, NULL},\n" 3316 " {kGlobalRef, CANCELLED_CODE, NULL, NULL, NULL},\n" 3317 " {kGlobalRef, UNKNOWN_CODE, NULL, NULL, NULL}};", 3318 getLLVMStyleWithColumns(60)); 3319 verifyGoogleFormat("SomeType Status::global_reps[3] = {\n" 3320 " {kGlobalRef, OK_CODE, NULL, NULL, NULL},\n" 3321 " {kGlobalRef, CANCELLED_CODE, NULL, NULL, NULL},\n" 3322 " {kGlobalRef, UNKNOWN_CODE, NULL, NULL, NULL}};"); 3323 verifyFormat("CGRect cg_rect = {{rect.fLeft, rect.fTop},\n" 3324 " {rect.fRight - rect.fLeft, rect.fBottom - " 3325 "rect.fTop}};"); 3326 3327 verifyFormat( 3328 "SomeArrayOfSomeType a = {\n" 3329 " {{1, 2, 3},\n" 3330 " {1, 2, 3},\n" 3331 " {111111111111111111111111111111, 222222222222222222222222222222,\n" 3332 " 333333333333333333333333333333},\n" 3333 " {1, 2, 3},\n" 3334 " {1, 2, 3}}};"); 3335 verifyFormat( 3336 "SomeArrayOfSomeType a = {\n" 3337 " {{1, 2, 3}},\n" 3338 " {{1, 2, 3}},\n" 3339 " {{111111111111111111111111111111, 222222222222222222222222222222,\n" 3340 " 333333333333333333333333333333}},\n" 3341 " {{1, 2, 3}},\n" 3342 " {{1, 2, 3}}};"); 3343 3344 verifyFormat("struct {\n" 3345 " unsigned bit;\n" 3346 " const char *const name;\n" 3347 "} kBitsToOs[] = {{kOsMac, \"Mac\"},\n" 3348 " {kOsWin, \"Windows\"},\n" 3349 " {kOsLinux, \"Linux\"},\n" 3350 " {kOsCrOS, \"Chrome OS\"}};"); 3351 verifyFormat("struct {\n" 3352 " unsigned bit;\n" 3353 " const char *const name;\n" 3354 "} kBitsToOs[] = {\n" 3355 " {kOsMac, \"Mac\"},\n" 3356 " {kOsWin, \"Windows\"},\n" 3357 " {kOsLinux, \"Linux\"},\n" 3358 " {kOsCrOS, \"Chrome OS\"},\n" 3359 "};"); 3360 } 3361 3362 TEST_F(FormatTest, FormatsSmallMacroDefinitionsInSingleLine) { 3363 verifyFormat("#define ALooooooooooooooooooooooooooooooooooooooongMacro(" 3364 " \\\n" 3365 " aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)"); 3366 } 3367 3368 TEST_F(FormatTest, DoesNotBreakPureVirtualFunctionDefinition) { 3369 verifyFormat("virtual void write(ELFWriter *writerrr,\n" 3370 " OwningPtr<FileOutputBuffer> &buffer) = 0;"); 3371 3372 // Do break defaulted and deleted functions. 3373 verifyFormat("virtual void ~Deeeeeeeestructor() =\n" 3374 " default;", 3375 getLLVMStyleWithColumns(40)); 3376 verifyFormat("virtual void ~Deeeeeeeestructor() =\n" 3377 " delete;", 3378 getLLVMStyleWithColumns(40)); 3379 } 3380 3381 TEST_F(FormatTest, BreaksStringLiteralsOnlyInDefine) { 3382 verifyFormat("# 1111 \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/aaaaaaaa.cpp\" 2 3", 3383 getLLVMStyleWithColumns(40)); 3384 verifyFormat("#line 11111 \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/aaaaaaaa.cpp\"", 3385 getLLVMStyleWithColumns(40)); 3386 EXPECT_EQ("#define Q \\\n" 3387 " \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/\" \\\n" 3388 " \"aaaaaaaa.cpp\"", 3389 format("#define Q \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/aaaaaaaa.cpp\"", 3390 getLLVMStyleWithColumns(40))); 3391 } 3392 3393 TEST_F(FormatTest, UnderstandsLinePPDirective) { 3394 EXPECT_EQ("# 123 \"A string literal\"", 3395 format(" # 123 \"A string literal\"")); 3396 } 3397 3398 TEST_F(FormatTest, LayoutUnknownPPDirective) { 3399 EXPECT_EQ("#;", format("#;")); 3400 verifyFormat("#\n;\n;\n;"); 3401 } 3402 3403 TEST_F(FormatTest, UnescapedEndOfLineEndsPPDirective) { 3404 EXPECT_EQ("#line 42 \"test\"\n", 3405 format("# \\\n line \\\n 42 \\\n \"test\"\n")); 3406 EXPECT_EQ("#define A B\n", format("# \\\n define \\\n A \\\n B\n", 3407 getLLVMStyleWithColumns(12))); 3408 } 3409 3410 TEST_F(FormatTest, EndOfFileEndsPPDirective) { 3411 EXPECT_EQ("#line 42 \"test\"", 3412 format("# \\\n line \\\n 42 \\\n \"test\"")); 3413 EXPECT_EQ("#define A B", format("# \\\n define \\\n A \\\n B")); 3414 } 3415 3416 TEST_F(FormatTest, DoesntRemoveUnknownTokens) { 3417 verifyFormat("#define A \\x20"); 3418 verifyFormat("#define A \\ x20"); 3419 EXPECT_EQ("#define A \\ x20", format("#define A \\ x20")); 3420 verifyFormat("#define A ''"); 3421 verifyFormat("#define A ''qqq"); 3422 verifyFormat("#define A `qqq"); 3423 verifyFormat("f(\"aaaa, bbbb, \"\\\"ccccc\\\"\");"); 3424 EXPECT_EQ("const char *c = STRINGIFY(\n" 3425 "\\na : b);", 3426 format("const char * c = STRINGIFY(\n" 3427 "\\na : b);")); 3428 3429 verifyFormat("a\r\\"); 3430 verifyFormat("a\v\\"); 3431 verifyFormat("a\f\\"); 3432 } 3433 3434 TEST_F(FormatTest, IndentsPPDirectiveInReducedSpace) { 3435 verifyFormat("#define A(BB)", getLLVMStyleWithColumns(13)); 3436 verifyFormat("#define A( \\\n BB)", getLLVMStyleWithColumns(12)); 3437 verifyFormat("#define A( \\\n A, B)", getLLVMStyleWithColumns(12)); 3438 // FIXME: We never break before the macro name. 3439 verifyFormat("#define AA( \\\n B)", getLLVMStyleWithColumns(12)); 3440 3441 verifyFormat("#define A A\n#define A A"); 3442 verifyFormat("#define A(X) A\n#define A A"); 3443 3444 verifyFormat("#define Something Other", getLLVMStyleWithColumns(23)); 3445 verifyFormat("#define Something \\\n Other", getLLVMStyleWithColumns(22)); 3446 } 3447 3448 TEST_F(FormatTest, HandlePreprocessorDirectiveContext) { 3449 EXPECT_EQ("// somecomment\n" 3450 "#include \"a.h\"\n" 3451 "#define A( \\\n" 3452 " A, B)\n" 3453 "#include \"b.h\"\n" 3454 "// somecomment\n", 3455 format(" // somecomment\n" 3456 " #include \"a.h\"\n" 3457 "#define A(A,\\\n" 3458 " B)\n" 3459 " #include \"b.h\"\n" 3460 " // somecomment\n", 3461 getLLVMStyleWithColumns(13))); 3462 } 3463 3464 TEST_F(FormatTest, LayoutSingleHash) { EXPECT_EQ("#\na;", format("#\na;")); } 3465 3466 TEST_F(FormatTest, LayoutCodeInMacroDefinitions) { 3467 EXPECT_EQ("#define A \\\n" 3468 " c; \\\n" 3469 " e;\n" 3470 "f;", 3471 format("#define A c; e;\n" 3472 "f;", 3473 getLLVMStyleWithColumns(14))); 3474 } 3475 3476 TEST_F(FormatTest, LayoutRemainingTokens) { EXPECT_EQ("{}", format("{}")); } 3477 3478 TEST_F(FormatTest, MacroDefinitionInsideStatement) { 3479 EXPECT_EQ("int x,\n" 3480 "#define A\n" 3481 " y;", 3482 format("int x,\n#define A\ny;")); 3483 } 3484 3485 TEST_F(FormatTest, HashInMacroDefinition) { 3486 EXPECT_EQ("#define A(c) L#c", format("#define A(c) L#c", getLLVMStyle())); 3487 verifyFormat("#define A \\\n b #c;", getLLVMStyleWithColumns(11)); 3488 verifyFormat("#define A \\\n" 3489 " { \\\n" 3490 " f(#c); \\\n" 3491 " }", 3492 getLLVMStyleWithColumns(11)); 3493 3494 verifyFormat("#define A(X) \\\n" 3495 " void function##X()", 3496 getLLVMStyleWithColumns(22)); 3497 3498 verifyFormat("#define A(a, b, c) \\\n" 3499 " void a##b##c()", 3500 getLLVMStyleWithColumns(22)); 3501 3502 verifyFormat("#define A void # ## #", getLLVMStyleWithColumns(22)); 3503 } 3504 3505 TEST_F(FormatTest, RespectWhitespaceInMacroDefinitions) { 3506 EXPECT_EQ("#define A (x)", format("#define A (x)")); 3507 EXPECT_EQ("#define A(x)", format("#define A(x)")); 3508 3509 FormatStyle Style = getLLVMStyle(); 3510 Style.SpaceBeforeParens = FormatStyle::SBPO_Never; 3511 verifyFormat("#define true ((foo)1)", Style); 3512 Style.SpaceBeforeParens = FormatStyle::SBPO_Always; 3513 verifyFormat("#define false((foo)0)", Style); 3514 } 3515 3516 TEST_F(FormatTest, EmptyLinesInMacroDefinitions) { 3517 EXPECT_EQ("#define A b;", format("#define A \\\n" 3518 " \\\n" 3519 " b;", 3520 getLLVMStyleWithColumns(25))); 3521 EXPECT_EQ("#define A \\\n" 3522 " \\\n" 3523 " a; \\\n" 3524 " b;", 3525 format("#define A \\\n" 3526 " \\\n" 3527 " a; \\\n" 3528 " b;", 3529 getLLVMStyleWithColumns(11))); 3530 EXPECT_EQ("#define A \\\n" 3531 " a; \\\n" 3532 " \\\n" 3533 " b;", 3534 format("#define A \\\n" 3535 " a; \\\n" 3536 " \\\n" 3537 " b;", 3538 getLLVMStyleWithColumns(11))); 3539 } 3540 3541 TEST_F(FormatTest, MacroDefinitionsWithIncompleteCode) { 3542 verifyIncompleteFormat("#define A :"); 3543 verifyFormat("#define SOMECASES \\\n" 3544 " case 1: \\\n" 3545 " case 2\n", 3546 getLLVMStyleWithColumns(20)); 3547 verifyFormat("#define MACRO(a) \\\n" 3548 " if (a) \\\n" 3549 " f(); \\\n" 3550 " else \\\n" 3551 " g()", 3552 getLLVMStyleWithColumns(18)); 3553 verifyFormat("#define A template <typename T>"); 3554 verifyIncompleteFormat("#define STR(x) #x\n" 3555 "f(STR(this_is_a_string_literal{));"); 3556 verifyFormat("#pragma omp threadprivate( \\\n" 3557 " y)), // expected-warning", 3558 getLLVMStyleWithColumns(28)); 3559 verifyFormat("#d, = };"); 3560 verifyFormat("#if \"a"); 3561 verifyIncompleteFormat("({\n" 3562 "#define b \\\n" 3563 " } \\\n" 3564 " a\n" 3565 "a", 3566 getLLVMStyleWithColumns(15)); 3567 verifyFormat("#define A \\\n" 3568 " { \\\n" 3569 " {\n" 3570 "#define B \\\n" 3571 " } \\\n" 3572 " }", 3573 getLLVMStyleWithColumns(15)); 3574 verifyNoCrash("#if a\na(\n#else\n#endif\n{a"); 3575 verifyNoCrash("a={0,1\n#if a\n#else\n;\n#endif\n}"); 3576 verifyNoCrash("#if a\na(\n#else\n#endif\n) a {a,b,c,d,f,g};"); 3577 verifyNoCrash("#ifdef A\n a(\n #else\n #endif\n) = []() { \n)}"); 3578 } 3579 3580 TEST_F(FormatTest, MacrosWithoutTrailingSemicolon) { 3581 verifyFormat("SOME_TYPE_NAME abc;"); // Gated on the newline. 3582 EXPECT_EQ("class A : public QObject {\n" 3583 " Q_OBJECT\n" 3584 "\n" 3585 " A() {}\n" 3586 "};", 3587 format("class A : public QObject {\n" 3588 " Q_OBJECT\n" 3589 "\n" 3590 " A() {\n}\n" 3591 "} ;")); 3592 EXPECT_EQ("MACRO\n" 3593 "/*static*/ int i;", 3594 format("MACRO\n" 3595 " /*static*/ int i;")); 3596 EXPECT_EQ("SOME_MACRO\n" 3597 "namespace {\n" 3598 "void f();\n" 3599 "} // namespace", 3600 format("SOME_MACRO\n" 3601 " namespace {\n" 3602 "void f( );\n" 3603 "} // namespace")); 3604 // Only if the identifier contains at least 5 characters. 3605 EXPECT_EQ("HTTP f();", format("HTTP\nf();")); 3606 EXPECT_EQ("MACRO\nf();", format("MACRO\nf();")); 3607 // Only if everything is upper case. 3608 EXPECT_EQ("class A : public QObject {\n" 3609 " Q_Object A() {}\n" 3610 "};", 3611 format("class A : public QObject {\n" 3612 " Q_Object\n" 3613 " A() {\n}\n" 3614 "} ;")); 3615 3616 // Only if the next line can actually start an unwrapped line. 3617 EXPECT_EQ("SOME_WEIRD_LOG_MACRO << SomeThing;", 3618 format("SOME_WEIRD_LOG_MACRO\n" 3619 "<< SomeThing;")); 3620 3621 verifyFormat("VISIT_GL_CALL(GenBuffers, void, (GLsizei n, GLuint* buffers), " 3622 "(n, buffers))\n", 3623 getChromiumStyle(FormatStyle::LK_Cpp)); 3624 3625 // See PR41483 3626 EXPECT_EQ("/**/ FOO(a)\n" 3627 "FOO(b)", 3628 format("/**/ FOO(a)\n" 3629 "FOO(b)")); 3630 } 3631 3632 TEST_F(FormatTest, MacroCallsWithoutTrailingSemicolon) { 3633 EXPECT_EQ("INITIALIZE_PASS_BEGIN(ScopDetection, \"polly-detect\")\n" 3634 "INITIALIZE_AG_DEPENDENCY(AliasAnalysis)\n" 3635 "INITIALIZE_PASS_DEPENDENCY(DominatorTree)\n" 3636 "class X {};\n" 3637 "INITIALIZE_PASS_END(ScopDetection, \"polly-detect\")\n" 3638 "int *createScopDetectionPass() { return 0; }", 3639 format(" INITIALIZE_PASS_BEGIN(ScopDetection, \"polly-detect\")\n" 3640 " INITIALIZE_AG_DEPENDENCY(AliasAnalysis)\n" 3641 " INITIALIZE_PASS_DEPENDENCY(DominatorTree)\n" 3642 " class X {};\n" 3643 " INITIALIZE_PASS_END(ScopDetection, \"polly-detect\")\n" 3644 " int *createScopDetectionPass() { return 0; }")); 3645 // FIXME: We could probably treat IPC_BEGIN_MESSAGE_MAP/IPC_END_MESSAGE_MAP as 3646 // braces, so that inner block is indented one level more. 3647 EXPECT_EQ("int q() {\n" 3648 " IPC_BEGIN_MESSAGE_MAP(WebKitTestController, message)\n" 3649 " IPC_MESSAGE_HANDLER(xxx, qqq)\n" 3650 " IPC_END_MESSAGE_MAP()\n" 3651 "}", 3652 format("int q() {\n" 3653 " IPC_BEGIN_MESSAGE_MAP(WebKitTestController, message)\n" 3654 " IPC_MESSAGE_HANDLER(xxx, qqq)\n" 3655 " IPC_END_MESSAGE_MAP()\n" 3656 "}")); 3657 3658 // Same inside macros. 3659 EXPECT_EQ("#define LIST(L) \\\n" 3660 " L(A) \\\n" 3661 " L(B) \\\n" 3662 " L(C)", 3663 format("#define LIST(L) \\\n" 3664 " L(A) \\\n" 3665 " L(B) \\\n" 3666 " L(C)", 3667 getGoogleStyle())); 3668 3669 // These must not be recognized as macros. 3670 EXPECT_EQ("int q() {\n" 3671 " f(x);\n" 3672 " f(x) {}\n" 3673 " f(x)->g();\n" 3674 " f(x)->*g();\n" 3675 " f(x).g();\n" 3676 " f(x) = x;\n" 3677 " f(x) += x;\n" 3678 " f(x) -= x;\n" 3679 " f(x) *= x;\n" 3680 " f(x) /= x;\n" 3681 " f(x) %= x;\n" 3682 " f(x) &= x;\n" 3683 " f(x) |= x;\n" 3684 " f(x) ^= x;\n" 3685 " f(x) >>= x;\n" 3686 " f(x) <<= x;\n" 3687 " f(x)[y].z();\n" 3688 " LOG(INFO) << x;\n" 3689 " ifstream(x) >> x;\n" 3690 "}\n", 3691 format("int q() {\n" 3692 " f(x)\n;\n" 3693 " f(x)\n {}\n" 3694 " f(x)\n->g();\n" 3695 " f(x)\n->*g();\n" 3696 " f(x)\n.g();\n" 3697 " f(x)\n = x;\n" 3698 " f(x)\n += x;\n" 3699 " f(x)\n -= x;\n" 3700 " f(x)\n *= x;\n" 3701 " f(x)\n /= x;\n" 3702 " f(x)\n %= x;\n" 3703 " f(x)\n &= x;\n" 3704 " f(x)\n |= x;\n" 3705 " f(x)\n ^= x;\n" 3706 " f(x)\n >>= x;\n" 3707 " f(x)\n <<= x;\n" 3708 " f(x)\n[y].z();\n" 3709 " LOG(INFO)\n << x;\n" 3710 " ifstream(x)\n >> x;\n" 3711 "}\n")); 3712 EXPECT_EQ("int q() {\n" 3713 " F(x)\n" 3714 " if (1) {\n" 3715 " }\n" 3716 " F(x)\n" 3717 " while (1) {\n" 3718 " }\n" 3719 " F(x)\n" 3720 " G(x);\n" 3721 " F(x)\n" 3722 " try {\n" 3723 " Q();\n" 3724 " } catch (...) {\n" 3725 " }\n" 3726 "}\n", 3727 format("int q() {\n" 3728 "F(x)\n" 3729 "if (1) {}\n" 3730 "F(x)\n" 3731 "while (1) {}\n" 3732 "F(x)\n" 3733 "G(x);\n" 3734 "F(x)\n" 3735 "try { Q(); } catch (...) {}\n" 3736 "}\n")); 3737 EXPECT_EQ("class A {\n" 3738 " A() : t(0) {}\n" 3739 " A(int i) noexcept() : {}\n" 3740 " A(X x)\n" // FIXME: function-level try blocks are broken. 3741 " try : t(0) {\n" 3742 " } catch (...) {\n" 3743 " }\n" 3744 "};", 3745 format("class A {\n" 3746 " A()\n : t(0) {}\n" 3747 " A(int i)\n noexcept() : {}\n" 3748 " A(X x)\n" 3749 " try : t(0) {} catch (...) {}\n" 3750 "};")); 3751 FormatStyle Style = getLLVMStyle(); 3752 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 3753 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always; 3754 Style.BraceWrapping.AfterFunction = true; 3755 EXPECT_EQ("void f()\n" 3756 "try\n" 3757 "{\n" 3758 "}", 3759 format("void f() try {\n" 3760 "}", 3761 Style)); 3762 EXPECT_EQ("class SomeClass {\n" 3763 "public:\n" 3764 " SomeClass() EXCLUSIVE_LOCK_FUNCTION(mu_);\n" 3765 "};", 3766 format("class SomeClass {\n" 3767 "public:\n" 3768 " SomeClass()\n" 3769 " EXCLUSIVE_LOCK_FUNCTION(mu_);\n" 3770 "};")); 3771 EXPECT_EQ("class SomeClass {\n" 3772 "public:\n" 3773 " SomeClass()\n" 3774 " EXCLUSIVE_LOCK_FUNCTION(mu_);\n" 3775 "};", 3776 format("class SomeClass {\n" 3777 "public:\n" 3778 " SomeClass()\n" 3779 " EXCLUSIVE_LOCK_FUNCTION(mu_);\n" 3780 "};", 3781 getLLVMStyleWithColumns(40))); 3782 3783 verifyFormat("MACRO(>)"); 3784 3785 // Some macros contain an implicit semicolon. 3786 Style = getLLVMStyle(); 3787 Style.StatementMacros.push_back("FOO"); 3788 verifyFormat("FOO(a) int b = 0;"); 3789 verifyFormat("FOO(a)\n" 3790 "int b = 0;", 3791 Style); 3792 verifyFormat("FOO(a);\n" 3793 "int b = 0;", 3794 Style); 3795 verifyFormat("FOO(argc, argv, \"4.0.2\")\n" 3796 "int b = 0;", 3797 Style); 3798 verifyFormat("FOO()\n" 3799 "int b = 0;", 3800 Style); 3801 verifyFormat("FOO\n" 3802 "int b = 0;", 3803 Style); 3804 verifyFormat("void f() {\n" 3805 " FOO(a)\n" 3806 " return a;\n" 3807 "}", 3808 Style); 3809 verifyFormat("FOO(a)\n" 3810 "FOO(b)", 3811 Style); 3812 verifyFormat("int a = 0;\n" 3813 "FOO(b)\n" 3814 "int c = 0;", 3815 Style); 3816 verifyFormat("int a = 0;\n" 3817 "int x = FOO(a)\n" 3818 "int b = 0;", 3819 Style); 3820 verifyFormat("void foo(int a) { FOO(a) }\n" 3821 "uint32_t bar() {}", 3822 Style); 3823 } 3824 3825 TEST_F(FormatTest, LayoutMacroDefinitionsStatementsSpanningBlocks) { 3826 verifyFormat("#define A \\\n" 3827 " f({ \\\n" 3828 " g(); \\\n" 3829 " });", 3830 getLLVMStyleWithColumns(11)); 3831 } 3832 3833 TEST_F(FormatTest, IndentPreprocessorDirectives) { 3834 FormatStyle Style = getLLVMStyle(); 3835 Style.IndentPPDirectives = FormatStyle::PPDIS_None; 3836 Style.ColumnLimit = 40; 3837 verifyFormat("#ifdef _WIN32\n" 3838 "#define A 0\n" 3839 "#ifdef VAR2\n" 3840 "#define B 1\n" 3841 "#include <someheader.h>\n" 3842 "#define MACRO \\\n" 3843 " some_very_long_func_aaaaaaaaaa();\n" 3844 "#endif\n" 3845 "#else\n" 3846 "#define A 1\n" 3847 "#endif", 3848 Style); 3849 Style.IndentPPDirectives = FormatStyle::PPDIS_AfterHash; 3850 verifyFormat("#ifdef _WIN32\n" 3851 "# define A 0\n" 3852 "# ifdef VAR2\n" 3853 "# define B 1\n" 3854 "# include <someheader.h>\n" 3855 "# define MACRO \\\n" 3856 " some_very_long_func_aaaaaaaaaa();\n" 3857 "# endif\n" 3858 "#else\n" 3859 "# define A 1\n" 3860 "#endif", 3861 Style); 3862 verifyFormat("#if A\n" 3863 "# define MACRO \\\n" 3864 " void a(int x) { \\\n" 3865 " b(); \\\n" 3866 " c(); \\\n" 3867 " d(); \\\n" 3868 " e(); \\\n" 3869 " f(); \\\n" 3870 " }\n" 3871 "#endif", 3872 Style); 3873 // Comments before include guard. 3874 verifyFormat("// file comment\n" 3875 "// file comment\n" 3876 "#ifndef HEADER_H\n" 3877 "#define HEADER_H\n" 3878 "code();\n" 3879 "#endif", 3880 Style); 3881 // Test with include guards. 3882 verifyFormat("#ifndef HEADER_H\n" 3883 "#define HEADER_H\n" 3884 "code();\n" 3885 "#endif", 3886 Style); 3887 // Include guards must have a #define with the same variable immediately 3888 // after #ifndef. 3889 verifyFormat("#ifndef NOT_GUARD\n" 3890 "# define FOO\n" 3891 "code();\n" 3892 "#endif", 3893 Style); 3894 3895 // Include guards must cover the entire file. 3896 verifyFormat("code();\n" 3897 "code();\n" 3898 "#ifndef NOT_GUARD\n" 3899 "# define NOT_GUARD\n" 3900 "code();\n" 3901 "#endif", 3902 Style); 3903 verifyFormat("#ifndef NOT_GUARD\n" 3904 "# define NOT_GUARD\n" 3905 "code();\n" 3906 "#endif\n" 3907 "code();", 3908 Style); 3909 // Test with trailing blank lines. 3910 verifyFormat("#ifndef HEADER_H\n" 3911 "#define HEADER_H\n" 3912 "code();\n" 3913 "#endif\n", 3914 Style); 3915 // Include guards don't have #else. 3916 verifyFormat("#ifndef NOT_GUARD\n" 3917 "# define NOT_GUARD\n" 3918 "code();\n" 3919 "#else\n" 3920 "#endif", 3921 Style); 3922 verifyFormat("#ifndef NOT_GUARD\n" 3923 "# define NOT_GUARD\n" 3924 "code();\n" 3925 "#elif FOO\n" 3926 "#endif", 3927 Style); 3928 // Non-identifier #define after potential include guard. 3929 verifyFormat("#ifndef FOO\n" 3930 "# define 1\n" 3931 "#endif\n", 3932 Style); 3933 // #if closes past last non-preprocessor line. 3934 verifyFormat("#ifndef FOO\n" 3935 "#define FOO\n" 3936 "#if 1\n" 3937 "int i;\n" 3938 "# define A 0\n" 3939 "#endif\n" 3940 "#endif\n", 3941 Style); 3942 // Don't crash if there is an #elif directive without a condition. 3943 verifyFormat("#if 1\n" 3944 "int x;\n" 3945 "#elif\n" 3946 "int y;\n" 3947 "#else\n" 3948 "int z;\n" 3949 "#endif", 3950 Style); 3951 // FIXME: This doesn't handle the case where there's code between the 3952 // #ifndef and #define but all other conditions hold. This is because when 3953 // the #define line is parsed, UnwrappedLineParser::Lines doesn't hold the 3954 // previous code line yet, so we can't detect it. 3955 EXPECT_EQ("#ifndef NOT_GUARD\n" 3956 "code();\n" 3957 "#define NOT_GUARD\n" 3958 "code();\n" 3959 "#endif", 3960 format("#ifndef NOT_GUARD\n" 3961 "code();\n" 3962 "# define NOT_GUARD\n" 3963 "code();\n" 3964 "#endif", 3965 Style)); 3966 // FIXME: This doesn't handle cases where legitimate preprocessor lines may 3967 // be outside an include guard. Examples are #pragma once and 3968 // #pragma GCC diagnostic, or anything else that does not change the meaning 3969 // of the file if it's included multiple times. 3970 EXPECT_EQ("#ifdef WIN32\n" 3971 "# pragma once\n" 3972 "#endif\n" 3973 "#ifndef HEADER_H\n" 3974 "# define HEADER_H\n" 3975 "code();\n" 3976 "#endif", 3977 format("#ifdef WIN32\n" 3978 "# pragma once\n" 3979 "#endif\n" 3980 "#ifndef HEADER_H\n" 3981 "#define HEADER_H\n" 3982 "code();\n" 3983 "#endif", 3984 Style)); 3985 // FIXME: This does not detect when there is a single non-preprocessor line 3986 // in front of an include-guard-like structure where other conditions hold 3987 // because ScopedLineState hides the line. 3988 EXPECT_EQ("code();\n" 3989 "#ifndef HEADER_H\n" 3990 "#define HEADER_H\n" 3991 "code();\n" 3992 "#endif", 3993 format("code();\n" 3994 "#ifndef HEADER_H\n" 3995 "# define HEADER_H\n" 3996 "code();\n" 3997 "#endif", 3998 Style)); 3999 // Keep comments aligned with #, otherwise indent comments normally. These 4000 // tests cannot use verifyFormat because messUp manipulates leading 4001 // whitespace. 4002 { 4003 const char *Expected = "" 4004 "void f() {\n" 4005 "#if 1\n" 4006 "// Preprocessor aligned.\n" 4007 "# define A 0\n" 4008 " // Code. Separated by blank line.\n" 4009 "\n" 4010 "# define B 0\n" 4011 " // Code. Not aligned with #\n" 4012 "# define C 0\n" 4013 "#endif"; 4014 const char *ToFormat = "" 4015 "void f() {\n" 4016 "#if 1\n" 4017 "// Preprocessor aligned.\n" 4018 "# define A 0\n" 4019 "// Code. Separated by blank line.\n" 4020 "\n" 4021 "# define B 0\n" 4022 " // Code. Not aligned with #\n" 4023 "# define C 0\n" 4024 "#endif"; 4025 EXPECT_EQ(Expected, format(ToFormat, Style)); 4026 EXPECT_EQ(Expected, format(Expected, Style)); 4027 } 4028 // Keep block quotes aligned. 4029 { 4030 const char *Expected = "" 4031 "void f() {\n" 4032 "#if 1\n" 4033 "/* Preprocessor aligned. */\n" 4034 "# define A 0\n" 4035 " /* Code. Separated by blank line. */\n" 4036 "\n" 4037 "# define B 0\n" 4038 " /* Code. Not aligned with # */\n" 4039 "# define C 0\n" 4040 "#endif"; 4041 const char *ToFormat = "" 4042 "void f() {\n" 4043 "#if 1\n" 4044 "/* Preprocessor aligned. */\n" 4045 "# define A 0\n" 4046 "/* Code. Separated by blank line. */\n" 4047 "\n" 4048 "# define B 0\n" 4049 " /* Code. Not aligned with # */\n" 4050 "# define C 0\n" 4051 "#endif"; 4052 EXPECT_EQ(Expected, format(ToFormat, Style)); 4053 EXPECT_EQ(Expected, format(Expected, Style)); 4054 } 4055 // Keep comments aligned with un-indented directives. 4056 { 4057 const char *Expected = "" 4058 "void f() {\n" 4059 "// Preprocessor aligned.\n" 4060 "#define A 0\n" 4061 " // Code. Separated by blank line.\n" 4062 "\n" 4063 "#define B 0\n" 4064 " // Code. Not aligned with #\n" 4065 "#define C 0\n"; 4066 const char *ToFormat = "" 4067 "void f() {\n" 4068 "// Preprocessor aligned.\n" 4069 "#define A 0\n" 4070 "// Code. Separated by blank line.\n" 4071 "\n" 4072 "#define B 0\n" 4073 " // Code. Not aligned with #\n" 4074 "#define C 0\n"; 4075 EXPECT_EQ(Expected, format(ToFormat, Style)); 4076 EXPECT_EQ(Expected, format(Expected, Style)); 4077 } 4078 // Test AfterHash with tabs. 4079 { 4080 FormatStyle Tabbed = Style; 4081 Tabbed.UseTab = FormatStyle::UT_Always; 4082 Tabbed.IndentWidth = 8; 4083 Tabbed.TabWidth = 8; 4084 verifyFormat("#ifdef _WIN32\n" 4085 "#\tdefine A 0\n" 4086 "#\tifdef VAR2\n" 4087 "#\t\tdefine B 1\n" 4088 "#\t\tinclude <someheader.h>\n" 4089 "#\t\tdefine MACRO \\\n" 4090 "\t\t\tsome_very_long_func_aaaaaaaaaa();\n" 4091 "#\tendif\n" 4092 "#else\n" 4093 "#\tdefine A 1\n" 4094 "#endif", 4095 Tabbed); 4096 } 4097 4098 // Regression test: Multiline-macro inside include guards. 4099 verifyFormat("#ifndef HEADER_H\n" 4100 "#define HEADER_H\n" 4101 "#define A() \\\n" 4102 " int i; \\\n" 4103 " int j;\n" 4104 "#endif // HEADER_H", 4105 getLLVMStyleWithColumns(20)); 4106 4107 Style.IndentPPDirectives = FormatStyle::PPDIS_BeforeHash; 4108 // Basic before hash indent tests 4109 verifyFormat("#ifdef _WIN32\n" 4110 " #define A 0\n" 4111 " #ifdef VAR2\n" 4112 " #define B 1\n" 4113 " #include <someheader.h>\n" 4114 " #define MACRO \\\n" 4115 " some_very_long_func_aaaaaaaaaa();\n" 4116 " #endif\n" 4117 "#else\n" 4118 " #define A 1\n" 4119 "#endif", 4120 Style); 4121 verifyFormat("#if A\n" 4122 " #define MACRO \\\n" 4123 " void a(int x) { \\\n" 4124 " b(); \\\n" 4125 " c(); \\\n" 4126 " d(); \\\n" 4127 " e(); \\\n" 4128 " f(); \\\n" 4129 " }\n" 4130 "#endif", 4131 Style); 4132 // Keep comments aligned with indented directives. These 4133 // tests cannot use verifyFormat because messUp manipulates leading 4134 // whitespace. 4135 { 4136 const char *Expected = "void f() {\n" 4137 "// Aligned to preprocessor.\n" 4138 "#if 1\n" 4139 " // Aligned to code.\n" 4140 " int a;\n" 4141 " #if 1\n" 4142 " // Aligned to preprocessor.\n" 4143 " #define A 0\n" 4144 " // Aligned to code.\n" 4145 " int b;\n" 4146 " #endif\n" 4147 "#endif\n" 4148 "}"; 4149 const char *ToFormat = "void f() {\n" 4150 "// Aligned to preprocessor.\n" 4151 "#if 1\n" 4152 "// Aligned to code.\n" 4153 "int a;\n" 4154 "#if 1\n" 4155 "// Aligned to preprocessor.\n" 4156 "#define A 0\n" 4157 "// Aligned to code.\n" 4158 "int b;\n" 4159 "#endif\n" 4160 "#endif\n" 4161 "}"; 4162 EXPECT_EQ(Expected, format(ToFormat, Style)); 4163 EXPECT_EQ(Expected, format(Expected, Style)); 4164 } 4165 { 4166 const char *Expected = "void f() {\n" 4167 "/* Aligned to preprocessor. */\n" 4168 "#if 1\n" 4169 " /* Aligned to code. */\n" 4170 " int a;\n" 4171 " #if 1\n" 4172 " /* Aligned to preprocessor. */\n" 4173 " #define A 0\n" 4174 " /* Aligned to code. */\n" 4175 " int b;\n" 4176 " #endif\n" 4177 "#endif\n" 4178 "}"; 4179 const char *ToFormat = "void f() {\n" 4180 "/* Aligned to preprocessor. */\n" 4181 "#if 1\n" 4182 "/* Aligned to code. */\n" 4183 "int a;\n" 4184 "#if 1\n" 4185 "/* Aligned to preprocessor. */\n" 4186 "#define A 0\n" 4187 "/* Aligned to code. */\n" 4188 "int b;\n" 4189 "#endif\n" 4190 "#endif\n" 4191 "}"; 4192 EXPECT_EQ(Expected, format(ToFormat, Style)); 4193 EXPECT_EQ(Expected, format(Expected, Style)); 4194 } 4195 4196 // Test single comment before preprocessor 4197 verifyFormat("// Comment\n" 4198 "\n" 4199 "#if 1\n" 4200 "#endif", 4201 Style); 4202 } 4203 4204 TEST_F(FormatTest, FormatHashIfNotAtStartOfLine) { 4205 verifyFormat("{\n { a #c; }\n}"); 4206 } 4207 4208 TEST_F(FormatTest, FormatUnbalancedStructuralElements) { 4209 EXPECT_EQ("#define A \\\n { \\\n {\nint i;", 4210 format("#define A { {\nint i;", getLLVMStyleWithColumns(11))); 4211 EXPECT_EQ("#define A \\\n } \\\n }\nint i;", 4212 format("#define A } }\nint i;", getLLVMStyleWithColumns(11))); 4213 } 4214 4215 TEST_F(FormatTest, EscapedNewlines) { 4216 FormatStyle Narrow = getLLVMStyleWithColumns(11); 4217 EXPECT_EQ("#define A \\\n int i; \\\n int j;", 4218 format("#define A \\\nint i;\\\n int j;", Narrow)); 4219 EXPECT_EQ("#define A\n\nint i;", format("#define A \\\n\n int i;")); 4220 EXPECT_EQ("template <class T> f();", format("\\\ntemplate <class T> f();")); 4221 EXPECT_EQ("/* \\ \\ \\\n */", format("\\\n/* \\ \\ \\\n */")); 4222 EXPECT_EQ("<a\n\\\\\n>", format("<a\n\\\\\n>")); 4223 4224 FormatStyle AlignLeft = getLLVMStyle(); 4225 AlignLeft.AlignEscapedNewlines = FormatStyle::ENAS_Left; 4226 EXPECT_EQ("#define MACRO(x) \\\n" 4227 "private: \\\n" 4228 " int x(int a);\n", 4229 format("#define MACRO(x) \\\n" 4230 "private: \\\n" 4231 " int x(int a);\n", 4232 AlignLeft)); 4233 4234 // CRLF line endings 4235 EXPECT_EQ("#define A \\\r\n int i; \\\r\n int j;", 4236 format("#define A \\\r\nint i;\\\r\n int j;", Narrow)); 4237 EXPECT_EQ("#define A\r\n\r\nint i;", format("#define A \\\r\n\r\n int i;")); 4238 EXPECT_EQ("template <class T> f();", format("\\\ntemplate <class T> f();")); 4239 EXPECT_EQ("/* \\ \\ \\\r\n */", format("\\\r\n/* \\ \\ \\\r\n */")); 4240 EXPECT_EQ("<a\r\n\\\\\r\n>", format("<a\r\n\\\\\r\n>")); 4241 EXPECT_EQ("#define MACRO(x) \\\r\n" 4242 "private: \\\r\n" 4243 " int x(int a);\r\n", 4244 format("#define MACRO(x) \\\r\n" 4245 "private: \\\r\n" 4246 " int x(int a);\r\n", 4247 AlignLeft)); 4248 4249 FormatStyle DontAlign = getLLVMStyle(); 4250 DontAlign.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign; 4251 DontAlign.MaxEmptyLinesToKeep = 3; 4252 // FIXME: can't use verifyFormat here because the newline before 4253 // "public:" is not inserted the first time it's reformatted 4254 EXPECT_EQ("#define A \\\n" 4255 " class Foo { \\\n" 4256 " void bar(); \\\n" 4257 "\\\n" 4258 "\\\n" 4259 "\\\n" 4260 " public: \\\n" 4261 " void baz(); \\\n" 4262 " };", 4263 format("#define A \\\n" 4264 " class Foo { \\\n" 4265 " void bar(); \\\n" 4266 "\\\n" 4267 "\\\n" 4268 "\\\n" 4269 " public: \\\n" 4270 " void baz(); \\\n" 4271 " };", 4272 DontAlign)); 4273 } 4274 4275 TEST_F(FormatTest, CalculateSpaceOnConsecutiveLinesInMacro) { 4276 verifyFormat("#define A \\\n" 4277 " int v( \\\n" 4278 " a); \\\n" 4279 " int i;", 4280 getLLVMStyleWithColumns(11)); 4281 } 4282 4283 TEST_F(FormatTest, MixingPreprocessorDirectivesAndNormalCode) { 4284 EXPECT_EQ( 4285 "#define ALooooooooooooooooooooooooooooooooooooooongMacro(" 4286 " \\\n" 4287 " aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)\n" 4288 "\n" 4289 "AlooooooooooooooooooooooooooooooooooooooongCaaaaaaaaaal(\n" 4290 " aLooooooooooooooooooooooonPaaaaaaaaaaaaaaaaaaaaarmmmm);\n", 4291 format(" #define ALooooooooooooooooooooooooooooooooooooooongMacro(" 4292 "\\\n" 4293 "aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)\n" 4294 " \n" 4295 " AlooooooooooooooooooooooooooooooooooooooongCaaaaaaaaaal(\n" 4296 " aLooooooooooooooooooooooonPaaaaaaaaaaaaaaaaaaaaarmmmm);\n")); 4297 } 4298 4299 TEST_F(FormatTest, LayoutStatementsAroundPreprocessorDirectives) { 4300 EXPECT_EQ("int\n" 4301 "#define A\n" 4302 " a;", 4303 format("int\n#define A\na;")); 4304 verifyFormat("functionCallTo(\n" 4305 " someOtherFunction(\n" 4306 " withSomeParameters, whichInSequence,\n" 4307 " areLongerThanALine(andAnotherCall,\n" 4308 "#define A B\n" 4309 " withMoreParamters,\n" 4310 " whichStronglyInfluenceTheLayout),\n" 4311 " andMoreParameters),\n" 4312 " trailing);", 4313 getLLVMStyleWithColumns(69)); 4314 verifyFormat("Foo::Foo()\n" 4315 "#ifdef BAR\n" 4316 " : baz(0)\n" 4317 "#endif\n" 4318 "{\n" 4319 "}"); 4320 verifyFormat("void f() {\n" 4321 " if (true)\n" 4322 "#ifdef A\n" 4323 " f(42);\n" 4324 " x();\n" 4325 "#else\n" 4326 " g();\n" 4327 " x();\n" 4328 "#endif\n" 4329 "}"); 4330 verifyFormat("void f(param1, param2,\n" 4331 " param3,\n" 4332 "#ifdef A\n" 4333 " param4(param5,\n" 4334 "#ifdef A1\n" 4335 " param6,\n" 4336 "#ifdef A2\n" 4337 " param7),\n" 4338 "#else\n" 4339 " param8),\n" 4340 " param9,\n" 4341 "#endif\n" 4342 " param10,\n" 4343 "#endif\n" 4344 " param11)\n" 4345 "#else\n" 4346 " param12)\n" 4347 "#endif\n" 4348 "{\n" 4349 " x();\n" 4350 "}", 4351 getLLVMStyleWithColumns(28)); 4352 verifyFormat("#if 1\n" 4353 "int i;"); 4354 verifyFormat("#if 1\n" 4355 "#endif\n" 4356 "#if 1\n" 4357 "#else\n" 4358 "#endif\n"); 4359 verifyFormat("DEBUG({\n" 4360 " return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 4361 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;\n" 4362 "});\n" 4363 "#if a\n" 4364 "#else\n" 4365 "#endif"); 4366 4367 verifyIncompleteFormat("void f(\n" 4368 "#if A\n" 4369 ");\n" 4370 "#else\n" 4371 "#endif"); 4372 } 4373 4374 TEST_F(FormatTest, GraciouslyHandleIncorrectPreprocessorConditions) { 4375 verifyFormat("#endif\n" 4376 "#if B"); 4377 } 4378 4379 TEST_F(FormatTest, FormatsJoinedLinesOnSubsequentRuns) { 4380 FormatStyle SingleLine = getLLVMStyle(); 4381 SingleLine.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_WithoutElse; 4382 verifyFormat("#if 0\n" 4383 "#elif 1\n" 4384 "#endif\n" 4385 "void foo() {\n" 4386 " if (test) foo2();\n" 4387 "}", 4388 SingleLine); 4389 } 4390 4391 TEST_F(FormatTest, LayoutBlockInsideParens) { 4392 verifyFormat("functionCall({ int i; });"); 4393 verifyFormat("functionCall({\n" 4394 " int i;\n" 4395 " int j;\n" 4396 "});"); 4397 verifyFormat("functionCall(\n" 4398 " {\n" 4399 " int i;\n" 4400 " int j;\n" 4401 " },\n" 4402 " aaaa, bbbb, cccc);"); 4403 verifyFormat("functionA(functionB({\n" 4404 " int i;\n" 4405 " int j;\n" 4406 " }),\n" 4407 " aaaa, bbbb, cccc);"); 4408 verifyFormat("functionCall(\n" 4409 " {\n" 4410 " int i;\n" 4411 " int j;\n" 4412 " },\n" 4413 " aaaa, bbbb, // comment\n" 4414 " cccc);"); 4415 verifyFormat("functionA(functionB({\n" 4416 " int i;\n" 4417 " int j;\n" 4418 " }),\n" 4419 " aaaa, bbbb, // comment\n" 4420 " cccc);"); 4421 verifyFormat("functionCall(aaaa, bbbb, { int i; });"); 4422 verifyFormat("functionCall(aaaa, bbbb, {\n" 4423 " int i;\n" 4424 " int j;\n" 4425 "});"); 4426 verifyFormat( 4427 "Aaa(\n" // FIXME: There shouldn't be a linebreak here. 4428 " {\n" 4429 " int i; // break\n" 4430 " },\n" 4431 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb,\n" 4432 " ccccccccccccccccc));"); 4433 verifyFormat("DEBUG({\n" 4434 " if (a)\n" 4435 " f();\n" 4436 "});"); 4437 } 4438 4439 TEST_F(FormatTest, LayoutBlockInsideStatement) { 4440 EXPECT_EQ("SOME_MACRO { int i; }\n" 4441 "int i;", 4442 format(" SOME_MACRO {int i;} int i;")); 4443 } 4444 4445 TEST_F(FormatTest, LayoutNestedBlocks) { 4446 verifyFormat("void AddOsStrings(unsigned bitmask) {\n" 4447 " struct s {\n" 4448 " int i;\n" 4449 " };\n" 4450 " s kBitsToOs[] = {{10}};\n" 4451 " for (int i = 0; i < 10; ++i)\n" 4452 " return;\n" 4453 "}"); 4454 verifyFormat("call(parameter, {\n" 4455 " something();\n" 4456 " // Comment using all columns.\n" 4457 " somethingelse();\n" 4458 "});", 4459 getLLVMStyleWithColumns(40)); 4460 verifyFormat("DEBUG( //\n" 4461 " { f(); }, a);"); 4462 verifyFormat("DEBUG( //\n" 4463 " {\n" 4464 " f(); //\n" 4465 " },\n" 4466 " a);"); 4467 4468 EXPECT_EQ("call(parameter, {\n" 4469 " something();\n" 4470 " // Comment too\n" 4471 " // looooooooooong.\n" 4472 " somethingElse();\n" 4473 "});", 4474 format("call(parameter, {\n" 4475 " something();\n" 4476 " // Comment too looooooooooong.\n" 4477 " somethingElse();\n" 4478 "});", 4479 getLLVMStyleWithColumns(29))); 4480 EXPECT_EQ("DEBUG({ int i; });", format("DEBUG({ int i; });")); 4481 EXPECT_EQ("DEBUG({ // comment\n" 4482 " int i;\n" 4483 "});", 4484 format("DEBUG({ // comment\n" 4485 "int i;\n" 4486 "});")); 4487 EXPECT_EQ("DEBUG({\n" 4488 " int i;\n" 4489 "\n" 4490 " // comment\n" 4491 " int j;\n" 4492 "});", 4493 format("DEBUG({\n" 4494 " int i;\n" 4495 "\n" 4496 " // comment\n" 4497 " int j;\n" 4498 "});")); 4499 4500 verifyFormat("DEBUG({\n" 4501 " if (a)\n" 4502 " return;\n" 4503 "});"); 4504 verifyGoogleFormat("DEBUG({\n" 4505 " if (a) return;\n" 4506 "});"); 4507 FormatStyle Style = getGoogleStyle(); 4508 Style.ColumnLimit = 45; 4509 verifyFormat("Debug(\n" 4510 " aaaaa,\n" 4511 " {\n" 4512 " if (aaaaaaaaaaaaaaaaaaaaaaaa) return;\n" 4513 " },\n" 4514 " a);", 4515 Style); 4516 4517 verifyFormat("SomeFunction({MACRO({ return output; }), b});"); 4518 4519 verifyNoCrash("^{v^{a}}"); 4520 } 4521 4522 TEST_F(FormatTest, FormatNestedBlocksInMacros) { 4523 EXPECT_EQ("#define MACRO() \\\n" 4524 " Debug(aaa, /* force line break */ \\\n" 4525 " { \\\n" 4526 " int i; \\\n" 4527 " int j; \\\n" 4528 " })", 4529 format("#define MACRO() Debug(aaa, /* force line break */ \\\n" 4530 " { int i; int j; })", 4531 getGoogleStyle())); 4532 4533 EXPECT_EQ("#define A \\\n" 4534 " [] { \\\n" 4535 " xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx( \\\n" 4536 " xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); \\\n" 4537 " }", 4538 format("#define A [] { xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx( \\\n" 4539 "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); }", 4540 getGoogleStyle())); 4541 } 4542 4543 TEST_F(FormatTest, PutEmptyBlocksIntoOneLine) { 4544 EXPECT_EQ("{}", format("{}")); 4545 verifyFormat("enum E {};"); 4546 verifyFormat("enum E {}"); 4547 FormatStyle Style = getLLVMStyle(); 4548 Style.SpaceInEmptyBlock = true; 4549 EXPECT_EQ("void f() { }", format("void f() {}", Style)); 4550 Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Empty; 4551 EXPECT_EQ("while (true) { }", format("while (true) {}", Style)); 4552 } 4553 4554 TEST_F(FormatTest, FormatBeginBlockEndMacros) { 4555 FormatStyle Style = getLLVMStyle(); 4556 Style.MacroBlockBegin = "^[A-Z_]+_BEGIN$"; 4557 Style.MacroBlockEnd = "^[A-Z_]+_END$"; 4558 verifyFormat("FOO_BEGIN\n" 4559 " FOO_ENTRY\n" 4560 "FOO_END", 4561 Style); 4562 verifyFormat("FOO_BEGIN\n" 4563 " NESTED_FOO_BEGIN\n" 4564 " NESTED_FOO_ENTRY\n" 4565 " NESTED_FOO_END\n" 4566 "FOO_END", 4567 Style); 4568 verifyFormat("FOO_BEGIN(Foo, Bar)\n" 4569 " int x;\n" 4570 " x = 1;\n" 4571 "FOO_END(Baz)", 4572 Style); 4573 } 4574 4575 //===----------------------------------------------------------------------===// 4576 // Line break tests. 4577 //===----------------------------------------------------------------------===// 4578 4579 TEST_F(FormatTest, PreventConfusingIndents) { 4580 verifyFormat( 4581 "void f() {\n" 4582 " SomeLongMethodName(SomeReallyLongMethod(CallOtherReallyLongMethod(\n" 4583 " parameter, parameter, parameter)),\n" 4584 " SecondLongCall(parameter));\n" 4585 "}"); 4586 verifyFormat( 4587 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 4588 " aaaaaaaaaaaaaaaaaaaaaaaa(\n" 4589 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 4590 " aaaaaaaaaaaaaaaaaaaaaaaa);"); 4591 verifyFormat( 4592 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 4593 " [aaaaaaaaaaaaaaaaaaaaaaaa\n" 4594 " [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]\n" 4595 " [aaaaaaaaaaaaaaaaaaaaaaaa]];"); 4596 verifyFormat( 4597 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<\n" 4598 " aaaaaaaaaaaaaaaaaaaaaaaa<\n" 4599 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>,\n" 4600 " aaaaaaaaaaaaaaaaaaaaaaaa>;"); 4601 verifyFormat("int a = bbbb && ccc &&\n" 4602 " fffff(\n" 4603 "#define A Just forcing a new line\n" 4604 " ddd);"); 4605 } 4606 4607 TEST_F(FormatTest, LineBreakingInBinaryExpressions) { 4608 verifyFormat( 4609 "bool aaaaaaa =\n" 4610 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaa).aaaaaaaaaaaaaaaaaaa() ||\n" 4611 " bbbbbbbb();"); 4612 verifyFormat( 4613 "bool aaaaaaa =\n" 4614 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaa).aaaaaaaaaaaaaaaaaaa() or\n" 4615 " bbbbbbbb();"); 4616 4617 verifyFormat("bool aaaaaaaaaaaaaaaaaaaaa =\n" 4618 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa != bbbbbbbbbbbbbbbbbb &&\n" 4619 " ccccccccc == ddddddddddd;"); 4620 verifyFormat("bool aaaaaaaaaaaaaaaaaaaaa =\n" 4621 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa != bbbbbbbbbbbbbbbbbb and\n" 4622 " ccccccccc == ddddddddddd;"); 4623 verifyFormat( 4624 "bool aaaaaaaaaaaaaaaaaaaaa =\n" 4625 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa not_eq bbbbbbbbbbbbbbbbbb and\n" 4626 " ccccccccc == ddddddddddd;"); 4627 4628 verifyFormat("aaaaaa = aaaaaaa(aaaaaaa, // break\n" 4629 " aaaaaa) &&\n" 4630 " bbbbbb && cccccc;"); 4631 verifyFormat("aaaaaa = aaaaaaa(aaaaaaa, // break\n" 4632 " aaaaaa) >>\n" 4633 " bbbbbb;"); 4634 verifyFormat("aa = Whitespaces.addUntouchableComment(\n" 4635 " SourceMgr.getSpellingColumnNumber(\n" 4636 " TheLine.Last->FormatTok.Tok.getLocation()) -\n" 4637 " 1);"); 4638 4639 verifyFormat("if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n" 4640 " bbbbbbbbbbbbbbbbbb) && // aaaaaaaaaaaaaaaa\n" 4641 " cccccc) {\n}"); 4642 verifyFormat("if constexpr ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n" 4643 " bbbbbbbbbbbbbbbbbb) && // aaaaaaaaaaa\n" 4644 " cccccc) {\n}"); 4645 verifyFormat("if CONSTEXPR ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n" 4646 " bbbbbbbbbbbbbbbbbb) && // aaaaaaaaaaa\n" 4647 " cccccc) {\n}"); 4648 verifyFormat("b = a &&\n" 4649 " // Comment\n" 4650 " b.c && d;"); 4651 4652 // If the LHS of a comparison is not a binary expression itself, the 4653 // additional linebreak confuses many people. 4654 verifyFormat( 4655 "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 4656 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) > 5) {\n" 4657 "}"); 4658 verifyFormat( 4659 "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 4660 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) == 5) {\n" 4661 "}"); 4662 verifyFormat( 4663 "if (aaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaaaaaaaaa(\n" 4664 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) == 5) {\n" 4665 "}"); 4666 verifyFormat( 4667 "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 4668 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) <=> 5) {\n" 4669 "}"); 4670 // Even explicit parentheses stress the precedence enough to make the 4671 // additional break unnecessary. 4672 verifyFormat("if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 4673 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) == 5) {\n" 4674 "}"); 4675 // This cases is borderline, but with the indentation it is still readable. 4676 verifyFormat( 4677 "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 4678 " aaaaaaaaaaaaaaa) > aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 4679 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n" 4680 "}", 4681 getLLVMStyleWithColumns(75)); 4682 4683 // If the LHS is a binary expression, we should still use the additional break 4684 // as otherwise the formatting hides the operator precedence. 4685 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 4686 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n" 4687 " 5) {\n" 4688 "}"); 4689 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 4690 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa <=>\n" 4691 " 5) {\n" 4692 "}"); 4693 4694 FormatStyle OnePerLine = getLLVMStyle(); 4695 OnePerLine.BinPackParameters = false; 4696 verifyFormat( 4697 "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n" 4698 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n" 4699 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}", 4700 OnePerLine); 4701 4702 verifyFormat("int i = someFunction(aaaaaaa, 0)\n" 4703 " .aaa(aaaaaaaaaaaaa) *\n" 4704 " aaaaaaa +\n" 4705 " aaaaaaa;", 4706 getLLVMStyleWithColumns(40)); 4707 } 4708 4709 TEST_F(FormatTest, ExpressionIndentation) { 4710 verifyFormat("bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 4711 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 4712 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n" 4713 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n" 4714 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb +\n" 4715 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb &&\n" 4716 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n" 4717 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >\n" 4718 " ccccccccccccccccccccccccccccccccccccccccc;"); 4719 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n" 4720 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 4721 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n" 4722 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}"); 4723 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 4724 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n" 4725 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n" 4726 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}"); 4727 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n" 4728 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n" 4729 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 4730 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}"); 4731 verifyFormat("if () {\n" 4732 "} else if (aaaaa && bbbbb > // break\n" 4733 " ccccc) {\n" 4734 "}"); 4735 verifyFormat("if () {\n" 4736 "} else if constexpr (aaaaa && bbbbb > // break\n" 4737 " ccccc) {\n" 4738 "}"); 4739 verifyFormat("if () {\n" 4740 "} else if CONSTEXPR (aaaaa && bbbbb > // break\n" 4741 " ccccc) {\n" 4742 "}"); 4743 verifyFormat("if () {\n" 4744 "} else if (aaaaa &&\n" 4745 " bbbbb > // break\n" 4746 " ccccc &&\n" 4747 " ddddd) {\n" 4748 "}"); 4749 4750 // Presence of a trailing comment used to change indentation of b. 4751 verifyFormat("return aaaaaaaaaaaaaaaaaaa +\n" 4752 " b;\n" 4753 "return aaaaaaaaaaaaaaaaaaa +\n" 4754 " b; //", 4755 getLLVMStyleWithColumns(30)); 4756 } 4757 4758 TEST_F(FormatTest, ExpressionIndentationBreakingBeforeOperators) { 4759 // Not sure what the best system is here. Like this, the LHS can be found 4760 // immediately above an operator (everything with the same or a higher 4761 // indent). The RHS is aligned right of the operator and so compasses 4762 // everything until something with the same indent as the operator is found. 4763 // FIXME: Is this a good system? 4764 FormatStyle Style = getLLVMStyle(); 4765 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 4766 verifyFormat( 4767 "bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 4768 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 4769 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 4770 " == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 4771 " * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 4772 " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 4773 " && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 4774 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 4775 " > ccccccccccccccccccccccccccccccccccccccccc;", 4776 Style); 4777 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 4778 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 4779 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 4780 " == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}", 4781 Style); 4782 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 4783 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 4784 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 4785 " == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}", 4786 Style); 4787 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 4788 " == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 4789 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 4790 " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}", 4791 Style); 4792 verifyFormat("if () {\n" 4793 "} else if (aaaaa\n" 4794 " && bbbbb // break\n" 4795 " > ccccc) {\n" 4796 "}", 4797 Style); 4798 verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 4799 " && bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;", 4800 Style); 4801 verifyFormat("return (a)\n" 4802 " // comment\n" 4803 " + b;", 4804 Style); 4805 verifyFormat( 4806 "int aaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 4807 " * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 4808 " + cc;", 4809 Style); 4810 4811 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 4812 " = aaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaa;", 4813 Style); 4814 4815 // Forced by comments. 4816 verifyFormat( 4817 "unsigned ContentSize =\n" 4818 " sizeof(int16_t) // DWARF ARange version number\n" 4819 " + sizeof(int32_t) // Offset of CU in the .debug_info section\n" 4820 " + sizeof(int8_t) // Pointer Size (in bytes)\n" 4821 " + sizeof(int8_t); // Segment Size (in bytes)"); 4822 4823 verifyFormat("return boost::fusion::at_c<0>(iiii).second\n" 4824 " == boost::fusion::at_c<1>(iiii).second;", 4825 Style); 4826 4827 Style.ColumnLimit = 60; 4828 verifyFormat("zzzzzzzzzz\n" 4829 " = bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 4830 " >> aaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaa);", 4831 Style); 4832 4833 Style.ColumnLimit = 80; 4834 Style.IndentWidth = 4; 4835 Style.TabWidth = 4; 4836 Style.UseTab = FormatStyle::UT_Always; 4837 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 4838 Style.AlignOperands = FormatStyle::OAS_DontAlign; 4839 EXPECT_EQ("return someVeryVeryLongConditionThatBarelyFitsOnALine\n" 4840 "\t&& (someOtherLongishConditionPart1\n" 4841 "\t\t|| someOtherEvenLongerNestedConditionPart2);", 4842 format("return someVeryVeryLongConditionThatBarelyFitsOnALine && " 4843 "(someOtherLongishConditionPart1 || " 4844 "someOtherEvenLongerNestedConditionPart2);", 4845 Style)); 4846 } 4847 4848 TEST_F(FormatTest, ExpressionIndentationStrictAlign) { 4849 FormatStyle Style = getLLVMStyle(); 4850 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 4851 Style.AlignOperands = FormatStyle::OAS_AlignAfterOperator; 4852 4853 verifyFormat("bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 4854 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 4855 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 4856 " == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 4857 " * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 4858 " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 4859 " && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 4860 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 4861 " > ccccccccccccccccccccccccccccccccccccccccc;", 4862 Style); 4863 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 4864 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 4865 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 4866 " == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}", 4867 Style); 4868 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 4869 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 4870 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 4871 " == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}", 4872 Style); 4873 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 4874 " == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 4875 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 4876 " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}", 4877 Style); 4878 verifyFormat("if () {\n" 4879 "} else if (aaaaa\n" 4880 " && bbbbb // break\n" 4881 " > ccccc) {\n" 4882 "}", 4883 Style); 4884 verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 4885 " && bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;", 4886 Style); 4887 verifyFormat("return (a)\n" 4888 " // comment\n" 4889 " + b;", 4890 Style); 4891 verifyFormat( 4892 "int aaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 4893 " * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 4894 " + cc;", 4895 Style); 4896 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n" 4897 " : bbbbbbbbbbbbbbbb ? 2222222222222222\n" 4898 " : 3333333333333333;", 4899 Style); 4900 verifyFormat( 4901 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 4902 " : ccccccccccccccc ? dddddddddddddddddd\n" 4903 " : eeeeeeeeeeeeeeeeee)\n" 4904 " : bbbbbbbbbbbbbbbb ? 2222222222222222\n" 4905 " : 3333333333333333;", 4906 Style); 4907 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 4908 " = aaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaa;", 4909 Style); 4910 4911 verifyFormat("return boost::fusion::at_c<0>(iiii).second\n" 4912 " == boost::fusion::at_c<1>(iiii).second;", 4913 Style); 4914 4915 Style.ColumnLimit = 60; 4916 verifyFormat("zzzzzzzzzzzzz\n" 4917 " = bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 4918 " >> aaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaa);", 4919 Style); 4920 4921 // Forced by comments. 4922 Style.ColumnLimit = 80; 4923 verifyFormat( 4924 "unsigned ContentSize\n" 4925 " = sizeof(int16_t) // DWARF ARange version number\n" 4926 " + sizeof(int32_t) // Offset of CU in the .debug_info section\n" 4927 " + sizeof(int8_t) // Pointer Size (in bytes)\n" 4928 " + sizeof(int8_t); // Segment Size (in bytes)", 4929 Style); 4930 4931 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment; 4932 verifyFormat( 4933 "unsigned ContentSize =\n" 4934 " sizeof(int16_t) // DWARF ARange version number\n" 4935 " + sizeof(int32_t) // Offset of CU in the .debug_info section\n" 4936 " + sizeof(int8_t) // Pointer Size (in bytes)\n" 4937 " + sizeof(int8_t); // Segment Size (in bytes)", 4938 Style); 4939 4940 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None; 4941 verifyFormat( 4942 "unsigned ContentSize =\n" 4943 " sizeof(int16_t) // DWARF ARange version number\n" 4944 " + sizeof(int32_t) // Offset of CU in the .debug_info section\n" 4945 " + sizeof(int8_t) // Pointer Size (in bytes)\n" 4946 " + sizeof(int8_t); // Segment Size (in bytes)", 4947 Style); 4948 } 4949 4950 TEST_F(FormatTest, EnforcedOperatorWraps) { 4951 // Here we'd like to wrap after the || operators, but a comment is forcing an 4952 // earlier wrap. 4953 verifyFormat("bool x = aaaaa //\n" 4954 " || bbbbb\n" 4955 " //\n" 4956 " || cccc;"); 4957 } 4958 4959 TEST_F(FormatTest, NoOperandAlignment) { 4960 FormatStyle Style = getLLVMStyle(); 4961 Style.AlignOperands = FormatStyle::OAS_DontAlign; 4962 verifyFormat("aaaaaaaaaaaaaa(aaaaaaaaaaaa,\n" 4963 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 4964 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 4965 Style); 4966 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment; 4967 verifyFormat("bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 4968 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 4969 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 4970 " == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 4971 " * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 4972 " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 4973 " && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 4974 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 4975 " > ccccccccccccccccccccccccccccccccccccccccc;", 4976 Style); 4977 4978 verifyFormat("int aaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 4979 " * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 4980 " + cc;", 4981 Style); 4982 verifyFormat("int a = aa\n" 4983 " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 4984 " * cccccccccccccccccccccccccccccccccccc;\n", 4985 Style); 4986 4987 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 4988 verifyFormat("return (a > b\n" 4989 " // comment1\n" 4990 " // comment2\n" 4991 " || c);", 4992 Style); 4993 } 4994 4995 TEST_F(FormatTest, BreakingBeforeNonAssigmentOperators) { 4996 FormatStyle Style = getLLVMStyle(); 4997 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment; 4998 verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n" 4999 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 5000 " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;", 5001 Style); 5002 } 5003 5004 TEST_F(FormatTest, AllowBinPackingInsideArguments) { 5005 FormatStyle Style = getLLVMStyle(); 5006 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment; 5007 Style.BinPackArguments = false; 5008 Style.ColumnLimit = 40; 5009 verifyFormat("void test() {\n" 5010 " someFunction(\n" 5011 " this + argument + is + quite\n" 5012 " + long + so + it + gets + wrapped\n" 5013 " + but + remains + bin - packed);\n" 5014 "}", 5015 Style); 5016 verifyFormat("void test() {\n" 5017 " someFunction(arg1,\n" 5018 " this + argument + is\n" 5019 " + quite + long + so\n" 5020 " + it + gets + wrapped\n" 5021 " + but + remains + bin\n" 5022 " - packed,\n" 5023 " arg3);\n" 5024 "}", 5025 Style); 5026 verifyFormat("void test() {\n" 5027 " someFunction(\n" 5028 " arg1,\n" 5029 " this + argument + has\n" 5030 " + anotherFunc(nested,\n" 5031 " calls + whose\n" 5032 " + arguments\n" 5033 " + are + also\n" 5034 " + wrapped,\n" 5035 " in + addition)\n" 5036 " + to + being + bin - packed,\n" 5037 " arg3);\n" 5038 "}", 5039 Style); 5040 5041 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None; 5042 verifyFormat("void test() {\n" 5043 " someFunction(\n" 5044 " arg1,\n" 5045 " this + argument + has +\n" 5046 " anotherFunc(nested,\n" 5047 " calls + whose +\n" 5048 " arguments +\n" 5049 " are + also +\n" 5050 " wrapped,\n" 5051 " in + addition) +\n" 5052 " to + being + bin - packed,\n" 5053 " arg3);\n" 5054 "}", 5055 Style); 5056 } 5057 5058 TEST_F(FormatTest, ConstructorInitializers) { 5059 verifyFormat("Constructor() : Initializer(FitsOnTheLine) {}"); 5060 verifyFormat("Constructor() : Inttializer(FitsOnTheLine) {}", 5061 getLLVMStyleWithColumns(45)); 5062 verifyFormat("Constructor()\n" 5063 " : Inttializer(FitsOnTheLine) {}", 5064 getLLVMStyleWithColumns(44)); 5065 verifyFormat("Constructor()\n" 5066 " : Inttializer(FitsOnTheLine) {}", 5067 getLLVMStyleWithColumns(43)); 5068 5069 verifyFormat("template <typename T>\n" 5070 "Constructor() : Initializer(FitsOnTheLine) {}", 5071 getLLVMStyleWithColumns(45)); 5072 5073 verifyFormat( 5074 "SomeClass::Constructor()\n" 5075 " : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}"); 5076 5077 verifyFormat( 5078 "SomeClass::Constructor()\n" 5079 " : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 5080 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}"); 5081 verifyFormat( 5082 "SomeClass::Constructor()\n" 5083 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 5084 " aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}"); 5085 verifyFormat("Constructor(aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 5086 " aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 5087 " : aaaaaaaaaa(aaaaaa) {}"); 5088 5089 verifyFormat("Constructor()\n" 5090 " : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 5091 " aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 5092 " aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 5093 " aaaaaaaaaaaaaaaaaaaaaaa() {}"); 5094 5095 verifyFormat("Constructor()\n" 5096 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 5097 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}"); 5098 5099 verifyFormat("Constructor(int Parameter = 0)\n" 5100 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa),\n" 5101 " aaaaaaaaaaaa(aaaaaaaaaaaaaaaaa) {}"); 5102 verifyFormat("Constructor()\n" 5103 " : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbbbbb(b) {\n" 5104 "}", 5105 getLLVMStyleWithColumns(60)); 5106 verifyFormat("Constructor()\n" 5107 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 5108 " aaaaaaaaaaaaaaaaaaaaaaaaa(aaaa, aaaa)) {}"); 5109 5110 // Here a line could be saved by splitting the second initializer onto two 5111 // lines, but that is not desirable. 5112 verifyFormat("Constructor()\n" 5113 " : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaa),\n" 5114 " aaaaaaaaaaa(aaaaaaaaaaa),\n" 5115 " aaaaaaaaaaaaaaaaaaaaat(aaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}"); 5116 5117 FormatStyle OnePerLine = getLLVMStyle(); 5118 OnePerLine.ConstructorInitializerAllOnOneLineOrOnePerLine = true; 5119 OnePerLine.AllowAllParametersOfDeclarationOnNextLine = false; 5120 verifyFormat("SomeClass::Constructor()\n" 5121 " : aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 5122 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 5123 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", 5124 OnePerLine); 5125 verifyFormat("SomeClass::Constructor()\n" 5126 " : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), // Some comment\n" 5127 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 5128 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", 5129 OnePerLine); 5130 verifyFormat("MyClass::MyClass(int var)\n" 5131 " : some_var_(var), // 4 space indent\n" 5132 " some_other_var_(var + 1) { // lined up\n" 5133 "}", 5134 OnePerLine); 5135 verifyFormat("Constructor()\n" 5136 " : aaaaa(aaaaaa),\n" 5137 " aaaaa(aaaaaa),\n" 5138 " aaaaa(aaaaaa),\n" 5139 " aaaaa(aaaaaa),\n" 5140 " aaaaa(aaaaaa) {}", 5141 OnePerLine); 5142 verifyFormat("Constructor()\n" 5143 " : aaaaa(aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa,\n" 5144 " aaaaaaaaaaaaaaaaaaaaaa) {}", 5145 OnePerLine); 5146 OnePerLine.BinPackParameters = false; 5147 verifyFormat( 5148 "Constructor()\n" 5149 " : aaaaaaaaaaaaaaaaaaaaaaaa(\n" 5150 " aaaaaaaaaaa().aaa(),\n" 5151 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}", 5152 OnePerLine); 5153 OnePerLine.ColumnLimit = 60; 5154 verifyFormat("Constructor()\n" 5155 " : aaaaaaaaaaaaaaaaaaaa(a),\n" 5156 " bbbbbbbbbbbbbbbbbbbbbbbb(b) {}", 5157 OnePerLine); 5158 5159 EXPECT_EQ("Constructor()\n" 5160 " : // Comment forcing unwanted break.\n" 5161 " aaaa(aaaa) {}", 5162 format("Constructor() :\n" 5163 " // Comment forcing unwanted break.\n" 5164 " aaaa(aaaa) {}")); 5165 } 5166 5167 TEST_F(FormatTest, AllowAllConstructorInitializersOnNextLine) { 5168 FormatStyle Style = getLLVMStyle(); 5169 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma; 5170 Style.ColumnLimit = 60; 5171 Style.ConstructorInitializerAllOnOneLineOrOnePerLine = true; 5172 Style.AllowAllConstructorInitializersOnNextLine = true; 5173 Style.BinPackParameters = false; 5174 5175 for (int i = 0; i < 4; ++i) { 5176 // Test all combinations of parameters that should not have an effect. 5177 Style.AllowAllParametersOfDeclarationOnNextLine = i & 1; 5178 Style.AllowAllArgumentsOnNextLine = i & 2; 5179 5180 Style.AllowAllConstructorInitializersOnNextLine = true; 5181 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma; 5182 verifyFormat("Constructor()\n" 5183 " : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}", 5184 Style); 5185 verifyFormat("Constructor() : a(a), b(b) {}", Style); 5186 5187 Style.AllowAllConstructorInitializersOnNextLine = false; 5188 verifyFormat("Constructor()\n" 5189 " : aaaaaaaaaaaaaaaaaaaa(a)\n" 5190 " , bbbbbbbbbbbbbbbbbbbbb(b) {}", 5191 Style); 5192 verifyFormat("Constructor() : a(a), b(b) {}", Style); 5193 5194 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon; 5195 Style.AllowAllConstructorInitializersOnNextLine = true; 5196 verifyFormat("Constructor()\n" 5197 " : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}", 5198 Style); 5199 5200 Style.AllowAllConstructorInitializersOnNextLine = false; 5201 verifyFormat("Constructor()\n" 5202 " : aaaaaaaaaaaaaaaaaaaa(a),\n" 5203 " bbbbbbbbbbbbbbbbbbbbb(b) {}", 5204 Style); 5205 5206 Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon; 5207 Style.AllowAllConstructorInitializersOnNextLine = true; 5208 verifyFormat("Constructor() :\n" 5209 " aaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}", 5210 Style); 5211 5212 Style.AllowAllConstructorInitializersOnNextLine = false; 5213 verifyFormat("Constructor() :\n" 5214 " aaaaaaaaaaaaaaaaaa(a),\n" 5215 " bbbbbbbbbbbbbbbbbbbbb(b) {}", 5216 Style); 5217 } 5218 5219 // Test interactions between AllowAllParametersOfDeclarationOnNextLine and 5220 // AllowAllConstructorInitializersOnNextLine in all 5221 // BreakConstructorInitializers modes 5222 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma; 5223 Style.AllowAllParametersOfDeclarationOnNextLine = true; 5224 Style.AllowAllConstructorInitializersOnNextLine = false; 5225 verifyFormat("SomeClassWithALongName::Constructor(\n" 5226 " int aaaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbbb)\n" 5227 " : aaaaaaaaaaaaaaaaaaaa(a)\n" 5228 " , bbbbbbbbbbbbbbbbbbbbb(b) {}", 5229 Style); 5230 5231 Style.AllowAllConstructorInitializersOnNextLine = true; 5232 verifyFormat("SomeClassWithALongName::Constructor(\n" 5233 " int aaaaaaaaaaaaaaaaaaaaaaaa,\n" 5234 " int bbbbbbbbbbbbb,\n" 5235 " int cccccccccccccccc)\n" 5236 " : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}", 5237 Style); 5238 5239 Style.AllowAllParametersOfDeclarationOnNextLine = false; 5240 Style.AllowAllConstructorInitializersOnNextLine = false; 5241 verifyFormat("SomeClassWithALongName::Constructor(\n" 5242 " int aaaaaaaaaaaaaaaaaaaaaaaa,\n" 5243 " int bbbbbbbbbbbbb)\n" 5244 " : aaaaaaaaaaaaaaaaaaaa(a)\n" 5245 " , bbbbbbbbbbbbbbbbbbbbb(b) {}", 5246 Style); 5247 5248 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon; 5249 5250 Style.AllowAllParametersOfDeclarationOnNextLine = true; 5251 verifyFormat("SomeClassWithALongName::Constructor(\n" 5252 " int aaaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbbb)\n" 5253 " : aaaaaaaaaaaaaaaaaaaa(a),\n" 5254 " bbbbbbbbbbbbbbbbbbbbb(b) {}", 5255 Style); 5256 5257 Style.AllowAllConstructorInitializersOnNextLine = true; 5258 verifyFormat("SomeClassWithALongName::Constructor(\n" 5259 " int aaaaaaaaaaaaaaaaaaaaaaaa,\n" 5260 " int bbbbbbbbbbbbb,\n" 5261 " int cccccccccccccccc)\n" 5262 " : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}", 5263 Style); 5264 5265 Style.AllowAllParametersOfDeclarationOnNextLine = false; 5266 Style.AllowAllConstructorInitializersOnNextLine = false; 5267 verifyFormat("SomeClassWithALongName::Constructor(\n" 5268 " int aaaaaaaaaaaaaaaaaaaaaaaa,\n" 5269 " int bbbbbbbbbbbbb)\n" 5270 " : aaaaaaaaaaaaaaaaaaaa(a),\n" 5271 " bbbbbbbbbbbbbbbbbbbbb(b) {}", 5272 Style); 5273 5274 Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon; 5275 Style.AllowAllParametersOfDeclarationOnNextLine = true; 5276 verifyFormat("SomeClassWithALongName::Constructor(\n" 5277 " int aaaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbbb) :\n" 5278 " aaaaaaaaaaaaaaaaaaaa(a),\n" 5279 " bbbbbbbbbbbbbbbbbbbbb(b) {}", 5280 Style); 5281 5282 Style.AllowAllConstructorInitializersOnNextLine = true; 5283 verifyFormat("SomeClassWithALongName::Constructor(\n" 5284 " int aaaaaaaaaaaaaaaaaaaaaaaa,\n" 5285 " int bbbbbbbbbbbbb,\n" 5286 " int cccccccccccccccc) :\n" 5287 " aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}", 5288 Style); 5289 5290 Style.AllowAllParametersOfDeclarationOnNextLine = false; 5291 Style.AllowAllConstructorInitializersOnNextLine = false; 5292 verifyFormat("SomeClassWithALongName::Constructor(\n" 5293 " int aaaaaaaaaaaaaaaaaaaaaaaa,\n" 5294 " int bbbbbbbbbbbbb) :\n" 5295 " aaaaaaaaaaaaaaaaaaaa(a),\n" 5296 " bbbbbbbbbbbbbbbbbbbbb(b) {}", 5297 Style); 5298 } 5299 5300 TEST_F(FormatTest, AllowAllArgumentsOnNextLine) { 5301 FormatStyle Style = getLLVMStyle(); 5302 Style.ColumnLimit = 60; 5303 Style.BinPackArguments = false; 5304 for (int i = 0; i < 4; ++i) { 5305 // Test all combinations of parameters that should not have an effect. 5306 Style.AllowAllParametersOfDeclarationOnNextLine = i & 1; 5307 Style.AllowAllConstructorInitializersOnNextLine = i & 2; 5308 5309 Style.AllowAllArgumentsOnNextLine = true; 5310 verifyFormat("void foo() {\n" 5311 " FunctionCallWithReallyLongName(\n" 5312 " aaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbb);\n" 5313 "}", 5314 Style); 5315 Style.AllowAllArgumentsOnNextLine = false; 5316 verifyFormat("void foo() {\n" 5317 " FunctionCallWithReallyLongName(\n" 5318 " aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 5319 " bbbbbbbbbbbb);\n" 5320 "}", 5321 Style); 5322 5323 Style.AllowAllArgumentsOnNextLine = true; 5324 verifyFormat("void foo() {\n" 5325 " auto VariableWithReallyLongName = {\n" 5326 " aaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbb};\n" 5327 "}", 5328 Style); 5329 Style.AllowAllArgumentsOnNextLine = false; 5330 verifyFormat("void foo() {\n" 5331 " auto VariableWithReallyLongName = {\n" 5332 " aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 5333 " bbbbbbbbbbbb};\n" 5334 "}", 5335 Style); 5336 } 5337 5338 // This parameter should not affect declarations. 5339 Style.BinPackParameters = false; 5340 Style.AllowAllArgumentsOnNextLine = false; 5341 Style.AllowAllParametersOfDeclarationOnNextLine = true; 5342 verifyFormat("void FunctionCallWithReallyLongName(\n" 5343 " int aaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbb);", 5344 Style); 5345 Style.AllowAllParametersOfDeclarationOnNextLine = false; 5346 verifyFormat("void FunctionCallWithReallyLongName(\n" 5347 " int aaaaaaaaaaaaaaaaaaaaaaa,\n" 5348 " int bbbbbbbbbbbb);", 5349 Style); 5350 } 5351 5352 TEST_F(FormatTest, AllowAllArgumentsOnNextLineDontAlign) { 5353 // Check that AllowAllArgumentsOnNextLine is respected for both BAS_DontAlign 5354 // and BAS_Align. 5355 auto Style = getLLVMStyle(); 5356 Style.ColumnLimit = 35; 5357 StringRef Input = "functionCall(paramA, paramB, paramC);\n" 5358 "void functionDecl(int A, int B, int C);"; 5359 Style.AllowAllArgumentsOnNextLine = false; 5360 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 5361 EXPECT_EQ(StringRef("functionCall(paramA, paramB,\n" 5362 " paramC);\n" 5363 "void functionDecl(int A, int B,\n" 5364 " int C);"), 5365 format(Input, Style)); 5366 Style.AlignAfterOpenBracket = FormatStyle::BAS_Align; 5367 EXPECT_EQ(StringRef("functionCall(paramA, paramB,\n" 5368 " paramC);\n" 5369 "void functionDecl(int A, int B,\n" 5370 " int C);"), 5371 format(Input, Style)); 5372 // However, BAS_AlwaysBreak should take precedence over 5373 // AllowAllArgumentsOnNextLine. 5374 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 5375 EXPECT_EQ(StringRef("functionCall(\n" 5376 " paramA, paramB, paramC);\n" 5377 "void functionDecl(\n" 5378 " int A, int B, int C);"), 5379 format(Input, Style)); 5380 5381 // When AllowAllArgumentsOnNextLine is set, we prefer breaking before the 5382 // first argument. 5383 Style.AllowAllArgumentsOnNextLine = true; 5384 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 5385 EXPECT_EQ(StringRef("functionCall(\n" 5386 " paramA, paramB, paramC);\n" 5387 "void functionDecl(\n" 5388 " int A, int B, int C);"), 5389 format(Input, Style)); 5390 // It wouldn't fit on one line with aligned parameters so this setting 5391 // doesn't change anything for BAS_Align. 5392 Style.AlignAfterOpenBracket = FormatStyle::BAS_Align; 5393 EXPECT_EQ(StringRef("functionCall(paramA, paramB,\n" 5394 " paramC);\n" 5395 "void functionDecl(int A, int B,\n" 5396 " int C);"), 5397 format(Input, Style)); 5398 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 5399 EXPECT_EQ(StringRef("functionCall(\n" 5400 " paramA, paramB, paramC);\n" 5401 "void functionDecl(\n" 5402 " int A, int B, int C);"), 5403 format(Input, Style)); 5404 } 5405 5406 TEST_F(FormatTest, BreakConstructorInitializersAfterColon) { 5407 FormatStyle Style = getLLVMStyle(); 5408 Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon; 5409 5410 verifyFormat("Constructor() : Initializer(FitsOnTheLine) {}"); 5411 verifyFormat("Constructor() : Initializer(FitsOnTheLine) {}", 5412 getStyleWithColumns(Style, 45)); 5413 verifyFormat("Constructor() :\n" 5414 " Initializer(FitsOnTheLine) {}", 5415 getStyleWithColumns(Style, 44)); 5416 verifyFormat("Constructor() :\n" 5417 " Initializer(FitsOnTheLine) {}", 5418 getStyleWithColumns(Style, 43)); 5419 5420 verifyFormat("template <typename T>\n" 5421 "Constructor() : Initializer(FitsOnTheLine) {}", 5422 getStyleWithColumns(Style, 50)); 5423 Style.ConstructorInitializerAllOnOneLineOrOnePerLine = true; 5424 verifyFormat( 5425 "SomeClass::Constructor() :\n" 5426 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}", 5427 Style); 5428 5429 Style.ConstructorInitializerAllOnOneLineOrOnePerLine = false; 5430 verifyFormat( 5431 "SomeClass::Constructor() :\n" 5432 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}", 5433 Style); 5434 5435 verifyFormat( 5436 "SomeClass::Constructor() :\n" 5437 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 5438 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", 5439 Style); 5440 verifyFormat( 5441 "SomeClass::Constructor() :\n" 5442 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 5443 " aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}", 5444 Style); 5445 verifyFormat("Constructor(aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 5446 " aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) :\n" 5447 " aaaaaaaaaa(aaaaaa) {}", 5448 Style); 5449 5450 verifyFormat("Constructor() :\n" 5451 " aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 5452 " aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 5453 " aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 5454 " aaaaaaaaaaaaaaaaaaaaaaa() {}", 5455 Style); 5456 5457 verifyFormat("Constructor() :\n" 5458 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 5459 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}", 5460 Style); 5461 5462 verifyFormat("Constructor(int Parameter = 0) :\n" 5463 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa),\n" 5464 " aaaaaaaaaaaa(aaaaaaaaaaaaaaaaa) {}", 5465 Style); 5466 verifyFormat("Constructor() :\n" 5467 " aaaaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbbbbb(b) {\n" 5468 "}", 5469 getStyleWithColumns(Style, 60)); 5470 verifyFormat("Constructor() :\n" 5471 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 5472 " aaaaaaaaaaaaaaaaaaaaaaaaa(aaaa, aaaa)) {}", 5473 Style); 5474 5475 // Here a line could be saved by splitting the second initializer onto two 5476 // lines, but that is not desirable. 5477 verifyFormat("Constructor() :\n" 5478 " aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaa),\n" 5479 " aaaaaaaaaaa(aaaaaaaaaaa),\n" 5480 " aaaaaaaaaaaaaaaaaaaaat(aaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}", 5481 Style); 5482 5483 FormatStyle OnePerLine = Style; 5484 OnePerLine.ConstructorInitializerAllOnOneLineOrOnePerLine = true; 5485 OnePerLine.AllowAllConstructorInitializersOnNextLine = false; 5486 verifyFormat("SomeClass::Constructor() :\n" 5487 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 5488 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 5489 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", 5490 OnePerLine); 5491 verifyFormat("SomeClass::Constructor() :\n" 5492 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa), // Some comment\n" 5493 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 5494 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", 5495 OnePerLine); 5496 verifyFormat("MyClass::MyClass(int var) :\n" 5497 " some_var_(var), // 4 space indent\n" 5498 " some_other_var_(var + 1) { // lined up\n" 5499 "}", 5500 OnePerLine); 5501 verifyFormat("Constructor() :\n" 5502 " aaaaa(aaaaaa),\n" 5503 " aaaaa(aaaaaa),\n" 5504 " aaaaa(aaaaaa),\n" 5505 " aaaaa(aaaaaa),\n" 5506 " aaaaa(aaaaaa) {}", 5507 OnePerLine); 5508 verifyFormat("Constructor() :\n" 5509 " aaaaa(aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa,\n" 5510 " aaaaaaaaaaaaaaaaaaaaaa) {}", 5511 OnePerLine); 5512 OnePerLine.BinPackParameters = false; 5513 verifyFormat("Constructor() :\n" 5514 " aaaaaaaaaaaaaaaaaaaaaaaa(\n" 5515 " aaaaaaaaaaa().aaa(),\n" 5516 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}", 5517 OnePerLine); 5518 OnePerLine.ColumnLimit = 60; 5519 verifyFormat("Constructor() :\n" 5520 " aaaaaaaaaaaaaaaaaaaa(a),\n" 5521 " bbbbbbbbbbbbbbbbbbbbbbbb(b) {}", 5522 OnePerLine); 5523 5524 EXPECT_EQ("Constructor() :\n" 5525 " // Comment forcing unwanted break.\n" 5526 " aaaa(aaaa) {}", 5527 format("Constructor() :\n" 5528 " // Comment forcing unwanted break.\n" 5529 " aaaa(aaaa) {}", 5530 Style)); 5531 5532 Style.ColumnLimit = 0; 5533 verifyFormat("SomeClass::Constructor() :\n" 5534 " a(a) {}", 5535 Style); 5536 verifyFormat("SomeClass::Constructor() noexcept :\n" 5537 " a(a) {}", 5538 Style); 5539 verifyFormat("SomeClass::Constructor() :\n" 5540 " a(a), b(b), c(c) {}", 5541 Style); 5542 verifyFormat("SomeClass::Constructor() :\n" 5543 " a(a) {\n" 5544 " foo();\n" 5545 " bar();\n" 5546 "}", 5547 Style); 5548 5549 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 5550 verifyFormat("SomeClass::Constructor() :\n" 5551 " a(a), b(b), c(c) {\n" 5552 "}", 5553 Style); 5554 verifyFormat("SomeClass::Constructor() :\n" 5555 " a(a) {\n" 5556 "}", 5557 Style); 5558 5559 Style.ColumnLimit = 80; 5560 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All; 5561 Style.ConstructorInitializerIndentWidth = 2; 5562 verifyFormat("SomeClass::Constructor() : a(a), b(b), c(c) {}", Style); 5563 verifyFormat("SomeClass::Constructor() :\n" 5564 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 5565 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {}", 5566 Style); 5567 5568 // `ConstructorInitializerIndentWidth` actually applies to InheritanceList as 5569 // well 5570 Style.BreakInheritanceList = FormatStyle::BILS_BeforeColon; 5571 verifyFormat( 5572 "class SomeClass\n" 5573 " : public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 5574 " public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};", 5575 Style); 5576 Style.BreakInheritanceList = FormatStyle::BILS_BeforeComma; 5577 verifyFormat( 5578 "class SomeClass\n" 5579 " : public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 5580 " , public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};", 5581 Style); 5582 Style.BreakInheritanceList = FormatStyle::BILS_AfterColon; 5583 verifyFormat( 5584 "class SomeClass :\n" 5585 " public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 5586 " public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};", 5587 Style); 5588 } 5589 5590 #ifndef EXPENSIVE_CHECKS 5591 // Expensive checks enables libstdc++ checking which includes validating the 5592 // state of ranges used in std::priority_queue - this blows out the 5593 // runtime/scalability of the function and makes this test unacceptably slow. 5594 TEST_F(FormatTest, MemoizationTests) { 5595 // This breaks if the memoization lookup does not take \c Indent and 5596 // \c LastSpace into account. 5597 verifyFormat( 5598 "extern CFRunLoopTimerRef\n" 5599 "CFRunLoopTimerCreate(CFAllocatorRef allocato, CFAbsoluteTime fireDate,\n" 5600 " CFTimeInterval interval, CFOptionFlags flags,\n" 5601 " CFIndex order, CFRunLoopTimerCallBack callout,\n" 5602 " CFRunLoopTimerContext *context) {}"); 5603 5604 // Deep nesting somewhat works around our memoization. 5605 verifyFormat( 5606 "aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n" 5607 " aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n" 5608 " aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n" 5609 " aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n" 5610 " aaaaa())))))))))))))))))))))))))))))))))))))));", 5611 getLLVMStyleWithColumns(65)); 5612 verifyFormat( 5613 "aaaaa(\n" 5614 " aaaaa,\n" 5615 " aaaaa(\n" 5616 " aaaaa,\n" 5617 " aaaaa(\n" 5618 " aaaaa,\n" 5619 " aaaaa(\n" 5620 " aaaaa,\n" 5621 " aaaaa(\n" 5622 " aaaaa,\n" 5623 " aaaaa(\n" 5624 " aaaaa,\n" 5625 " aaaaa(\n" 5626 " aaaaa,\n" 5627 " aaaaa(\n" 5628 " aaaaa,\n" 5629 " aaaaa(\n" 5630 " aaaaa,\n" 5631 " aaaaa(\n" 5632 " aaaaa,\n" 5633 " aaaaa(\n" 5634 " aaaaa,\n" 5635 " aaaaa(\n" 5636 " aaaaa,\n" 5637 " aaaaa))))))))))));", 5638 getLLVMStyleWithColumns(65)); 5639 verifyFormat( 5640 "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" 5641 " a),\n" 5642 " a),\n" 5643 " a),\n" 5644 " a),\n" 5645 " a),\n" 5646 " a),\n" 5647 " a),\n" 5648 " a),\n" 5649 " a),\n" 5650 " a),\n" 5651 " a),\n" 5652 " a),\n" 5653 " a),\n" 5654 " a),\n" 5655 " a),\n" 5656 " a),\n" 5657 " a)", 5658 getLLVMStyleWithColumns(65)); 5659 5660 // This test takes VERY long when memoization is broken. 5661 FormatStyle OnePerLine = getLLVMStyle(); 5662 OnePerLine.ConstructorInitializerAllOnOneLineOrOnePerLine = true; 5663 OnePerLine.BinPackParameters = false; 5664 std::string input = "Constructor()\n" 5665 " : aaaa(a,\n"; 5666 for (unsigned i = 0, e = 80; i != e; ++i) { 5667 input += " a,\n"; 5668 } 5669 input += " a) {}"; 5670 verifyFormat(input, OnePerLine); 5671 } 5672 #endif 5673 5674 TEST_F(FormatTest, BreaksAsHighAsPossible) { 5675 verifyFormat( 5676 "void f() {\n" 5677 " if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaa && aaaaaaaaaaaaaaaaaaaaaaaaaa) ||\n" 5678 " (bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb && bbbbbbbbbbbbbbbbbbbbbbbbbb))\n" 5679 " f();\n" 5680 "}"); 5681 verifyFormat("if (Intervals[i].getRange().getFirst() <\n" 5682 " Intervals[i - 1].getRange().getLast()) {\n}"); 5683 } 5684 5685 TEST_F(FormatTest, BreaksFunctionDeclarations) { 5686 // Principially, we break function declarations in a certain order: 5687 // 1) break amongst arguments. 5688 verifyFormat("Aaaaaaaaaaaaaa bbbbbbbbbbbbbb(Cccccccccccccc cccccccccccccc,\n" 5689 " Cccccccccccccc cccccccccccccc);"); 5690 verifyFormat("template <class TemplateIt>\n" 5691 "SomeReturnType SomeFunction(TemplateIt begin, TemplateIt end,\n" 5692 " TemplateIt *stop) {}"); 5693 5694 // 2) break after return type. 5695 verifyFormat( 5696 "Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 5697 "bbbbbbbbbbbbbb(Cccccccccccccc cccccccccccccccccccccccccc);", 5698 getGoogleStyle()); 5699 5700 // 3) break after (. 5701 verifyFormat( 5702 "Aaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbb(\n" 5703 " Cccccccccccccccccccccccccccccc cccccccccccccccccccccccccccccccc);", 5704 getGoogleStyle()); 5705 5706 // 4) break before after nested name specifiers. 5707 verifyFormat( 5708 "Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 5709 "SomeClasssssssssssssssssssssssssssssssssssssss::\n" 5710 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(Cccccccccccccc cccccccccc);", 5711 getGoogleStyle()); 5712 5713 // However, there are exceptions, if a sufficient amount of lines can be 5714 // saved. 5715 // FIXME: The precise cut-offs wrt. the number of saved lines might need some 5716 // more adjusting. 5717 verifyFormat("Aaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbb(Cccccccccccccc cccccccccc,\n" 5718 " Cccccccccccccc cccccccccc,\n" 5719 " Cccccccccccccc cccccccccc,\n" 5720 " Cccccccccccccc cccccccccc,\n" 5721 " Cccccccccccccc cccccccccc);"); 5722 verifyFormat( 5723 "Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 5724 "bbbbbbbbbbb(Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n" 5725 " Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n" 5726 " Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc);", 5727 getGoogleStyle()); 5728 verifyFormat( 5729 "Aaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(Cccccccccccccc cccccccccc,\n" 5730 " Cccccccccccccc cccccccccc,\n" 5731 " Cccccccccccccc cccccccccc,\n" 5732 " Cccccccccccccc cccccccccc,\n" 5733 " Cccccccccccccc cccccccccc,\n" 5734 " Cccccccccccccc cccccccccc,\n" 5735 " Cccccccccccccc cccccccccc);"); 5736 verifyFormat("Aaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n" 5737 " Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n" 5738 " Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n" 5739 " Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n" 5740 " Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc);"); 5741 5742 // Break after multi-line parameters. 5743 verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 5744 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 5745 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 5746 " bbbb bbbb);"); 5747 verifyFormat("void SomeLoooooooooooongFunction(\n" 5748 " std::unique_ptr<aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>\n" 5749 " aaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 5750 " int bbbbbbbbbbbbb);"); 5751 5752 // Treat overloaded operators like other functions. 5753 verifyFormat("SomeLoooooooooooooooooooooooooogType\n" 5754 "operator>(const SomeLoooooooooooooooooooooooooogType &other);"); 5755 verifyFormat("SomeLoooooooooooooooooooooooooogType\n" 5756 "operator>>(const SomeLooooooooooooooooooooooooogType &other);"); 5757 verifyFormat("SomeLoooooooooooooooooooooooooogType\n" 5758 "operator<<(const SomeLooooooooooooooooooooooooogType &other);"); 5759 verifyGoogleFormat( 5760 "SomeLoooooooooooooooooooooooooooooogType operator>>(\n" 5761 " const SomeLooooooooogType &a, const SomeLooooooooogType &b);"); 5762 verifyGoogleFormat( 5763 "SomeLoooooooooooooooooooooooooooooogType operator<<(\n" 5764 " const SomeLooooooooogType &a, const SomeLooooooooogType &b);"); 5765 verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 5766 " int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa = 1);"); 5767 verifyFormat("aaaaaaaaaaaaaaaaaaaaaa\n" 5768 "aaaaaaaaaaaaaaaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaa = 1);"); 5769 verifyGoogleFormat( 5770 "typename aaaaaaaaaa<aaaaaa>::aaaaaaaaaaa\n" 5771 "aaaaaaaaaa<aaaaaa>::aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 5772 " bool *aaaaaaaaaaaaaaaaaa, bool *aa) {}"); 5773 verifyGoogleFormat("template <typename T>\n" 5774 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 5775 "aaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaaaaaaaa(\n" 5776 " aaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaa);"); 5777 5778 FormatStyle Style = getLLVMStyle(); 5779 Style.PointerAlignment = FormatStyle::PAS_Left; 5780 verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 5781 " aaaaaaaaaaaaaaaaaaaaaaaaa* const aaaaaaaaaaaa) {}", 5782 Style); 5783 verifyFormat("void aaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa*\n" 5784 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}", 5785 Style); 5786 } 5787 5788 TEST_F(FormatTest, DontBreakBeforeQualifiedOperator) { 5789 // Regression test for https://bugs.llvm.org/show_bug.cgi?id=40516: 5790 // Prefer keeping `::` followed by `operator` together. 5791 EXPECT_EQ("const aaaa::bbbbbbb &\n" 5792 "ccccccccc::operator++() {\n" 5793 " stuff();\n" 5794 "}", 5795 format("const aaaa::bbbbbbb\n" 5796 "&ccccccccc::operator++() { stuff(); }", 5797 getLLVMStyleWithColumns(40))); 5798 } 5799 5800 TEST_F(FormatTest, TrailingReturnType) { 5801 verifyFormat("auto foo() -> int;\n"); 5802 // correct trailing return type spacing 5803 verifyFormat("auto operator->() -> int;\n"); 5804 verifyFormat("auto operator++(int) -> int;\n"); 5805 5806 verifyFormat("struct S {\n" 5807 " auto bar() const -> int;\n" 5808 "};"); 5809 verifyFormat("template <size_t Order, typename T>\n" 5810 "auto load_img(const std::string &filename)\n" 5811 " -> alias::tensor<Order, T, mem::tag::cpu> {}"); 5812 verifyFormat("auto SomeFunction(A aaaaaaaaaaaaaaaaaaaaa) const\n" 5813 " -> decltype(f(aaaaaaaaaaaaaaaaaaaaa)) {}"); 5814 verifyFormat("auto doSomething(Aaaaaa *aaaaaa) -> decltype(aaaaaa->f()) {}"); 5815 verifyFormat("template <typename T>\n" 5816 "auto aaaaaaaaaaaaaaaaaaaaaa(T t)\n" 5817 " -> decltype(eaaaaaaaaaaaaaaa<T>(t.a).aaaaaaaa());"); 5818 5819 // Not trailing return types. 5820 verifyFormat("void f() { auto a = b->c(); }"); 5821 } 5822 5823 TEST_F(FormatTest, DeductionGuides) { 5824 verifyFormat("template <class T> A(const T &, const T &) -> A<T &>;"); 5825 verifyFormat("template <class T> explicit A(T &, T &&) -> A<T>;"); 5826 verifyFormat("template <class... Ts> S(Ts...) -> S<Ts...>;"); 5827 verifyFormat( 5828 "template <class... T>\n" 5829 "array(T &&...t) -> array<std::common_type_t<T...>, sizeof...(T)>;"); 5830 verifyFormat("template <class T> A() -> A<decltype(p->foo<3>())>;"); 5831 verifyFormat("template <class T> A() -> A<decltype(foo<traits<1>>)>;"); 5832 verifyFormat("template <class T> A() -> A<sizeof(p->foo<1>)>;"); 5833 verifyFormat("template <class T> A() -> A<(3 < 2)>;"); 5834 verifyFormat("template <class T> A() -> A<((3) < (2))>;"); 5835 verifyFormat("template <class T> x() -> x<1>;"); 5836 verifyFormat("template <class T> explicit x(T &) -> x<1>;"); 5837 5838 // Ensure not deduction guides. 5839 verifyFormat("c()->f<int>();"); 5840 verifyFormat("x()->foo<1>;"); 5841 verifyFormat("x = p->foo<3>();"); 5842 verifyFormat("x()->x<1>();"); 5843 verifyFormat("x()->x<1>;"); 5844 } 5845 5846 TEST_F(FormatTest, BreaksFunctionDeclarationsWithTrailingTokens) { 5847 // Avoid breaking before trailing 'const' or other trailing annotations, if 5848 // they are not function-like. 5849 FormatStyle Style = getGoogleStyle(); 5850 Style.ColumnLimit = 47; 5851 verifyFormat("void someLongFunction(\n" 5852 " int someLoooooooooooooongParameter) const {\n}", 5853 getLLVMStyleWithColumns(47)); 5854 verifyFormat("LoooooongReturnType\n" 5855 "someLoooooooongFunction() const {}", 5856 getLLVMStyleWithColumns(47)); 5857 verifyFormat("LoooooongReturnType someLoooooooongFunction()\n" 5858 " const {}", 5859 Style); 5860 verifyFormat("void SomeFunction(aaaaa aaaaaaaaaaaaaaaaaaaa,\n" 5861 " aaaaa aaaaaaaaaaaaaaaaaaaa) OVERRIDE;"); 5862 verifyFormat("void SomeFunction(aaaaa aaaaaaaaaaaaaaaaaaaa,\n" 5863 " aaaaa aaaaaaaaaaaaaaaaaaaa) OVERRIDE FINAL;"); 5864 verifyFormat("void SomeFunction(aaaaa aaaaaaaaaaaaaaaaaaaa,\n" 5865 " aaaaa aaaaaaaaaaaaaaaaaaaa) override final;"); 5866 verifyFormat("virtual void aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaa aaaa,\n" 5867 " aaaaaaaaaaa aaaaa) const override;"); 5868 verifyGoogleFormat( 5869 "virtual void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 5870 " const override;"); 5871 5872 // Even if the first parameter has to be wrapped. 5873 verifyFormat("void someLongFunction(\n" 5874 " int someLongParameter) const {}", 5875 getLLVMStyleWithColumns(46)); 5876 verifyFormat("void someLongFunction(\n" 5877 " int someLongParameter) const {}", 5878 Style); 5879 verifyFormat("void someLongFunction(\n" 5880 " int someLongParameter) override {}", 5881 Style); 5882 verifyFormat("void someLongFunction(\n" 5883 " int someLongParameter) OVERRIDE {}", 5884 Style); 5885 verifyFormat("void someLongFunction(\n" 5886 " int someLongParameter) final {}", 5887 Style); 5888 verifyFormat("void someLongFunction(\n" 5889 " int someLongParameter) FINAL {}", 5890 Style); 5891 verifyFormat("void someLongFunction(\n" 5892 " int parameter) const override {}", 5893 Style); 5894 5895 Style.BreakBeforeBraces = FormatStyle::BS_Allman; 5896 verifyFormat("void someLongFunction(\n" 5897 " int someLongParameter) const\n" 5898 "{\n" 5899 "}", 5900 Style); 5901 5902 Style.BreakBeforeBraces = FormatStyle::BS_Whitesmiths; 5903 verifyFormat("void someLongFunction(\n" 5904 " int someLongParameter) const\n" 5905 " {\n" 5906 " }", 5907 Style); 5908 5909 // Unless these are unknown annotations. 5910 verifyFormat("void SomeFunction(aaaaaaaaaa aaaaaaaaaaaaaaa,\n" 5911 " aaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 5912 " LONG_AND_UGLY_ANNOTATION;"); 5913 5914 // Breaking before function-like trailing annotations is fine to keep them 5915 // close to their arguments. 5916 verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 5917 " LOCKS_EXCLUDED(aaaaaaaaaaaaa);"); 5918 verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) const\n" 5919 " LOCKS_EXCLUDED(aaaaaaaaaaaaa);"); 5920 verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) const\n" 5921 " LOCKS_EXCLUDED(aaaaaaaaaaaaa) {}"); 5922 verifyGoogleFormat("void aaaaaaaaaaaaaa(aaaaaaaa aaa) override\n" 5923 " AAAAAAAAAAAAAAAAAAAAAAAA(aaaaaaaaaaaaaaa);"); 5924 verifyFormat("SomeFunction([](int i) LOCKS_EXCLUDED(a) {});"); 5925 5926 verifyFormat( 5927 "void aaaaaaaaaaaaaaaaaa()\n" 5928 " __attribute__((aaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaa,\n" 5929 " aaaaaaaaaaaaaaaaaaaaaaaaa));"); 5930 verifyFormat("bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 5931 " __attribute__((unused));"); 5932 verifyGoogleFormat( 5933 "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 5934 " GUARDED_BY(aaaaaaaaaaaa);"); 5935 verifyGoogleFormat( 5936 "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 5937 " GUARDED_BY(aaaaaaaaaaaa);"); 5938 verifyGoogleFormat( 5939 "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa GUARDED_BY(aaaaaaaaaaaa) =\n" 5940 " aaaaaaaa::aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 5941 verifyGoogleFormat( 5942 "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa GUARDED_BY(aaaaaaaaaaaa) =\n" 5943 " aaaaaaaaaaaaaaaaaaaaaaaaa;"); 5944 } 5945 5946 TEST_F(FormatTest, FunctionAnnotations) { 5947 verifyFormat("DEPRECATED(\"Use NewClass::NewFunction instead.\")\n" 5948 "int OldFunction(const string ¶meter) {}"); 5949 verifyFormat("DEPRECATED(\"Use NewClass::NewFunction instead.\")\n" 5950 "string OldFunction(const string ¶meter) {}"); 5951 verifyFormat("template <typename T>\n" 5952 "DEPRECATED(\"Use NewClass::NewFunction instead.\")\n" 5953 "string OldFunction(const string ¶meter) {}"); 5954 5955 // Not function annotations. 5956 verifyFormat("ASSERT(\"aaaaa\") << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 5957 " << bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"); 5958 verifyFormat("TEST_F(ThisIsATestFixtureeeeeeeeeeeee,\n" 5959 " ThisIsATestWithAReallyReallyReallyReallyLongName) {}"); 5960 verifyFormat("MACRO(abc).function() // wrap\n" 5961 " << abc;"); 5962 verifyFormat("MACRO(abc)->function() // wrap\n" 5963 " << abc;"); 5964 verifyFormat("MACRO(abc)::function() // wrap\n" 5965 " << abc;"); 5966 } 5967 5968 TEST_F(FormatTest, BreaksDesireably) { 5969 verifyFormat("if (aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa) ||\n" 5970 " aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa) ||\n" 5971 " aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa)) {\n}"); 5972 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 5973 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n" 5974 "}"); 5975 5976 verifyFormat( 5977 "aaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 5978 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}"); 5979 5980 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 5981 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 5982 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa));"); 5983 5984 verifyFormat( 5985 "aaaaaaaa(aaaaaaaaaaaaa,\n" 5986 " aaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 5987 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)),\n" 5988 " aaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 5989 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)));"); 5990 5991 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n" 5992 " (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 5993 5994 verifyFormat( 5995 "void f() {\n" 5996 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa &&\n" 5997 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n" 5998 "}"); 5999 verifyFormat( 6000 "aaaaaa(new Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6001 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaa));"); 6002 verifyFormat( 6003 "aaaaaa(aaa, new Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6004 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaa));"); 6005 verifyFormat( 6006 "aaaaaa(aaa,\n" 6007 " new Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6008 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 6009 " aaaa);"); 6010 verifyFormat("aaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 6011 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 6012 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 6013 6014 // Indent consistently independent of call expression and unary operator. 6015 verifyFormat("aaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n" 6016 " dddddddddddddddddddddddddddddd));"); 6017 verifyFormat("aaaaaaaaaaa(!bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n" 6018 " dddddddddddddddddddddddddddddd));"); 6019 verifyFormat("aaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbb.ccccccccccccccccc(\n" 6020 " dddddddddddddddddddddddddddddd));"); 6021 6022 // This test case breaks on an incorrect memoization, i.e. an optimization not 6023 // taking into account the StopAt value. 6024 verifyFormat( 6025 "return aaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaa ||\n" 6026 " aaaaaaaaaaa(aaaaaaaaa) || aaaaaaaaaaaaaaaaaaaaaaa ||\n" 6027 " aaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaa ||\n" 6028 " (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 6029 6030 verifyFormat("{\n {\n {\n" 6031 " Annotation.SpaceRequiredBefore =\n" 6032 " Line.Tokens[i - 1].Tok.isNot(tok::l_paren) &&\n" 6033 " Line.Tokens[i - 1].Tok.isNot(tok::l_square);\n" 6034 " }\n }\n}"); 6035 6036 // Break on an outer level if there was a break on an inner level. 6037 EXPECT_EQ("f(g(h(a, // comment\n" 6038 " b, c),\n" 6039 " d, e),\n" 6040 " x, y);", 6041 format("f(g(h(a, // comment\n" 6042 " b, c), d, e), x, y);")); 6043 6044 // Prefer breaking similar line breaks. 6045 verifyFormat( 6046 "const int kTrackingOptions = NSTrackingMouseMoved |\n" 6047 " NSTrackingMouseEnteredAndExited |\n" 6048 " NSTrackingActiveAlways;"); 6049 } 6050 6051 TEST_F(FormatTest, FormatsDeclarationsOnePerLine) { 6052 FormatStyle NoBinPacking = getGoogleStyle(); 6053 NoBinPacking.BinPackParameters = false; 6054 NoBinPacking.BinPackArguments = true; 6055 verifyFormat("void f() {\n" 6056 " f(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaa,\n" 6057 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n" 6058 "}", 6059 NoBinPacking); 6060 verifyFormat("void f(int aaaaaaaaaaaaaaaaaaaa,\n" 6061 " int aaaaaaaaaaaaaaaaaaaa,\n" 6062 " int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}", 6063 NoBinPacking); 6064 6065 NoBinPacking.AllowAllParametersOfDeclarationOnNextLine = false; 6066 verifyFormat("void aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 6067 " vector<int> bbbbbbbbbbbbbbb);", 6068 NoBinPacking); 6069 // FIXME: This behavior difference is probably not wanted. However, currently 6070 // we cannot distinguish BreakBeforeParameter being set because of the wrapped 6071 // template arguments from BreakBeforeParameter being set because of the 6072 // one-per-line formatting. 6073 verifyFormat( 6074 "void fffffffffff(aaaaaaaaaaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaa,\n" 6075 " aaaaaaaaaa> aaaaaaaaaa);", 6076 NoBinPacking); 6077 verifyFormat( 6078 "void fffffffffff(\n" 6079 " aaaaaaaaaaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaa>\n" 6080 " aaaaaaaaaa);"); 6081 } 6082 6083 TEST_F(FormatTest, FormatsOneParameterPerLineIfNecessary) { 6084 FormatStyle NoBinPacking = getGoogleStyle(); 6085 NoBinPacking.BinPackParameters = false; 6086 NoBinPacking.BinPackArguments = false; 6087 verifyFormat("f(aaaaaaaaaaaaaaaaaaaa,\n" 6088 " aaaaaaaaaaaaaaaaaaaa,\n" 6089 " aaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaa);", 6090 NoBinPacking); 6091 verifyFormat("aaaaaaa(aaaaaaaaaaaaa,\n" 6092 " aaaaaaaaaaaaa,\n" 6093 " aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa));", 6094 NoBinPacking); 6095 verifyFormat( 6096 "aaaaaaaa(aaaaaaaaaaaaa,\n" 6097 " aaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6098 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)),\n" 6099 " aaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6100 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)));", 6101 NoBinPacking); 6102 verifyFormat("aaaaaaaaaaaaaaa(aaaaaaaaa, aaaaaaaaa, aaaaaaaaaaaaaaaaaaaaa)\n" 6103 " .aaaaaaaaaaaaaaaaaa();", 6104 NoBinPacking); 6105 verifyFormat("void f() {\n" 6106 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6107 " aaaaaaaaaa, aaaaaaaaaa, aaaaaaaaaa, aaaaaaaaaaa);\n" 6108 "}", 6109 NoBinPacking); 6110 6111 verifyFormat( 6112 "aaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa,\n" 6113 " aaaaaaaaaaaa,\n" 6114 " aaaaaaaaaaaa);", 6115 NoBinPacking); 6116 verifyFormat( 6117 "somefunction(someotherFunction(ddddddddddddddddddddddddddddddddddd,\n" 6118 " ddddddddddddddddddddddddddddd),\n" 6119 " test);", 6120 NoBinPacking); 6121 6122 verifyFormat("std::vector<aaaaaaaaaaaaaaaaaaaaaaa,\n" 6123 " aaaaaaaaaaaaaaaaaaaaaaa,\n" 6124 " aaaaaaaaaaaaaaaaaaaaaaa>\n" 6125 " aaaaaaaaaaaaaaaaaa;", 6126 NoBinPacking); 6127 verifyFormat("a(\"a\"\n" 6128 " \"a\",\n" 6129 " a);"); 6130 6131 NoBinPacking.AllowAllParametersOfDeclarationOnNextLine = false; 6132 verifyFormat("void aaaaaaaaaa(aaaaaaaaa,\n" 6133 " aaaaaaaaa,\n" 6134 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 6135 NoBinPacking); 6136 verifyFormat( 6137 "void f() {\n" 6138 " aaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaa, aaaaaaaaa, aaaaaaaaaaaaaaaaaaaaa)\n" 6139 " .aaaaaaa();\n" 6140 "}", 6141 NoBinPacking); 6142 verifyFormat( 6143 "template <class SomeType, class SomeOtherType>\n" 6144 "SomeType SomeFunction(SomeType Type, SomeOtherType OtherType) {}", 6145 NoBinPacking); 6146 } 6147 6148 TEST_F(FormatTest, AdaptiveOnePerLineFormatting) { 6149 FormatStyle Style = getLLVMStyleWithColumns(15); 6150 Style.ExperimentalAutoDetectBinPacking = true; 6151 EXPECT_EQ("aaa(aaaa,\n" 6152 " aaaa,\n" 6153 " aaaa);\n" 6154 "aaa(aaaa,\n" 6155 " aaaa,\n" 6156 " aaaa);", 6157 format("aaa(aaaa,\n" // one-per-line 6158 " aaaa,\n" 6159 " aaaa );\n" 6160 "aaa(aaaa, aaaa, aaaa);", // inconclusive 6161 Style)); 6162 EXPECT_EQ("aaa(aaaa, aaaa,\n" 6163 " aaaa);\n" 6164 "aaa(aaaa, aaaa,\n" 6165 " aaaa);", 6166 format("aaa(aaaa, aaaa,\n" // bin-packed 6167 " aaaa );\n" 6168 "aaa(aaaa, aaaa, aaaa);", // inconclusive 6169 Style)); 6170 } 6171 6172 TEST_F(FormatTest, FormatsBuilderPattern) { 6173 verifyFormat("return llvm::StringSwitch<Reference::Kind>(name)\n" 6174 " .StartsWith(\".eh_frame_hdr\", ORDER_EH_FRAMEHDR)\n" 6175 " .StartsWith(\".eh_frame\", ORDER_EH_FRAME)\n" 6176 " .StartsWith(\".init\", ORDER_INIT)\n" 6177 " .StartsWith(\".fini\", ORDER_FINI)\n" 6178 " .StartsWith(\".hash\", ORDER_HASH)\n" 6179 " .Default(ORDER_TEXT);\n"); 6180 6181 verifyFormat("return aaaaaaaaaaaaaaaaa->aaaaa().aaaaaaaaaaaaa().aaaaaa() <\n" 6182 " aaaaaaaaaaaaaaa->aaaaa().aaaaaaaaaaaaa().aaaaaa();"); 6183 verifyFormat("aaaaaaa->aaaaaaa\n" 6184 " ->aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6185 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 6186 " ->aaaaaaaa(aaaaaaaaaaaaaaa);"); 6187 verifyFormat( 6188 "aaaaaaa->aaaaaaa\n" 6189 " ->aaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 6190 " ->aaaaaaaa(aaaaaaaaaaaaaaa);"); 6191 verifyFormat( 6192 "aaaaaaaaaaaaaaaaaaa()->aaaaaa(bbbbb)->aaaaaaaaaaaaaaaaaaa( // break\n" 6193 " aaaaaaaaaaaaaa);"); 6194 verifyFormat( 6195 "aaaaaaaaaaaaaaaaaaaaaaa *aaaaaaaaa =\n" 6196 " aaaaaa->aaaaaaaaaaaa()\n" 6197 " ->aaaaaaaaaaaaaaaa(\n" 6198 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 6199 " ->aaaaaaaaaaaaaaaaa();"); 6200 verifyGoogleFormat( 6201 "void f() {\n" 6202 " someo->Add((new util::filetools::Handler(dir))\n" 6203 " ->OnEvent1(NewPermanentCallback(\n" 6204 " this, &HandlerHolderClass::EventHandlerCBA))\n" 6205 " ->OnEvent2(NewPermanentCallback(\n" 6206 " this, &HandlerHolderClass::EventHandlerCBB))\n" 6207 " ->OnEvent3(NewPermanentCallback(\n" 6208 " this, &HandlerHolderClass::EventHandlerCBC))\n" 6209 " ->OnEvent5(NewPermanentCallback(\n" 6210 " this, &HandlerHolderClass::EventHandlerCBD))\n" 6211 " ->OnEvent6(NewPermanentCallback(\n" 6212 " this, &HandlerHolderClass::EventHandlerCBE)));\n" 6213 "}"); 6214 6215 verifyFormat( 6216 "aaaaaaaaaaa().aaaaaaaaaaa().aaaaaaaaaaa().aaaaaaaaaaa().aaaaaaaaaaa();"); 6217 verifyFormat("aaaaaaaaaaaaaaa()\n" 6218 " .aaaaaaaaaaaaaaa()\n" 6219 " .aaaaaaaaaaaaaaa()\n" 6220 " .aaaaaaaaaaaaaaa()\n" 6221 " .aaaaaaaaaaaaaaa();"); 6222 verifyFormat("aaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa()\n" 6223 " .aaaaaaaaaaaaaaa()\n" 6224 " .aaaaaaaaaaaaaaa()\n" 6225 " .aaaaaaaaaaaaaaa();"); 6226 verifyFormat("aaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa()\n" 6227 " .aaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa()\n" 6228 " .aaaaaaaaaaaaaaa();"); 6229 verifyFormat("aaaaaaaaaaaaa->aaaaaaaaaaaaaaaaaaaaaaaa()\n" 6230 " ->aaaaaaaaaaaaaae(0)\n" 6231 " ->aaaaaaaaaaaaaaa();"); 6232 6233 // Don't linewrap after very short segments. 6234 verifyFormat("a().aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 6235 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 6236 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 6237 verifyFormat("aa().aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 6238 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 6239 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 6240 verifyFormat("aaa()\n" 6241 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 6242 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 6243 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 6244 6245 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaa()\n" 6246 " .aaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 6247 " .has<bbbbbbbbbbbbbbbbbbbbb>();"); 6248 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaa()\n" 6249 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<\n" 6250 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>();"); 6251 6252 // Prefer not to break after empty parentheses. 6253 verifyFormat("FirstToken->WhitespaceRange.getBegin().getLocWithOffset(\n" 6254 " First->LastNewlineOffset);"); 6255 6256 // Prefer not to create "hanging" indents. 6257 verifyFormat( 6258 "return !soooooooooooooome_map\n" 6259 " .insert(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 6260 " .second;"); 6261 verifyFormat( 6262 "return aaaaaaaaaaaaaaaa\n" 6263 " .aaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa)\n" 6264 " .aaaa(aaaaaaaaaaaaaa);"); 6265 // No hanging indent here. 6266 verifyFormat("aaaaaaaaaaaaaaaa.aaaaaaaaaaaaaa.aaaaaaaaaaaaaaa(\n" 6267 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 6268 verifyFormat("aaaaaaaaaaaaaaaa.aaaaaaaaaaaaaa().aaaaaaaaaaaaaaa(\n" 6269 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 6270 verifyFormat("aaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa)\n" 6271 " .aaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 6272 getLLVMStyleWithColumns(60)); 6273 verifyFormat("aaaaaaaaaaaaaaaaaa\n" 6274 " .aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa)\n" 6275 " .aaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 6276 getLLVMStyleWithColumns(59)); 6277 verifyFormat("aaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6278 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 6279 " .aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 6280 6281 // Dont break if only closing statements before member call 6282 verifyFormat("test() {\n" 6283 " ([]() -> {\n" 6284 " int b = 32;\n" 6285 " return 3;\n" 6286 " }).foo();\n" 6287 "}"); 6288 verifyFormat("test() {\n" 6289 " (\n" 6290 " []() -> {\n" 6291 " int b = 32;\n" 6292 " return 3;\n" 6293 " },\n" 6294 " foo, bar)\n" 6295 " .foo();\n" 6296 "}"); 6297 verifyFormat("test() {\n" 6298 " ([]() -> {\n" 6299 " int b = 32;\n" 6300 " return 3;\n" 6301 " })\n" 6302 " .foo()\n" 6303 " .bar();\n" 6304 "}"); 6305 verifyFormat("test() {\n" 6306 " ([]() -> {\n" 6307 " int b = 32;\n" 6308 " return 3;\n" 6309 " })\n" 6310 " .foo(\"aaaaaaaaaaaaaaaaa\"\n" 6311 " \"bbbb\");\n" 6312 "}", 6313 getLLVMStyleWithColumns(30)); 6314 } 6315 6316 TEST_F(FormatTest, BreaksAccordingToOperatorPrecedence) { 6317 verifyFormat( 6318 "if (aaaaaaaaaaaaaaaaaaaaaaaaa ||\n" 6319 " bbbbbbbbbbbbbbbbbbbbbbbbb && ccccccccccccccccccccccccc) {\n}"); 6320 verifyFormat( 6321 "if (aaaaaaaaaaaaaaaaaaaaaaaaa or\n" 6322 " bbbbbbbbbbbbbbbbbbbbbbbbb and cccccccccccccccccccccccc) {\n}"); 6323 6324 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa && bbbbbbbbbbbbbbbbbbbbbbbbb ||\n" 6325 " ccccccccccccccccccccccccc) {\n}"); 6326 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa and bbbbbbbbbbbbbbbbbbbbbbbb or\n" 6327 " ccccccccccccccccccccccccc) {\n}"); 6328 6329 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa || bbbbbbbbbbbbbbbbbbbbbbbbb ||\n" 6330 " ccccccccccccccccccccccccc) {\n}"); 6331 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa or bbbbbbbbbbbbbbbbbbbbbbbbb or\n" 6332 " ccccccccccccccccccccccccc) {\n}"); 6333 6334 verifyFormat( 6335 "if ((aaaaaaaaaaaaaaaaaaaaaaaaa || bbbbbbbbbbbbbbbbbbbbbbbbb) &&\n" 6336 " ccccccccccccccccccccccccc) {\n}"); 6337 verifyFormat( 6338 "if ((aaaaaaaaaaaaaaaaaaaaaaaaa or bbbbbbbbbbbbbbbbbbbbbbbbb) and\n" 6339 " ccccccccccccccccccccccccc) {\n}"); 6340 6341 verifyFormat("return aaaa & AAAAAAAAAAAAAAAAAAAAAAAAAAAAA ||\n" 6342 " bbbb & BBBBBBBBBBBBBBBBBBBBBBBBBBBBB ||\n" 6343 " cccc & CCCCCCCCCCCCCCCCCCCCCCCCCC ||\n" 6344 " dddd & DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD;"); 6345 verifyFormat("return aaaa & AAAAAAAAAAAAAAAAAAAAAAAAAAAAA or\n" 6346 " bbbb & BBBBBBBBBBBBBBBBBBBBBBBBBBBBB or\n" 6347 " cccc & CCCCCCCCCCCCCCCCCCCCCCCCCC or\n" 6348 " dddd & DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD;"); 6349 6350 verifyFormat("if ((aaaaaaaaaa != aaaaaaaaaaaaaaa ||\n" 6351 " aaaaaaaaaaaaaaaaaaaaaaaa() >= aaaaaaaaaaaaaaaaaaaa) &&\n" 6352 " aaaaaaaaaaaaaaa != aa) {\n}"); 6353 verifyFormat("if ((aaaaaaaaaa != aaaaaaaaaaaaaaa or\n" 6354 " aaaaaaaaaaaaaaaaaaaaaaaa() >= aaaaaaaaaaaaaaaaaaaa) and\n" 6355 " aaaaaaaaaaaaaaa != aa) {\n}"); 6356 } 6357 6358 TEST_F(FormatTest, BreaksAfterAssignments) { 6359 verifyFormat( 6360 "unsigned Cost =\n" 6361 " TTI.getMemoryOpCost(I->getOpcode(), VectorTy, SI->getAlignment(),\n" 6362 " SI->getPointerAddressSpaceee());\n"); 6363 verifyFormat( 6364 "CharSourceRange LineRange = CharSourceRange::getTokenRange(\n" 6365 " Line.Tokens.front().Tok.getLo(), Line.Tokens.back().Tok.getLoc());"); 6366 6367 verifyFormat( 6368 "aaaaaaaaaaaaaaaaaaaaaaaaaa aaaa = aaaaaaaaaaaaaa(0).aaaa().aaaaaaaaa(\n" 6369 " aaaaaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaaaaaaa);"); 6370 verifyFormat("unsigned OriginalStartColumn =\n" 6371 " SourceMgr.getSpellingColumnNumber(\n" 6372 " Current.FormatTok.getStartOfNonWhitespace()) -\n" 6373 " 1;"); 6374 } 6375 6376 TEST_F(FormatTest, ConfigurableBreakAssignmentPenalty) { 6377 FormatStyle Style = getLLVMStyle(); 6378 verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaa =\n" 6379 " bbbbbbbbbbbbbbbbbbbbbbbbbb + cccccccccccccccccccccccccc;", 6380 Style); 6381 6382 Style.PenaltyBreakAssignment = 20; 6383 verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaa = bbbbbbbbbbbbbbbbbbbbbbbbbb +\n" 6384 " cccccccccccccccccccccccccc;", 6385 Style); 6386 } 6387 6388 TEST_F(FormatTest, AlignsAfterAssignments) { 6389 verifyFormat( 6390 "int Result = aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n" 6391 " aaaaaaaaaaaaaaaaaaaaaaaaa;"); 6392 verifyFormat( 6393 "Result += aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n" 6394 " aaaaaaaaaaaaaaaaaaaaaaaaa;"); 6395 verifyFormat( 6396 "Result >>= aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n" 6397 " aaaaaaaaaaaaaaaaaaaaaaaaa;"); 6398 verifyFormat( 6399 "int Result = (aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n" 6400 " aaaaaaaaaaaaaaaaaaaaaaaaa);"); 6401 verifyFormat( 6402 "double LooooooooooooooooooooooooongResult = aaaaaaaaaaaaaaaaaaaaaaaa +\n" 6403 " aaaaaaaaaaaaaaaaaaaaaaaa +\n" 6404 " aaaaaaaaaaaaaaaaaaaaaaaa;"); 6405 } 6406 6407 TEST_F(FormatTest, AlignsAfterReturn) { 6408 verifyFormat( 6409 "return aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n" 6410 " aaaaaaaaaaaaaaaaaaaaaaaaa;"); 6411 verifyFormat( 6412 "return (aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n" 6413 " aaaaaaaaaaaaaaaaaaaaaaaaa);"); 6414 verifyFormat( 6415 "return aaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >=\n" 6416 " aaaaaaaaaaaaaaaaaaaaaa();"); 6417 verifyFormat( 6418 "return (aaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >=\n" 6419 " aaaaaaaaaaaaaaaaaaaaaa());"); 6420 verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6421 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 6422 verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6423 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) &&\n" 6424 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 6425 verifyFormat("return\n" 6426 " // true if code is one of a or b.\n" 6427 " code == a || code == b;"); 6428 } 6429 6430 TEST_F(FormatTest, AlignsAfterOpenBracket) { 6431 verifyFormat( 6432 "void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaa aaaaaaaa,\n" 6433 " aaaaaaaaa aaaaaaa) {}"); 6434 verifyFormat( 6435 "SomeLongVariableName->someVeryLongFunctionName(aaaaaaaaaaa aaaaaaaaa,\n" 6436 " aaaaaaaaaaa aaaaaaaaa);"); 6437 verifyFormat( 6438 "SomeLongVariableName->someFunction(foooooooo(aaaaaaaaaaaaaaa,\n" 6439 " aaaaaaaaaaaaaaaaaaaaa));"); 6440 FormatStyle Style = getLLVMStyle(); 6441 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 6442 verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6443 " aaaaaaaaaaa aaaaaaaa, aaaaaaaaa aaaaaaa) {}", 6444 Style); 6445 verifyFormat("SomeLongVariableName->someVeryLongFunctionName(\n" 6446 " aaaaaaaaaaa aaaaaaaaa, aaaaaaaaaaa aaaaaaaaa);", 6447 Style); 6448 verifyFormat("SomeLongVariableName->someFunction(\n" 6449 " foooooooo(aaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaa));", 6450 Style); 6451 verifyFormat( 6452 "void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaa aaaaaaaa,\n" 6453 " aaaaaaaaa aaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}", 6454 Style); 6455 verifyFormat( 6456 "SomeLongVariableName->someVeryLongFunctionName(aaaaaaaaaaa aaaaaaaaa,\n" 6457 " aaaaaaaaaaa aaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 6458 Style); 6459 verifyFormat( 6460 "SomeLongVariableName->someFunction(foooooooo(aaaaaaaaaaaaaaa,\n" 6461 " aaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa));", 6462 Style); 6463 6464 verifyFormat("bbbbbbbbbbbb(aaaaaaaaaaaaaaaaaaaaaaaa, //\n" 6465 " ccccccc(aaaaaaaaaaaaaaaaa, //\n" 6466 " b));", 6467 Style); 6468 6469 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 6470 Style.BinPackArguments = false; 6471 Style.BinPackParameters = false; 6472 verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6473 " aaaaaaaaaaa aaaaaaaa,\n" 6474 " aaaaaaaaa aaaaaaa,\n" 6475 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}", 6476 Style); 6477 verifyFormat("SomeLongVariableName->someVeryLongFunctionName(\n" 6478 " aaaaaaaaaaa aaaaaaaaa,\n" 6479 " aaaaaaaaaaa aaaaaaaaa,\n" 6480 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 6481 Style); 6482 verifyFormat("SomeLongVariableName->someFunction(foooooooo(\n" 6483 " aaaaaaaaaaaaaaa,\n" 6484 " aaaaaaaaaaaaaaaaaaaaa,\n" 6485 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa));", 6486 Style); 6487 verifyFormat( 6488 "aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa(\n" 6489 " aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)));", 6490 Style); 6491 verifyFormat( 6492 "aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaa.aaaaaaaaaa(\n" 6493 " aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)));", 6494 Style); 6495 verifyFormat( 6496 "aaaaaaaaaaaaaaaaaaaaaaaa(\n" 6497 " aaaaaaaaaaaaaaaaaaaaa(\n" 6498 " aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)),\n" 6499 " aaaaaaaaaaaaaaaa);", 6500 Style); 6501 verifyFormat( 6502 "aaaaaaaaaaaaaaaaaaaaaaaa(\n" 6503 " aaaaaaaaaaaaaaaaaaaaa(\n" 6504 " aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)) &&\n" 6505 " aaaaaaaaaaaaaaaa);", 6506 Style); 6507 } 6508 6509 TEST_F(FormatTest, ParenthesesAndOperandAlignment) { 6510 FormatStyle Style = getLLVMStyleWithColumns(40); 6511 verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n" 6512 " bbbbbbbbbbbbbbbbbbbbbb);", 6513 Style); 6514 Style.AlignAfterOpenBracket = FormatStyle::BAS_Align; 6515 Style.AlignOperands = FormatStyle::OAS_DontAlign; 6516 verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n" 6517 " bbbbbbbbbbbbbbbbbbbbbb);", 6518 Style); 6519 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 6520 Style.AlignOperands = FormatStyle::OAS_Align; 6521 verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n" 6522 " bbbbbbbbbbbbbbbbbbbbbb);", 6523 Style); 6524 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 6525 Style.AlignOperands = FormatStyle::OAS_DontAlign; 6526 verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n" 6527 " bbbbbbbbbbbbbbbbbbbbbb);", 6528 Style); 6529 } 6530 6531 TEST_F(FormatTest, BreaksConditionalExpressions) { 6532 verifyFormat( 6533 "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6534 " ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6535 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 6536 verifyFormat( 6537 "aaaa(aaaaaaaaaa, aaaaaaaa,\n" 6538 " aaaaaaaaaaaaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6539 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 6540 verifyFormat( 6541 "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6542 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 6543 verifyFormat("aaaa(aaaaaaaaa, aaaaaaaaa,\n" 6544 " aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6545 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 6546 verifyFormat( 6547 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa ? aaaa(aaaaaa)\n" 6548 " : aaaaaaaaaaaaa);"); 6549 verifyFormat( 6550 "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n" 6551 " aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6552 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 6553 " aaaaaaaaaaaaa);"); 6554 verifyFormat( 6555 "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n" 6556 " aaaaaaaaaaaaaaaa ?: aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 6557 " aaaaaaaaaaaaa);"); 6558 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6559 " ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6560 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 6561 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6562 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 6563 verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 6564 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6565 " ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6566 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 6567 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6568 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 6569 " aaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 6570 verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 6571 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6572 " ?: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6573 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 6574 " aaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 6575 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6576 " ? aaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6577 " : aaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 6578 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaa =\n" 6579 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6580 " ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6581 " : aaaaaaaaaaaaaaaa;"); 6582 verifyFormat( 6583 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6584 " ? aaaaaaaaaaaaaaa\n" 6585 " : aaaaaaaaaaaaaaa;"); 6586 verifyFormat("f(aaaaaaaaaaaaaaaa == // force break\n" 6587 " aaaaaaaaa\n" 6588 " ? b\n" 6589 " : c);"); 6590 verifyFormat("return aaaa == bbbb\n" 6591 " // comment\n" 6592 " ? aaaa\n" 6593 " : bbbb;"); 6594 verifyFormat("unsigned Indent =\n" 6595 " format(TheLine.First,\n" 6596 " IndentForLevel[TheLine.Level] >= 0\n" 6597 " ? IndentForLevel[TheLine.Level]\n" 6598 " : TheLine * 2,\n" 6599 " TheLine.InPPDirective, PreviousEndOfLineColumn);", 6600 getLLVMStyleWithColumns(60)); 6601 verifyFormat("bool aaaaaa = aaaaaaaaaaaaa //\n" 6602 " ? aaaaaaaaaaaaaaa\n" 6603 " : bbbbbbbbbbbbbbb //\n" 6604 " ? ccccccccccccccc\n" 6605 " : ddddddddddddddd;"); 6606 verifyFormat("bool aaaaaa = aaaaaaaaaaaaa //\n" 6607 " ? aaaaaaaaaaaaaaa\n" 6608 " : (bbbbbbbbbbbbbbb //\n" 6609 " ? ccccccccccccccc\n" 6610 " : ddddddddddddddd);"); 6611 verifyFormat( 6612 "int aaaaaaaaaaaaaaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6613 " ? aaaaaaaaaaaaaaaaaaaaaaaaa +\n" 6614 " aaaaaaaaaaaaaaaaaaaaa +\n" 6615 " aaaaaaaaaaaaaaaaaaaaa\n" 6616 " : aaaaaaaaaa;"); 6617 verifyFormat( 6618 "aaaaaa = aaaaaaaaaaaa ? aaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6619 " : aaaaaaaaaaaaaaaaaaaaaa\n" 6620 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 6621 6622 FormatStyle NoBinPacking = getLLVMStyle(); 6623 NoBinPacking.BinPackArguments = false; 6624 verifyFormat( 6625 "void f() {\n" 6626 " g(aaa,\n" 6627 " aaaaaaaaaa == aaaaaaaaaa ? aaaa : aaaaa,\n" 6628 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6629 " ? aaaaaaaaaaaaaaa\n" 6630 " : aaaaaaaaaaaaaaa);\n" 6631 "}", 6632 NoBinPacking); 6633 verifyFormat( 6634 "void f() {\n" 6635 " g(aaa,\n" 6636 " aaaaaaaaaa == aaaaaaaaaa ? aaaa : aaaaa,\n" 6637 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6638 " ?: aaaaaaaaaaaaaaa);\n" 6639 "}", 6640 NoBinPacking); 6641 6642 verifyFormat("SomeFunction(aaaaaaaaaaaaaaaaa,\n" 6643 " // comment.\n" 6644 " ccccccccccccccccccccccccccccccccccccccc\n" 6645 " ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6646 " : bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb);"); 6647 6648 // Assignments in conditional expressions. Apparently not uncommon :-(. 6649 verifyFormat("return a != b\n" 6650 " // comment\n" 6651 " ? a = b\n" 6652 " : a = b;"); 6653 verifyFormat("return a != b\n" 6654 " // comment\n" 6655 " ? a = a != b\n" 6656 " // comment\n" 6657 " ? a = b\n" 6658 " : a\n" 6659 " : a;\n"); 6660 verifyFormat("return a != b\n" 6661 " // comment\n" 6662 " ? a\n" 6663 " : a = a != b\n" 6664 " // comment\n" 6665 " ? a = b\n" 6666 " : a;"); 6667 6668 // Chained conditionals 6669 FormatStyle Style = getLLVMStyle(); 6670 Style.ColumnLimit = 70; 6671 Style.AlignOperands = FormatStyle::OAS_Align; 6672 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n" 6673 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 6674 " : 3333333333333333;", 6675 Style); 6676 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n" 6677 " : bbbbbbbbbb ? 2222222222222222\n" 6678 " : 3333333333333333;", 6679 Style); 6680 verifyFormat("return aaaaaaaaaa ? 1111111111111111\n" 6681 " : bbbbbbbbbbbbbbbb ? 2222222222222222\n" 6682 " : 3333333333333333;", 6683 Style); 6684 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n" 6685 " : bbbbbbbbbbbbbb ? 222222\n" 6686 " : 333333;", 6687 Style); 6688 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n" 6689 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 6690 " : cccccccccccccc ? 3333333333333333\n" 6691 " : 4444444444444444;", 6692 Style); 6693 verifyFormat("return aaaaaaaaaaaaaaaa ? (aaa ? bbb : ccc)\n" 6694 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 6695 " : 3333333333333333;", 6696 Style); 6697 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n" 6698 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 6699 " : (aaa ? bbb : ccc);", 6700 Style); 6701 verifyFormat( 6702 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 6703 " : cccccccccccccccccc)\n" 6704 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 6705 " : 3333333333333333;", 6706 Style); 6707 verifyFormat( 6708 "return aaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 6709 " : cccccccccccccccccc)\n" 6710 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 6711 " : 3333333333333333;", 6712 Style); 6713 verifyFormat( 6714 "return aaaaaaaaa ? a = (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 6715 " : dddddddddddddddddd)\n" 6716 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 6717 " : 3333333333333333;", 6718 Style); 6719 verifyFormat( 6720 "return aaaaaaaaa ? a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 6721 " : dddddddddddddddddd)\n" 6722 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 6723 " : 3333333333333333;", 6724 Style); 6725 verifyFormat( 6726 "return aaaaaaaaa ? 1111111111111111\n" 6727 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 6728 " : a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 6729 " : dddddddddddddddddd)\n", 6730 Style); 6731 verifyFormat( 6732 "return aaaaaaaaaaaaaaaa ? 1111111111111111\n" 6733 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 6734 " : (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 6735 " : cccccccccccccccccc);", 6736 Style); 6737 verifyFormat( 6738 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 6739 " : ccccccccccccccc ? dddddddddddddddddd\n" 6740 " : eeeeeeeeeeeeeeeeee)\n" 6741 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 6742 " : 3333333333333333;", 6743 Style); 6744 verifyFormat( 6745 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 6746 " : ccccccccccccccc ? dddddddddddddddddd\n" 6747 " : eeeeeeeeeeeeeeeeee)\n" 6748 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 6749 " : 3333333333333333;", 6750 Style); 6751 verifyFormat( 6752 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 6753 " : cccccccccccc ? dddddddddddddddddd\n" 6754 " : eeeeeeeeeeeeeeeeee)\n" 6755 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 6756 " : 3333333333333333;", 6757 Style); 6758 verifyFormat( 6759 "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 6760 " : cccccccccccccccccc\n" 6761 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 6762 " : 3333333333333333;", 6763 Style); 6764 verifyFormat( 6765 "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 6766 " : cccccccccccccccc ? dddddddddddddddddd\n" 6767 " : eeeeeeeeeeeeeeeeee\n" 6768 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 6769 " : 3333333333333333;", 6770 Style); 6771 verifyFormat("return aaaaaaaaaaaaaaaaaaaaa\n" 6772 " ? (aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 6773 " : cccccccccccccccccc ? dddddddddddddddddd\n" 6774 " : eeeeeeeeeeeeeeeeee)\n" 6775 " : bbbbbbbbbbbbbbbbbbb ? 2222222222222222\n" 6776 " : 3333333333333333;", 6777 Style); 6778 verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaa\n" 6779 " ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 6780 " : cccccccccccccccc ? dddddddddddddddddd\n" 6781 " : eeeeeeeeeeeeeeeeee\n" 6782 " : bbbbbbbbbbbbbbbbbbbbbbb ? 2222222222222222\n" 6783 " : 3333333333333333;", 6784 Style); 6785 6786 Style.AlignOperands = FormatStyle::OAS_DontAlign; 6787 Style.BreakBeforeTernaryOperators = false; 6788 // FIXME: Aligning the question marks is weird given DontAlign. 6789 // Consider disabling this alignment in this case. Also check whether this 6790 // will render the adjustment from https://reviews.llvm.org/D82199 6791 // unnecessary. 6792 verifyFormat("int x = aaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa :\n" 6793 " bbbb ? cccccccccccccccccc :\n" 6794 " ddddd;\n", 6795 Style); 6796 6797 EXPECT_EQ( 6798 "MMMMMMMMMMMMMMMMMMMMMMMMMMM = A ?\n" 6799 " /*\n" 6800 " */\n" 6801 " function() {\n" 6802 " try {\n" 6803 " return JJJJJJJJJJJJJJ(\n" 6804 " pppppppppppppppppppppppppppppppppppppppppppppppppp);\n" 6805 " }\n" 6806 " } :\n" 6807 " function() {};", 6808 format( 6809 "MMMMMMMMMMMMMMMMMMMMMMMMMMM = A ?\n" 6810 " /*\n" 6811 " */\n" 6812 " function() {\n" 6813 " try {\n" 6814 " return JJJJJJJJJJJJJJ(\n" 6815 " pppppppppppppppppppppppppppppppppppppppppppppppppp);\n" 6816 " }\n" 6817 " } :\n" 6818 " function() {};", 6819 getGoogleStyle(FormatStyle::LK_JavaScript))); 6820 } 6821 6822 TEST_F(FormatTest, BreaksConditionalExpressionsAfterOperator) { 6823 FormatStyle Style = getLLVMStyle(); 6824 Style.BreakBeforeTernaryOperators = false; 6825 Style.ColumnLimit = 70; 6826 verifyFormat( 6827 "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaa ?\n" 6828 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n" 6829 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 6830 Style); 6831 verifyFormat( 6832 "aaaa(aaaaaaaaaa, aaaaaaaa,\n" 6833 " aaaaaaaaaaaaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n" 6834 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 6835 Style); 6836 verifyFormat( 6837 "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n" 6838 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 6839 Style); 6840 verifyFormat("aaaa(aaaaaaaa, aaaaaaaaaa,\n" 6841 " aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n" 6842 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 6843 Style); 6844 verifyFormat( 6845 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa ? aaaa(aaaaaa) :\n" 6846 " aaaaaaaaaaaaa);", 6847 Style); 6848 verifyFormat( 6849 "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n" 6850 " aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n" 6851 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 6852 " aaaaaaaaaaaaa);", 6853 Style); 6854 verifyFormat( 6855 "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n" 6856 " aaaaaaaaaaaaaaaa ?: aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 6857 " aaaaaaaaaaaaa);", 6858 Style); 6859 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n" 6860 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6861 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) :\n" 6862 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6863 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 6864 Style); 6865 verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 6866 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n" 6867 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6868 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) :\n" 6869 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6870 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 6871 " aaaaaaaaaaaaaaaaaaaaaaaaaaa);", 6872 Style); 6873 verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 6874 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?:\n" 6875 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6876 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 6877 " aaaaaaaaaaaaaaaaaaaaaaaaaaa);", 6878 Style); 6879 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n" 6880 " aaaaaaaaaaaaaaaaaaaaaaaaaaa :\n" 6881 " aaaaaaaaaaaaaaaaaaaaaaaaaaa;", 6882 Style); 6883 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaa =\n" 6884 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n" 6885 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n" 6886 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;", 6887 Style); 6888 verifyFormat( 6889 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n" 6890 " aaaaaaaaaaaaaaa :\n" 6891 " aaaaaaaaaaaaaaa;", 6892 Style); 6893 verifyFormat("f(aaaaaaaaaaaaaaaa == // force break\n" 6894 " aaaaaaaaa ?\n" 6895 " b :\n" 6896 " c);", 6897 Style); 6898 verifyFormat("unsigned Indent =\n" 6899 " format(TheLine.First,\n" 6900 " IndentForLevel[TheLine.Level] >= 0 ?\n" 6901 " IndentForLevel[TheLine.Level] :\n" 6902 " TheLine * 2,\n" 6903 " TheLine.InPPDirective, PreviousEndOfLineColumn);", 6904 Style); 6905 verifyFormat("bool aaaaaa = aaaaaaaaaaaaa ? //\n" 6906 " aaaaaaaaaaaaaaa :\n" 6907 " bbbbbbbbbbbbbbb ? //\n" 6908 " ccccccccccccccc :\n" 6909 " ddddddddddddddd;", 6910 Style); 6911 verifyFormat("bool aaaaaa = aaaaaaaaaaaaa ? //\n" 6912 " aaaaaaaaaaaaaaa :\n" 6913 " (bbbbbbbbbbbbbbb ? //\n" 6914 " ccccccccccccccc :\n" 6915 " ddddddddddddddd);", 6916 Style); 6917 verifyFormat("int i = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n" 6918 " /*bbbbbbbbbbbbbbb=*/bbbbbbbbbbbbbbbbbbbbbbbbb :\n" 6919 " ccccccccccccccccccccccccccc;", 6920 Style); 6921 verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n" 6922 " aaaaa :\n" 6923 " bbbbbbbbbbbbbbb + cccccccccccccccc;", 6924 Style); 6925 6926 // Chained conditionals 6927 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n" 6928 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 6929 " 3333333333333333;", 6930 Style); 6931 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n" 6932 " bbbbbbbbbb ? 2222222222222222 :\n" 6933 " 3333333333333333;", 6934 Style); 6935 verifyFormat("return aaaaaaaaaa ? 1111111111111111 :\n" 6936 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 6937 " 3333333333333333;", 6938 Style); 6939 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n" 6940 " bbbbbbbbbbbbbbbb ? 222222 :\n" 6941 " 333333;", 6942 Style); 6943 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n" 6944 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 6945 " cccccccccccccccc ? 3333333333333333 :\n" 6946 " 4444444444444444;", 6947 Style); 6948 verifyFormat("return aaaaaaaaaaaaaaaa ? (aaa ? bbb : ccc) :\n" 6949 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 6950 " 3333333333333333;", 6951 Style); 6952 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n" 6953 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 6954 " (aaa ? bbb : ccc);", 6955 Style); 6956 verifyFormat( 6957 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 6958 " cccccccccccccccccc) :\n" 6959 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 6960 " 3333333333333333;", 6961 Style); 6962 verifyFormat( 6963 "return aaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 6964 " cccccccccccccccccc) :\n" 6965 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 6966 " 3333333333333333;", 6967 Style); 6968 verifyFormat( 6969 "return aaaaaaaaa ? a = (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 6970 " dddddddddddddddddd) :\n" 6971 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 6972 " 3333333333333333;", 6973 Style); 6974 verifyFormat( 6975 "return aaaaaaaaa ? a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 6976 " dddddddddddddddddd) :\n" 6977 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 6978 " 3333333333333333;", 6979 Style); 6980 verifyFormat( 6981 "return aaaaaaaaa ? 1111111111111111 :\n" 6982 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 6983 " a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 6984 " dddddddddddddddddd)\n", 6985 Style); 6986 verifyFormat( 6987 "return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n" 6988 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 6989 " (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 6990 " cccccccccccccccccc);", 6991 Style); 6992 verifyFormat( 6993 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 6994 " ccccccccccccccccc ? dddddddddddddddddd :\n" 6995 " eeeeeeeeeeeeeeeeee) :\n" 6996 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 6997 " 3333333333333333;", 6998 Style); 6999 verifyFormat( 7000 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 7001 " ccccccccccccc ? dddddddddddddddddd :\n" 7002 " eeeeeeeeeeeeeeeeee) :\n" 7003 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 7004 " 3333333333333333;", 7005 Style); 7006 verifyFormat( 7007 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 7008 " ccccccccccccccccc ? dddddddddddddddddd :\n" 7009 " eeeeeeeeeeeeeeeeee) :\n" 7010 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 7011 " 3333333333333333;", 7012 Style); 7013 verifyFormat( 7014 "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 7015 " cccccccccccccccccc :\n" 7016 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 7017 " 3333333333333333;", 7018 Style); 7019 verifyFormat( 7020 "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 7021 " cccccccccccccccccc ? dddddddddddddddddd :\n" 7022 " eeeeeeeeeeeeeeeeee :\n" 7023 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 7024 " 3333333333333333;", 7025 Style); 7026 verifyFormat("return aaaaaaaaaaaaaaaaaaaaa ?\n" 7027 " (aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 7028 " cccccccccccccccccc ? dddddddddddddddddd :\n" 7029 " eeeeeeeeeeeeeeeeee) :\n" 7030 " bbbbbbbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 7031 " 3333333333333333;", 7032 Style); 7033 verifyFormat("return aaaaaaaaaaaaaaaaaaaaa ?\n" 7034 " aaaaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 7035 " cccccccccccccccccccc ? dddddddddddddddddd :\n" 7036 " eeeeeeeeeeeeeeeeee :\n" 7037 " bbbbbbbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 7038 " 3333333333333333;", 7039 Style); 7040 } 7041 7042 TEST_F(FormatTest, DeclarationsOfMultipleVariables) { 7043 verifyFormat("bool aaaaaaaaaaaaaaaaa = aaaaaa->aaaaaaaaaaaaaaaaa(),\n" 7044 " aaaaaaaaaaa = aaaaaa->aaaaaaaaaaa();"); 7045 verifyFormat("bool a = true, b = false;"); 7046 7047 verifyFormat("bool aaaaaaaaaaaaaaaaaaaaaaaaa =\n" 7048 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaa),\n" 7049 " bbbbbbbbbbbbbbbbbbbbbbbbb =\n" 7050 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(bbbbbbbbbbbbbbbb);"); 7051 verifyFormat( 7052 "bool aaaaaaaaaaaaaaaaaaaaa =\n" 7053 " bbbbbbbbbbbbbbbbbbbbbbbbbbbb && cccccccccccccccccccccccccccc,\n" 7054 " d = e && f;"); 7055 verifyFormat("aaaaaaaaa a = aaaaaaaaaaaaaaaaaaaa, b = bbbbbbbbbbbbbbbbbbbb,\n" 7056 " c = cccccccccccccccccccc, d = dddddddddddddddddddd;"); 7057 verifyFormat("aaaaaaaaa *a = aaaaaaaaaaaaaaaaaaa, *b = bbbbbbbbbbbbbbbbbbb,\n" 7058 " *c = ccccccccccccccccccc, *d = ddddddddddddddddddd;"); 7059 verifyFormat("aaaaaaaaa ***a = aaaaaaaaaaaaaaaaaaa, ***b = bbbbbbbbbbbbbbb,\n" 7060 " ***c = ccccccccccccccccccc, ***d = ddddddddddddddd;"); 7061 7062 FormatStyle Style = getGoogleStyle(); 7063 Style.PointerAlignment = FormatStyle::PAS_Left; 7064 Style.DerivePointerAlignment = false; 7065 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7066 " *aaaaaaaaaaaaaaaaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaa,\n" 7067 " *b = bbbbbbbbbbbbbbbbbbb;", 7068 Style); 7069 verifyFormat("aaaaaaaaa *a = aaaaaaaaaaaaaaaaaaa, *b = bbbbbbbbbbbbbbbbbbb,\n" 7070 " *b = bbbbbbbbbbbbbbbbbbb, *d = ddddddddddddddddddd;", 7071 Style); 7072 verifyFormat("vector<int*> a, b;", Style); 7073 verifyFormat("for (int *p, *q; p != q; p = p->next) {\n}", Style); 7074 } 7075 7076 TEST_F(FormatTest, ConditionalExpressionsInBrackets) { 7077 verifyFormat("arr[foo ? bar : baz];"); 7078 verifyFormat("f()[foo ? bar : baz];"); 7079 verifyFormat("(a + b)[foo ? bar : baz];"); 7080 verifyFormat("arr[foo ? (4 > 5 ? 4 : 5) : 5 < 5 ? 5 : 7];"); 7081 } 7082 7083 TEST_F(FormatTest, AlignsStringLiterals) { 7084 verifyFormat("loooooooooooooooooooooooooongFunction(\"short literal \"\n" 7085 " \"short literal\");"); 7086 verifyFormat( 7087 "looooooooooooooooooooooooongFunction(\n" 7088 " \"short literal\"\n" 7089 " \"looooooooooooooooooooooooooooooooooooooooooooooooong literal\");"); 7090 verifyFormat("someFunction(\"Always break between multi-line\"\n" 7091 " \" string literals\",\n" 7092 " and, other, parameters);"); 7093 EXPECT_EQ("fun + \"1243\" /* comment */\n" 7094 " \"5678\";", 7095 format("fun + \"1243\" /* comment */\n" 7096 " \"5678\";", 7097 getLLVMStyleWithColumns(28))); 7098 EXPECT_EQ( 7099 "aaaaaa = \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n" 7100 " \"aaaaaaaaaaaaaaaaaaaaa\"\n" 7101 " \"aaaaaaaaaaaaaaaa\";", 7102 format("aaaaaa =" 7103 "\"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaa " 7104 "aaaaaaaaaaaaaaaaaaaaa\" " 7105 "\"aaaaaaaaaaaaaaaa\";")); 7106 verifyFormat("a = a + \"a\"\n" 7107 " \"a\"\n" 7108 " \"a\";"); 7109 verifyFormat("f(\"a\", \"b\"\n" 7110 " \"c\");"); 7111 7112 verifyFormat( 7113 "#define LL_FORMAT \"ll\"\n" 7114 "printf(\"aaaaa: %d, bbbbbb: %\" LL_FORMAT \"d, cccccccc: %\" LL_FORMAT\n" 7115 " \"d, ddddddddd: %\" LL_FORMAT \"d\");"); 7116 7117 verifyFormat("#define A(X) \\\n" 7118 " \"aaaaa\" #X \"bbbbbb\" \\\n" 7119 " \"ccccc\"", 7120 getLLVMStyleWithColumns(23)); 7121 verifyFormat("#define A \"def\"\n" 7122 "f(\"abc\" A \"ghi\"\n" 7123 " \"jkl\");"); 7124 7125 verifyFormat("f(L\"a\"\n" 7126 " L\"b\");"); 7127 verifyFormat("#define A(X) \\\n" 7128 " L\"aaaaa\" #X L\"bbbbbb\" \\\n" 7129 " L\"ccccc\"", 7130 getLLVMStyleWithColumns(25)); 7131 7132 verifyFormat("f(@\"a\"\n" 7133 " @\"b\");"); 7134 verifyFormat("NSString s = @\"a\"\n" 7135 " @\"b\"\n" 7136 " @\"c\";"); 7137 verifyFormat("NSString s = @\"a\"\n" 7138 " \"b\"\n" 7139 " \"c\";"); 7140 } 7141 7142 TEST_F(FormatTest, ReturnTypeBreakingStyle) { 7143 FormatStyle Style = getLLVMStyle(); 7144 // No declarations or definitions should be moved to own line. 7145 Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_None; 7146 verifyFormat("class A {\n" 7147 " int f() { return 1; }\n" 7148 " int g();\n" 7149 "};\n" 7150 "int f() { return 1; }\n" 7151 "int g();\n", 7152 Style); 7153 7154 // All declarations and definitions should have the return type moved to its 7155 // own line. 7156 Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_All; 7157 Style.TypenameMacros = {"LIST"}; 7158 verifyFormat("SomeType\n" 7159 "funcdecl(LIST(uint64_t));", 7160 Style); 7161 verifyFormat("class E {\n" 7162 " int\n" 7163 " f() {\n" 7164 " return 1;\n" 7165 " }\n" 7166 " int\n" 7167 " g();\n" 7168 "};\n" 7169 "int\n" 7170 "f() {\n" 7171 " return 1;\n" 7172 "}\n" 7173 "int\n" 7174 "g();\n", 7175 Style); 7176 7177 // Top-level definitions, and no kinds of declarations should have the 7178 // return type moved to its own line. 7179 Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_TopLevelDefinitions; 7180 verifyFormat("class B {\n" 7181 " int f() { return 1; }\n" 7182 " int g();\n" 7183 "};\n" 7184 "int\n" 7185 "f() {\n" 7186 " return 1;\n" 7187 "}\n" 7188 "int g();\n", 7189 Style); 7190 7191 // Top-level definitions and declarations should have the return type moved 7192 // to its own line. 7193 Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_TopLevel; 7194 verifyFormat("class C {\n" 7195 " int f() { return 1; }\n" 7196 " int g();\n" 7197 "};\n" 7198 "int\n" 7199 "f() {\n" 7200 " return 1;\n" 7201 "}\n" 7202 "int\n" 7203 "g();\n", 7204 Style); 7205 7206 // All definitions should have the return type moved to its own line, but no 7207 // kinds of declarations. 7208 Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_AllDefinitions; 7209 verifyFormat("class D {\n" 7210 " int\n" 7211 " f() {\n" 7212 " return 1;\n" 7213 " }\n" 7214 " int g();\n" 7215 "};\n" 7216 "int\n" 7217 "f() {\n" 7218 " return 1;\n" 7219 "}\n" 7220 "int g();\n", 7221 Style); 7222 verifyFormat("const char *\n" 7223 "f(void) {\n" // Break here. 7224 " return \"\";\n" 7225 "}\n" 7226 "const char *bar(void);\n", // No break here. 7227 Style); 7228 verifyFormat("template <class T>\n" 7229 "T *\n" 7230 "f(T &c) {\n" // Break here. 7231 " return NULL;\n" 7232 "}\n" 7233 "template <class T> T *f(T &c);\n", // No break here. 7234 Style); 7235 verifyFormat("class C {\n" 7236 " int\n" 7237 " operator+() {\n" 7238 " return 1;\n" 7239 " }\n" 7240 " int\n" 7241 " operator()() {\n" 7242 " return 1;\n" 7243 " }\n" 7244 "};\n", 7245 Style); 7246 verifyFormat("void\n" 7247 "A::operator()() {}\n" 7248 "void\n" 7249 "A::operator>>() {}\n" 7250 "void\n" 7251 "A::operator+() {}\n" 7252 "void\n" 7253 "A::operator*() {}\n" 7254 "void\n" 7255 "A::operator->() {}\n" 7256 "void\n" 7257 "A::operator void *() {}\n" 7258 "void\n" 7259 "A::operator void &() {}\n" 7260 "void\n" 7261 "A::operator void &&() {}\n" 7262 "void\n" 7263 "A::operator char *() {}\n" 7264 "void\n" 7265 "A::operator[]() {}\n" 7266 "void\n" 7267 "A::operator!() {}\n" 7268 "void\n" 7269 "A::operator**() {}\n" 7270 "void\n" 7271 "A::operator<Foo> *() {}\n" 7272 "void\n" 7273 "A::operator<Foo> **() {}\n" 7274 "void\n" 7275 "A::operator<Foo> &() {}\n" 7276 "void\n" 7277 "A::operator void **() {}\n", 7278 Style); 7279 verifyFormat("constexpr auto\n" 7280 "operator()() const -> reference {}\n" 7281 "constexpr auto\n" 7282 "operator>>() const -> reference {}\n" 7283 "constexpr auto\n" 7284 "operator+() const -> reference {}\n" 7285 "constexpr auto\n" 7286 "operator*() const -> reference {}\n" 7287 "constexpr auto\n" 7288 "operator->() const -> reference {}\n" 7289 "constexpr auto\n" 7290 "operator++() const -> reference {}\n" 7291 "constexpr auto\n" 7292 "operator void *() const -> reference {}\n" 7293 "constexpr auto\n" 7294 "operator void **() const -> reference {}\n" 7295 "constexpr auto\n" 7296 "operator void *() const -> reference {}\n" 7297 "constexpr auto\n" 7298 "operator void &() const -> reference {}\n" 7299 "constexpr auto\n" 7300 "operator void &&() const -> reference {}\n" 7301 "constexpr auto\n" 7302 "operator char *() const -> reference {}\n" 7303 "constexpr auto\n" 7304 "operator!() const -> reference {}\n" 7305 "constexpr auto\n" 7306 "operator[]() const -> reference {}\n", 7307 Style); 7308 verifyFormat("void *operator new(std::size_t s);", // No break here. 7309 Style); 7310 verifyFormat("void *\n" 7311 "operator new(std::size_t s) {}", 7312 Style); 7313 verifyFormat("void *\n" 7314 "operator delete[](void *ptr) {}", 7315 Style); 7316 Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup; 7317 verifyFormat("const char *\n" 7318 "f(void)\n" // Break here. 7319 "{\n" 7320 " return \"\";\n" 7321 "}\n" 7322 "const char *bar(void);\n", // No break here. 7323 Style); 7324 verifyFormat("template <class T>\n" 7325 "T *\n" // Problem here: no line break 7326 "f(T &c)\n" // Break here. 7327 "{\n" 7328 " return NULL;\n" 7329 "}\n" 7330 "template <class T> T *f(T &c);\n", // No break here. 7331 Style); 7332 verifyFormat("int\n" 7333 "foo(A<bool> a)\n" 7334 "{\n" 7335 " return a;\n" 7336 "}\n", 7337 Style); 7338 verifyFormat("int\n" 7339 "foo(A<8> a)\n" 7340 "{\n" 7341 " return a;\n" 7342 "}\n", 7343 Style); 7344 verifyFormat("int\n" 7345 "foo(A<B<bool>, 8> a)\n" 7346 "{\n" 7347 " return a;\n" 7348 "}\n", 7349 Style); 7350 verifyFormat("int\n" 7351 "foo(A<B<8>, bool> a)\n" 7352 "{\n" 7353 " return a;\n" 7354 "}\n", 7355 Style); 7356 verifyFormat("int\n" 7357 "foo(A<B<bool>, bool> a)\n" 7358 "{\n" 7359 " return a;\n" 7360 "}\n", 7361 Style); 7362 verifyFormat("int\n" 7363 "foo(A<B<8>, 8> a)\n" 7364 "{\n" 7365 " return a;\n" 7366 "}\n", 7367 Style); 7368 7369 Style = getGNUStyle(); 7370 7371 // Test for comments at the end of function declarations. 7372 verifyFormat("void\n" 7373 "foo (int a, /*abc*/ int b) // def\n" 7374 "{\n" 7375 "}\n", 7376 Style); 7377 7378 verifyFormat("void\n" 7379 "foo (int a, /* abc */ int b) /* def */\n" 7380 "{\n" 7381 "}\n", 7382 Style); 7383 7384 // Definitions that should not break after return type 7385 verifyFormat("void foo (int a, int b); // def\n", Style); 7386 verifyFormat("void foo (int a, int b); /* def */\n", Style); 7387 verifyFormat("void foo (int a, int b);\n", Style); 7388 } 7389 7390 TEST_F(FormatTest, AlwaysBreakBeforeMultilineStrings) { 7391 FormatStyle NoBreak = getLLVMStyle(); 7392 NoBreak.AlwaysBreakBeforeMultilineStrings = false; 7393 FormatStyle Break = getLLVMStyle(); 7394 Break.AlwaysBreakBeforeMultilineStrings = true; 7395 verifyFormat("aaaa = \"bbbb\"\n" 7396 " \"cccc\";", 7397 NoBreak); 7398 verifyFormat("aaaa =\n" 7399 " \"bbbb\"\n" 7400 " \"cccc\";", 7401 Break); 7402 verifyFormat("aaaa(\"bbbb\"\n" 7403 " \"cccc\");", 7404 NoBreak); 7405 verifyFormat("aaaa(\n" 7406 " \"bbbb\"\n" 7407 " \"cccc\");", 7408 Break); 7409 verifyFormat("aaaa(qqq, \"bbbb\"\n" 7410 " \"cccc\");", 7411 NoBreak); 7412 verifyFormat("aaaa(qqq,\n" 7413 " \"bbbb\"\n" 7414 " \"cccc\");", 7415 Break); 7416 verifyFormat("aaaa(qqq,\n" 7417 " L\"bbbb\"\n" 7418 " L\"cccc\");", 7419 Break); 7420 verifyFormat("aaaaa(aaaaaa, aaaaaaa(\"aaaa\"\n" 7421 " \"bbbb\"));", 7422 Break); 7423 verifyFormat("string s = someFunction(\n" 7424 " \"abc\"\n" 7425 " \"abc\");", 7426 Break); 7427 7428 // As we break before unary operators, breaking right after them is bad. 7429 verifyFormat("string foo = abc ? \"x\"\n" 7430 " \"blah blah blah blah blah blah\"\n" 7431 " : \"y\";", 7432 Break); 7433 7434 // Don't break if there is no column gain. 7435 verifyFormat("f(\"aaaa\"\n" 7436 " \"bbbb\");", 7437 Break); 7438 7439 // Treat literals with escaped newlines like multi-line string literals. 7440 EXPECT_EQ("x = \"a\\\n" 7441 "b\\\n" 7442 "c\";", 7443 format("x = \"a\\\n" 7444 "b\\\n" 7445 "c\";", 7446 NoBreak)); 7447 EXPECT_EQ("xxxx =\n" 7448 " \"a\\\n" 7449 "b\\\n" 7450 "c\";", 7451 format("xxxx = \"a\\\n" 7452 "b\\\n" 7453 "c\";", 7454 Break)); 7455 7456 EXPECT_EQ("NSString *const kString =\n" 7457 " @\"aaaa\"\n" 7458 " @\"bbbb\";", 7459 format("NSString *const kString = @\"aaaa\"\n" 7460 "@\"bbbb\";", 7461 Break)); 7462 7463 Break.ColumnLimit = 0; 7464 verifyFormat("const char *hello = \"hello llvm\";", Break); 7465 } 7466 7467 TEST_F(FormatTest, AlignsPipes) { 7468 verifyFormat( 7469 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7470 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7471 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 7472 verifyFormat( 7473 "aaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaa\n" 7474 " << aaaaaaaaaaaaaaaaaaaa;"); 7475 verifyFormat( 7476 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7477 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 7478 verifyFormat( 7479 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 7480 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 7481 verifyFormat( 7482 "llvm::outs() << \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"\n" 7483 " \"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\"\n" 7484 " << \"ccccccccccccccccccccccccccccccccccccccccccccccccc\";"); 7485 verifyFormat( 7486 "aaaaaaaa << (aaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7487 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 7488 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 7489 verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7490 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7491 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 7492 " << bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;"); 7493 verifyFormat("llvm::errs() << \"aaaaaaaaaaaaaaaaaaaaaaa: \"\n" 7494 " << aaaaaaaaaaaaaaaaa(aaaaaaaa, aaaaaaaaaaa);"); 7495 verifyFormat( 7496 "llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7497 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7498 verifyFormat( 7499 "auto Diag = diag() << aaaaaaaaaaaaaaaa(aaaaaaaaaaaa, aaaaaaaaaaaaa,\n" 7500 " aaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7501 7502 verifyFormat("llvm::outs() << \"aaaaaaaaaaaaaaaa: \"\n" 7503 " << aaaaaaaa.aaaaaaaaaaaa(aaa)->aaaaaaaaaaaaaa();"); 7504 verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7505 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7506 " aaaaaaaaaaaaaaaaaaaaa)\n" 7507 " << aaaaaaaaaaaaaaaaaaaaaaaaaa;"); 7508 verifyFormat("LOG_IF(aaa == //\n" 7509 " bbb)\n" 7510 " << a << b;"); 7511 7512 // But sometimes, breaking before the first "<<" is desirable. 7513 verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaa, aaaaaaaa)\n" 7514 " << aaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaa);"); 7515 verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbb)\n" 7516 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7517 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 7518 verifyFormat("SemaRef.Diag(Loc, diag::note_for_range_begin_end)\n" 7519 " << BEF << IsTemplate << Description << E->getType();"); 7520 verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaa, aaaaaaaa)\n" 7521 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7522 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7523 verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaa, aaaaaaaa)\n" 7524 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7525 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 7526 " << aaa;"); 7527 7528 verifyFormat( 7529 "llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7530 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 7531 7532 // Incomplete string literal. 7533 EXPECT_EQ("llvm::errs() << \"\n" 7534 " << a;", 7535 format("llvm::errs() << \"\n<<a;")); 7536 7537 verifyFormat("void f() {\n" 7538 " CHECK_EQ(aaaa, (*bbbbbbbbb)->cccccc)\n" 7539 " << \"qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\";\n" 7540 "}"); 7541 7542 // Handle 'endl'. 7543 verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaa << endl\n" 7544 " << bbbbbbbbbbbbbbbbbbbbbb << endl;"); 7545 verifyFormat("llvm::errs() << endl << bbbbbbbbbbbbbbbbbbbbbb << endl;"); 7546 7547 // Handle '\n'. 7548 verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaa << \"\\n\"\n" 7549 " << bbbbbbbbbbbbbbbbbbbbbb << \"\\n\";"); 7550 verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaa << \'\\n\'\n" 7551 " << bbbbbbbbbbbbbbbbbbbbbb << \'\\n\';"); 7552 verifyFormat("llvm::errs() << aaaa << \"aaaaaaaaaaaaaaaaaa\\n\"\n" 7553 " << bbbb << \"bbbbbbbbbbbbbbbbbb\\n\";"); 7554 verifyFormat("llvm::errs() << \"\\n\" << bbbbbbbbbbbbbbbbbbbbbb << \"\\n\";"); 7555 } 7556 7557 TEST_F(FormatTest, KeepStringLabelValuePairsOnALine) { 7558 verifyFormat("return out << \"somepacket = {\\n\"\n" 7559 " << \" aaaaaa = \" << pkt.aaaaaa << \"\\n\"\n" 7560 " << \" bbbb = \" << pkt.bbbb << \"\\n\"\n" 7561 " << \" cccccc = \" << pkt.cccccc << \"\\n\"\n" 7562 " << \" ddd = [\" << pkt.ddd << \"]\\n\"\n" 7563 " << \"}\";"); 7564 7565 verifyFormat("llvm::outs() << \"aaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaa\n" 7566 " << \"aaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaa\n" 7567 " << \"aaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaa;"); 7568 verifyFormat( 7569 "llvm::outs() << \"aaaaaaaaaaaaaaaaa = \" << aaaaaaaaaaaaaaaaa\n" 7570 " << \"bbbbbbbbbbbbbbbbb = \" << bbbbbbbbbbbbbbbbb\n" 7571 " << \"ccccccccccccccccc = \" << ccccccccccccccccc\n" 7572 " << \"ddddddddddddddddd = \" << ddddddddddddddddd\n" 7573 " << \"eeeeeeeeeeeeeeeee = \" << eeeeeeeeeeeeeeeee;"); 7574 verifyFormat("llvm::outs() << aaaaaaaaaaaaaaaaaaaaaaaa << \"=\"\n" 7575 " << bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;"); 7576 verifyFormat( 7577 "void f() {\n" 7578 " llvm::outs() << \"aaaaaaaaaaaaaaaaaaaa: \"\n" 7579 " << aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n" 7580 "}"); 7581 7582 // Breaking before the first "<<" is generally not desirable. 7583 verifyFormat( 7584 "llvm::errs()\n" 7585 " << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7586 " << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7587 " << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7588 " << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;", 7589 getLLVMStyleWithColumns(70)); 7590 verifyFormat("llvm::errs() << \"aaaaaaaaaaaaaaaaaaa: \"\n" 7591 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7592 " << \"aaaaaaaaaaaaaaaaaaa: \"\n" 7593 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7594 " << \"aaaaaaaaaaaaaaaaaaa: \"\n" 7595 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;", 7596 getLLVMStyleWithColumns(70)); 7597 7598 verifyFormat("string v = \"aaaaaaaaaaaaaaaa: \" + aaaaaaaaaaaaaaaa +\n" 7599 " \"aaaaaaaaaaaaaaaa: \" + aaaaaaaaaaaaaaaa +\n" 7600 " \"aaaaaaaaaaaaaaaa: \" + aaaaaaaaaaaaaaaa;"); 7601 verifyFormat("string v = StrCat(\"aaaaaaaaaaaaaaaa: \", aaaaaaaaaaaaaaaa,\n" 7602 " \"aaaaaaaaaaaaaaaa: \", aaaaaaaaaaaaaaaa,\n" 7603 " \"aaaaaaaaaaaaaaaa: \", aaaaaaaaaaaaaaaa);"); 7604 verifyFormat("string v = \"aaaaaaaaaaaaaaaa: \" +\n" 7605 " (aaaa + aaaa);", 7606 getLLVMStyleWithColumns(40)); 7607 verifyFormat("string v = StrCat(\"aaaaaaaaaaaa: \" +\n" 7608 " (aaaaaaa + aaaaa));", 7609 getLLVMStyleWithColumns(40)); 7610 verifyFormat( 7611 "string v = StrCat(\"aaaaaaaaaaaaaaaaaaaaaaaaaaa: \",\n" 7612 " SomeFunction(aaaaaaaaaaaa, aaaaaaaa.aaaaaaa),\n" 7613 " bbbbbbbbbbbbbbbbbbbbbbb);"); 7614 } 7615 7616 TEST_F(FormatTest, UnderstandsEquals) { 7617 verifyFormat( 7618 "aaaaaaaaaaaaaaaaa =\n" 7619 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 7620 verifyFormat( 7621 "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n" 7622 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}"); 7623 verifyFormat( 7624 "if (a) {\n" 7625 " f();\n" 7626 "} else if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n" 7627 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n" 7628 "}"); 7629 7630 verifyFormat("if (int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n" 7631 " 100000000 + 10000000) {\n}"); 7632 } 7633 7634 TEST_F(FormatTest, WrapsAtFunctionCallsIfNecessary) { 7635 verifyFormat("LoooooooooooooooooooooooooooooooooooooongObject\n" 7636 " .looooooooooooooooooooooooooooooooooooooongFunction();"); 7637 7638 verifyFormat("LoooooooooooooooooooooooooooooooooooooongObject\n" 7639 " ->looooooooooooooooooooooooooooooooooooooongFunction();"); 7640 7641 verifyFormat( 7642 "LooooooooooooooooooooooooooooooooongObject->shortFunction(Parameter1,\n" 7643 " Parameter2);"); 7644 7645 verifyFormat( 7646 "ShortObject->shortFunction(\n" 7647 " LooooooooooooooooooooooooooooooooooooooooooooooongParameter1,\n" 7648 " LooooooooooooooooooooooooooooooooooooooooooooooongParameter2);"); 7649 7650 verifyFormat("loooooooooooooongFunction(\n" 7651 " LoooooooooooooongObject->looooooooooooooooongFunction());"); 7652 7653 verifyFormat( 7654 "function(LoooooooooooooooooooooooooooooooooooongObject\n" 7655 " ->loooooooooooooooooooooooooooooooooooooooongFunction());"); 7656 7657 verifyFormat("EXPECT_CALL(SomeObject, SomeFunction(Parameter))\n" 7658 " .WillRepeatedly(Return(SomeValue));"); 7659 verifyFormat("void f() {\n" 7660 " EXPECT_CALL(SomeObject, SomeFunction(Parameter))\n" 7661 " .Times(2)\n" 7662 " .WillRepeatedly(Return(SomeValue));\n" 7663 "}"); 7664 verifyFormat("SomeMap[std::pair(aaaaaaaaaaaa, bbbbbbbbbbbbbbb)].insert(\n" 7665 " ccccccccccccccccccccccc);"); 7666 verifyFormat("aaaaa(aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7667 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 7668 " .aaaaa(aaaaa),\n" 7669 " aaaaaaaaaaaaaaaaaaaaa);"); 7670 verifyFormat("void f() {\n" 7671 " aaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7672 " aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa)->aaaaaaaaa());\n" 7673 "}"); 7674 verifyFormat("aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7675 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 7676 " .aaaaaaaaaaaaaaa(aa(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7677 " aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7678 " aaaaaaaaaaaaaaaaaaaaaaaaaaa));"); 7679 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7680 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7681 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7682 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()) {\n" 7683 "}"); 7684 7685 // Here, it is not necessary to wrap at "." or "->". 7686 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaa) ||\n" 7687 " aaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}"); 7688 verifyFormat( 7689 "aaaaaaaaaaa->aaaaaaaaa(\n" 7690 " aaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7691 " aaaaaaaaaaaaaaaaaa->aaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa));\n"); 7692 7693 verifyFormat( 7694 "aaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7695 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa().aaaaaaaaaaaaaaaaa());"); 7696 verifyFormat("a->aaaaaa()->aaaaaaaaaaa(aaaaaaaa()->aaaaaa()->aaaaa() *\n" 7697 " aaaaaaaaa()->aaaaaa()->aaaaa());"); 7698 verifyFormat("a->aaaaaa()->aaaaaaaaaaa(aaaaaaaa()->aaaaaa()->aaaaa() ||\n" 7699 " aaaaaaaaa()->aaaaaa()->aaaaa());"); 7700 7701 verifyFormat("aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7702 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 7703 " .a();"); 7704 7705 FormatStyle NoBinPacking = getLLVMStyle(); 7706 NoBinPacking.BinPackParameters = false; 7707 verifyFormat("aaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa)\n" 7708 " .aaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa)\n" 7709 " .aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaa,\n" 7710 " aaaaaaaaaaaaaaaaaaa,\n" 7711 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 7712 NoBinPacking); 7713 7714 // If there is a subsequent call, change to hanging indentation. 7715 verifyFormat( 7716 "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7717 " aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa))\n" 7718 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 7719 verifyFormat( 7720 "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7721 " aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa));"); 7722 verifyFormat("aaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7723 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 7724 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 7725 verifyFormat("aaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7726 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 7727 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa());"); 7728 } 7729 7730 TEST_F(FormatTest, WrapsTemplateDeclarations) { 7731 verifyFormat("template <typename T>\n" 7732 "virtual void loooooooooooongFunction(int Param1, int Param2);"); 7733 verifyFormat("template <typename T>\n" 7734 "// T should be one of {A, B}.\n" 7735 "virtual void loooooooooooongFunction(int Param1, int Param2);"); 7736 verifyFormat( 7737 "template <typename T>\n" 7738 "using comment_to_xml_conversion = comment_to_xml_conversion<T, int>;"); 7739 verifyFormat("template <typename T>\n" 7740 "void f(int Paaaaaaaaaaaaaaaaaaaaaaaaaaaaaaram1,\n" 7741 " int Paaaaaaaaaaaaaaaaaaaaaaaaaaaaaaram2);"); 7742 verifyFormat( 7743 "template <typename T>\n" 7744 "void looooooooooooooooooooongFunction(int Paaaaaaaaaaaaaaaaaaaaram1,\n" 7745 " int Paaaaaaaaaaaaaaaaaaaaram2);"); 7746 verifyFormat( 7747 "template <typename T>\n" 7748 "aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaa,\n" 7749 " aaaaaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaaaaa,\n" 7750 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7751 verifyFormat("template <typename T>\n" 7752 "void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7753 " int aaaaaaaaaaaaaaaaaaaaaa);"); 7754 verifyFormat( 7755 "template <typename T1, typename T2 = char, typename T3 = char,\n" 7756 " typename T4 = char>\n" 7757 "void f();"); 7758 verifyFormat("template <typename aaaaaaaaaaa, typename bbbbbbbbbbbbb,\n" 7759 " template <typename> class cccccccccccccccccccccc,\n" 7760 " typename ddddddddddddd>\n" 7761 "class C {};"); 7762 verifyFormat( 7763 "aaaaaaaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa>(\n" 7764 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7765 7766 verifyFormat("void f() {\n" 7767 " a<aaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaa>(\n" 7768 " a(aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa));\n" 7769 "}"); 7770 7771 verifyFormat("template <typename T> class C {};"); 7772 verifyFormat("template <typename T> void f();"); 7773 verifyFormat("template <typename T> void f() {}"); 7774 verifyFormat( 7775 "aaaaaaaaaaaaa<aaaaaaaaaa, aaaaaaaaaaa,\n" 7776 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7777 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa> *aaaa =\n" 7778 " new aaaaaaaaaaaaa<aaaaaaaaaa, aaaaaaaaaaa,\n" 7779 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7780 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>(\n" 7781 " bbbbbbbbbbbbbbbbbbbbbbbb);", 7782 getLLVMStyleWithColumns(72)); 7783 EXPECT_EQ("static_cast<A< //\n" 7784 " B> *>(\n" 7785 "\n" 7786 ");", 7787 format("static_cast<A<//\n" 7788 " B>*>(\n" 7789 "\n" 7790 " );")); 7791 verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7792 " const typename aaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaa);"); 7793 7794 FormatStyle AlwaysBreak = getLLVMStyle(); 7795 AlwaysBreak.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes; 7796 verifyFormat("template <typename T>\nclass C {};", AlwaysBreak); 7797 verifyFormat("template <typename T>\nvoid f();", AlwaysBreak); 7798 verifyFormat("template <typename T>\nvoid f() {}", AlwaysBreak); 7799 verifyFormat("void aaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7800 " bbbbbbbbbbbbbbbbbbbbbbbbbbbb>(\n" 7801 " ccccccccccccccccccccccccccccccccccccccccccccccc);"); 7802 verifyFormat("template <template <typename> class Fooooooo,\n" 7803 " template <typename> class Baaaaaaar>\n" 7804 "struct C {};", 7805 AlwaysBreak); 7806 verifyFormat("template <typename T> // T can be A, B or C.\n" 7807 "struct C {};", 7808 AlwaysBreak); 7809 verifyFormat("template <enum E> class A {\n" 7810 "public:\n" 7811 " E *f();\n" 7812 "};"); 7813 7814 FormatStyle NeverBreak = getLLVMStyle(); 7815 NeverBreak.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_No; 7816 verifyFormat("template <typename T> class C {};", NeverBreak); 7817 verifyFormat("template <typename T> void f();", NeverBreak); 7818 verifyFormat("template <typename T> void f() {}", NeverBreak); 7819 verifyFormat("template <typename T>\nvoid foo(aaaaaaaaaaaaaaaaaaaaaaaaaa " 7820 "bbbbbbbbbbbbbbbbbbbb) {}", 7821 NeverBreak); 7822 verifyFormat("void aaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7823 " bbbbbbbbbbbbbbbbbbbbbbbbbbbb>(\n" 7824 " ccccccccccccccccccccccccccccccccccccccccccccccc);", 7825 NeverBreak); 7826 verifyFormat("template <template <typename> class Fooooooo,\n" 7827 " template <typename> class Baaaaaaar>\n" 7828 "struct C {};", 7829 NeverBreak); 7830 verifyFormat("template <typename T> // T can be A, B or C.\n" 7831 "struct C {};", 7832 NeverBreak); 7833 verifyFormat("template <enum E> class A {\n" 7834 "public:\n" 7835 " E *f();\n" 7836 "};", 7837 NeverBreak); 7838 NeverBreak.PenaltyBreakTemplateDeclaration = 100; 7839 verifyFormat("template <typename T> void\nfoo(aaaaaaaaaaaaaaaaaaaaaaaaaa " 7840 "bbbbbbbbbbbbbbbbbbbb) {}", 7841 NeverBreak); 7842 } 7843 7844 TEST_F(FormatTest, WrapsTemplateDeclarationsWithComments) { 7845 FormatStyle Style = getGoogleStyle(FormatStyle::LK_Cpp); 7846 Style.ColumnLimit = 60; 7847 EXPECT_EQ("// Baseline - no comments.\n" 7848 "template <\n" 7849 " typename aaaaaaaaaaaaaaaaaaaaaa<bbbbbbbbbbbb>::value>\n" 7850 "void f() {}", 7851 format("// Baseline - no comments.\n" 7852 "template <\n" 7853 " typename aaaaaaaaaaaaaaaaaaaaaa<bbbbbbbbbbbb>::value>\n" 7854 "void f() {}", 7855 Style)); 7856 7857 EXPECT_EQ("template <\n" 7858 " typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing\n" 7859 "void f() {}", 7860 format("template <\n" 7861 " typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing\n" 7862 "void f() {}", 7863 Style)); 7864 7865 EXPECT_EQ( 7866 "template <\n" 7867 " typename aaaaaaaaaa<bbbbbbbbbbbb>::value> /* line */\n" 7868 "void f() {}", 7869 format("template <typename aaaaaaaaaa<bbbbbbbbbbbb>::value> /* line */\n" 7870 "void f() {}", 7871 Style)); 7872 7873 EXPECT_EQ( 7874 "template <\n" 7875 " typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing\n" 7876 " // multiline\n" 7877 "void f() {}", 7878 format("template <\n" 7879 " typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing\n" 7880 " // multiline\n" 7881 "void f() {}", 7882 Style)); 7883 7884 EXPECT_EQ( 7885 "template <typename aaaaaaaaaa<\n" 7886 " bbbbbbbbbbbb>::value> // trailing loooong\n" 7887 "void f() {}", 7888 format( 7889 "template <\n" 7890 " typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing loooong\n" 7891 "void f() {}", 7892 Style)); 7893 } 7894 7895 TEST_F(FormatTest, WrapsTemplateParameters) { 7896 FormatStyle Style = getLLVMStyle(); 7897 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 7898 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None; 7899 verifyFormat( 7900 "template <typename... a> struct q {};\n" 7901 "extern q<aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa,\n" 7902 " aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa>\n" 7903 " y;", 7904 Style); 7905 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 7906 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 7907 verifyFormat( 7908 "template <typename... a> struct r {};\n" 7909 "extern r<aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa,\n" 7910 " aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa>\n" 7911 " y;", 7912 Style); 7913 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 7914 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None; 7915 verifyFormat("template <typename... a> struct s {};\n" 7916 "extern s<\n" 7917 " aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, " 7918 "aaaaaaaaaaaaaaaaaaaaaa,\n" 7919 " aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, " 7920 "aaaaaaaaaaaaaaaaaaaaaa>\n" 7921 " y;", 7922 Style); 7923 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 7924 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 7925 verifyFormat("template <typename... a> struct t {};\n" 7926 "extern t<\n" 7927 " aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, " 7928 "aaaaaaaaaaaaaaaaaaaaaa,\n" 7929 " aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, " 7930 "aaaaaaaaaaaaaaaaaaaaaa>\n" 7931 " y;", 7932 Style); 7933 } 7934 7935 TEST_F(FormatTest, WrapsAtNestedNameSpecifiers) { 7936 verifyFormat( 7937 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n" 7938 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 7939 verifyFormat( 7940 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n" 7941 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7942 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa());"); 7943 7944 // FIXME: Should we have the extra indent after the second break? 7945 verifyFormat( 7946 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n" 7947 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n" 7948 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 7949 7950 verifyFormat( 7951 "aaaaaaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb::\n" 7952 " cccccccccccccccccccccccccccccccccccccccccccccc());"); 7953 7954 // Breaking at nested name specifiers is generally not desirable. 7955 verifyFormat( 7956 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7957 " aaaaaaaaaaaaaaaaaaaaaaa);"); 7958 7959 verifyFormat("aaaaaaaaaaaaaaaaaa(aaaaaaaa,\n" 7960 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n" 7961 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7962 " aaaaaaaaaaaaaaaaaaaaa);", 7963 getLLVMStyleWithColumns(74)); 7964 7965 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n" 7966 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7967 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 7968 } 7969 7970 TEST_F(FormatTest, UnderstandsTemplateParameters) { 7971 verifyFormat("A<int> a;"); 7972 verifyFormat("A<A<A<int>>> a;"); 7973 verifyFormat("A<A<A<int, 2>, 3>, 4> a;"); 7974 verifyFormat("bool x = a < 1 || 2 > a;"); 7975 verifyFormat("bool x = 5 < f<int>();"); 7976 verifyFormat("bool x = f<int>() > 5;"); 7977 verifyFormat("bool x = 5 < a<int>::x;"); 7978 verifyFormat("bool x = a < 4 ? a > 2 : false;"); 7979 verifyFormat("bool x = f() ? a < 2 : a > 2;"); 7980 7981 verifyGoogleFormat("A<A<int>> a;"); 7982 verifyGoogleFormat("A<A<A<int>>> a;"); 7983 verifyGoogleFormat("A<A<A<A<int>>>> a;"); 7984 verifyGoogleFormat("A<A<int> > a;"); 7985 verifyGoogleFormat("A<A<A<int> > > a;"); 7986 verifyGoogleFormat("A<A<A<A<int> > > > a;"); 7987 verifyGoogleFormat("A<::A<int>> a;"); 7988 verifyGoogleFormat("A<::A> a;"); 7989 verifyGoogleFormat("A< ::A> a;"); 7990 verifyGoogleFormat("A< ::A<int> > a;"); 7991 EXPECT_EQ("A<A<A<A>>> a;", format("A<A<A<A> >> a;", getGoogleStyle())); 7992 EXPECT_EQ("A<A<A<A>>> a;", format("A<A<A<A>> > a;", getGoogleStyle())); 7993 EXPECT_EQ("A<::A<int>> a;", format("A< ::A<int>> a;", getGoogleStyle())); 7994 EXPECT_EQ("A<::A<int>> a;", format("A<::A<int> > a;", getGoogleStyle())); 7995 EXPECT_EQ("auto x = [] { A<A<A<A>>> a; };", 7996 format("auto x=[]{A<A<A<A> >> a;};", getGoogleStyle())); 7997 7998 verifyFormat("A<A<int>> a;", getChromiumStyle(FormatStyle::LK_Cpp)); 7999 8000 // template closer followed by a token that starts with > or = 8001 verifyFormat("bool b = a<1> > 1;"); 8002 verifyFormat("bool b = a<1> >= 1;"); 8003 verifyFormat("int i = a<1> >> 1;"); 8004 FormatStyle Style = getLLVMStyle(); 8005 Style.SpaceBeforeAssignmentOperators = false; 8006 verifyFormat("bool b= a<1> == 1;", Style); 8007 verifyFormat("a<int> = 1;", Style); 8008 verifyFormat("a<int> >>= 1;", Style); 8009 8010 verifyFormat("test < a | b >> c;"); 8011 verifyFormat("test<test<a | b>> c;"); 8012 verifyFormat("test >> a >> b;"); 8013 verifyFormat("test << a >> b;"); 8014 8015 verifyFormat("f<int>();"); 8016 verifyFormat("template <typename T> void f() {}"); 8017 verifyFormat("struct A<std::enable_if<sizeof(T2) < sizeof(int32)>::type>;"); 8018 verifyFormat("struct A<std::enable_if<sizeof(T2) ? sizeof(int32) : " 8019 "sizeof(char)>::type>;"); 8020 verifyFormat("template <class T> struct S<std::is_arithmetic<T>{}> {};"); 8021 verifyFormat("f(a.operator()<A>());"); 8022 verifyFormat("f(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8023 " .template operator()<A>());", 8024 getLLVMStyleWithColumns(35)); 8025 8026 // Not template parameters. 8027 verifyFormat("return a < b && c > d;"); 8028 verifyFormat("void f() {\n" 8029 " while (a < b && c > d) {\n" 8030 " }\n" 8031 "}"); 8032 verifyFormat("template <typename... Types>\n" 8033 "typename enable_if<0 < sizeof...(Types)>::type Foo() {}"); 8034 8035 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8036 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaa >> aaaaa);", 8037 getLLVMStyleWithColumns(60)); 8038 verifyFormat("static_assert(is_convertible<A &&, B>::value, \"AAA\");"); 8039 verifyFormat("Constructor(A... a) : a_(X<A>{std::forward<A>(a)}...) {}"); 8040 verifyFormat("< < < < < < < < < < < < < < < < < < < < < < < < < < < < < <"); 8041 verifyFormat("some_templated_type<decltype([](int i) { return i; })>"); 8042 } 8043 8044 TEST_F(FormatTest, UnderstandsShiftOperators) { 8045 verifyFormat("if (i < x >> 1)"); 8046 verifyFormat("while (i < x >> 1)"); 8047 verifyFormat("for (unsigned i = 0; i < i; ++i, v = v >> 1)"); 8048 verifyFormat("for (unsigned i = 0; i < x >> 1; ++i, v = v >> 1)"); 8049 verifyFormat( 8050 "for (std::vector<int>::iterator i = 0; i < x >> 1; ++i, v = v >> 1)"); 8051 verifyFormat("Foo.call<Bar<Function>>()"); 8052 verifyFormat("if (Foo.call<Bar<Function>>() == 0)"); 8053 verifyFormat("for (std::vector<std::pair<int>>::iterator i = 0; i < x >> 1; " 8054 "++i, v = v >> 1)"); 8055 verifyFormat("if (w<u<v<x>>, 1>::t)"); 8056 } 8057 8058 TEST_F(FormatTest, BitshiftOperatorWidth) { 8059 EXPECT_EQ("int a = 1 << 2; /* foo\n" 8060 " bar */", 8061 format("int a=1<<2; /* foo\n" 8062 " bar */")); 8063 8064 EXPECT_EQ("int b = 256 >> 1; /* foo\n" 8065 " bar */", 8066 format("int b =256>>1 ; /* foo\n" 8067 " bar */")); 8068 } 8069 8070 TEST_F(FormatTest, UnderstandsBinaryOperators) { 8071 verifyFormat("COMPARE(a, ==, b);"); 8072 verifyFormat("auto s = sizeof...(Ts) - 1;"); 8073 } 8074 8075 TEST_F(FormatTest, UnderstandsPointersToMembers) { 8076 verifyFormat("int A::*x;"); 8077 verifyFormat("int (S::*func)(void *);"); 8078 verifyFormat("void f() { int (S::*func)(void *); }"); 8079 verifyFormat("typedef bool *(Class::*Member)() const;"); 8080 verifyFormat("void f() {\n" 8081 " (a->*f)();\n" 8082 " a->*x;\n" 8083 " (a.*f)();\n" 8084 " ((*a).*f)();\n" 8085 " a.*x;\n" 8086 "}"); 8087 verifyFormat("void f() {\n" 8088 " (a->*aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)(\n" 8089 " aaaa, bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb);\n" 8090 "}"); 8091 verifyFormat( 8092 "(aaaaaaaaaa->*bbbbbbb)(\n" 8093 " aaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa));"); 8094 FormatStyle Style = getLLVMStyle(); 8095 Style.PointerAlignment = FormatStyle::PAS_Left; 8096 verifyFormat("typedef bool* (Class::*Member)() const;", Style); 8097 } 8098 8099 TEST_F(FormatTest, UnderstandsUnaryOperators) { 8100 verifyFormat("int a = -2;"); 8101 verifyFormat("f(-1, -2, -3);"); 8102 verifyFormat("a[-1] = 5;"); 8103 verifyFormat("int a = 5 + -2;"); 8104 verifyFormat("if (i == -1) {\n}"); 8105 verifyFormat("if (i != -1) {\n}"); 8106 verifyFormat("if (i > -1) {\n}"); 8107 verifyFormat("if (i < -1) {\n}"); 8108 verifyFormat("++(a->f());"); 8109 verifyFormat("--(a->f());"); 8110 verifyFormat("(a->f())++;"); 8111 verifyFormat("a[42]++;"); 8112 verifyFormat("if (!(a->f())) {\n}"); 8113 verifyFormat("if (!+i) {\n}"); 8114 verifyFormat("~&a;"); 8115 8116 verifyFormat("a-- > b;"); 8117 verifyFormat("b ? -a : c;"); 8118 verifyFormat("n * sizeof char16;"); 8119 verifyFormat("n * alignof char16;", getGoogleStyle()); 8120 verifyFormat("sizeof(char);"); 8121 verifyFormat("alignof(char);", getGoogleStyle()); 8122 8123 verifyFormat("return -1;"); 8124 verifyFormat("throw -1;"); 8125 verifyFormat("switch (a) {\n" 8126 "case -1:\n" 8127 " break;\n" 8128 "}"); 8129 verifyFormat("#define X -1"); 8130 verifyFormat("#define X -kConstant"); 8131 8132 verifyFormat("const NSPoint kBrowserFrameViewPatternOffset = {-5, +3};"); 8133 verifyFormat("const NSPoint kBrowserFrameViewPatternOffset = {+5, -3};"); 8134 8135 verifyFormat("int a = /* confusing comment */ -1;"); 8136 // FIXME: The space after 'i' is wrong, but hopefully, this is a rare case. 8137 verifyFormat("int a = i /* confusing comment */++;"); 8138 8139 verifyFormat("co_yield -1;"); 8140 verifyFormat("co_return -1;"); 8141 8142 // Check that * is not treated as a binary operator when we set 8143 // PointerAlignment as PAS_Left after a keyword and not a declaration. 8144 FormatStyle PASLeftStyle = getLLVMStyle(); 8145 PASLeftStyle.PointerAlignment = FormatStyle::PAS_Left; 8146 verifyFormat("co_return *a;", PASLeftStyle); 8147 verifyFormat("co_await *a;", PASLeftStyle); 8148 verifyFormat("co_yield *a", PASLeftStyle); 8149 verifyFormat("return *a;", PASLeftStyle); 8150 } 8151 8152 TEST_F(FormatTest, DoesNotIndentRelativeToUnaryOperators) { 8153 verifyFormat("if (!aaaaaaaaaa( // break\n" 8154 " aaaaa)) {\n" 8155 "}"); 8156 verifyFormat("aaaaaaaaaa(!aaaaaaaaaa( // break\n" 8157 " aaaaa));"); 8158 verifyFormat("*aaa = aaaaaaa( // break\n" 8159 " bbbbbb);"); 8160 } 8161 8162 TEST_F(FormatTest, UnderstandsOverloadedOperators) { 8163 verifyFormat("bool operator<();"); 8164 verifyFormat("bool operator>();"); 8165 verifyFormat("bool operator=();"); 8166 verifyFormat("bool operator==();"); 8167 verifyFormat("bool operator!=();"); 8168 verifyFormat("int operator+();"); 8169 verifyFormat("int operator++();"); 8170 verifyFormat("int operator++(int) volatile noexcept;"); 8171 verifyFormat("bool operator,();"); 8172 verifyFormat("bool operator();"); 8173 verifyFormat("bool operator()();"); 8174 verifyFormat("bool operator[]();"); 8175 verifyFormat("operator bool();"); 8176 verifyFormat("operator int();"); 8177 verifyFormat("operator void *();"); 8178 verifyFormat("operator SomeType<int>();"); 8179 verifyFormat("operator SomeType<int, int>();"); 8180 verifyFormat("operator SomeType<SomeType<int>>();"); 8181 verifyFormat("void *operator new(std::size_t size);"); 8182 verifyFormat("void *operator new[](std::size_t size);"); 8183 verifyFormat("void operator delete(void *ptr);"); 8184 verifyFormat("void operator delete[](void *ptr);"); 8185 verifyFormat("template <typename AAAAAAA, typename BBBBBBB>\n" 8186 "AAAAAAA operator/(const AAAAAAA &a, BBBBBBB &b);"); 8187 verifyFormat("aaaaaaaaaaaaaaaaaaaaaa operator,(\n" 8188 " aaaaaaaaaaaaaaaaaaaaa &aaaaaaaaaaaaaaaaaaaaaaaaaa) const;"); 8189 8190 verifyFormat( 8191 "ostream &operator<<(ostream &OutputStream,\n" 8192 " SomeReallyLongType WithSomeReallyLongValue);"); 8193 verifyFormat("bool operator<(const aaaaaaaaaaaaaaaaaaaaa &left,\n" 8194 " const aaaaaaaaaaaaaaaaaaaaa &right) {\n" 8195 " return left.group < right.group;\n" 8196 "}"); 8197 verifyFormat("SomeType &operator=(const SomeType &S);"); 8198 verifyFormat("f.template operator()<int>();"); 8199 8200 verifyGoogleFormat("operator void*();"); 8201 verifyGoogleFormat("operator SomeType<SomeType<int>>();"); 8202 verifyGoogleFormat("operator ::A();"); 8203 8204 verifyFormat("using A::operator+;"); 8205 verifyFormat("inline A operator^(const A &lhs, const A &rhs) {}\n" 8206 "int i;"); 8207 } 8208 8209 TEST_F(FormatTest, UnderstandsFunctionRefQualification) { 8210 verifyFormat("Deleted &operator=(const Deleted &) & = default;"); 8211 verifyFormat("Deleted &operator=(const Deleted &) && = delete;"); 8212 verifyFormat("SomeType MemberFunction(const Deleted &) & = delete;"); 8213 verifyFormat("SomeType MemberFunction(const Deleted &) && = delete;"); 8214 verifyFormat("Deleted &operator=(const Deleted &) &;"); 8215 verifyFormat("Deleted &operator=(const Deleted &) &&;"); 8216 verifyFormat("SomeType MemberFunction(const Deleted &) &;"); 8217 verifyFormat("SomeType MemberFunction(const Deleted &) &&;"); 8218 verifyFormat("SomeType MemberFunction(const Deleted &) && {}"); 8219 verifyFormat("SomeType MemberFunction(const Deleted &) && final {}"); 8220 verifyFormat("SomeType MemberFunction(const Deleted &) && override {}"); 8221 verifyFormat("void Fn(T const &) const &;"); 8222 verifyFormat("void Fn(T const volatile &&) const volatile &&;"); 8223 verifyFormat("template <typename T>\n" 8224 "void F(T) && = delete;", 8225 getGoogleStyle()); 8226 8227 FormatStyle AlignLeft = getLLVMStyle(); 8228 AlignLeft.PointerAlignment = FormatStyle::PAS_Left; 8229 verifyFormat("void A::b() && {}", AlignLeft); 8230 verifyFormat("Deleted& operator=(const Deleted&) & = default;", AlignLeft); 8231 verifyFormat("SomeType MemberFunction(const Deleted&) & = delete;", 8232 AlignLeft); 8233 verifyFormat("Deleted& operator=(const Deleted&) &;", AlignLeft); 8234 verifyFormat("SomeType MemberFunction(const Deleted&) &;", AlignLeft); 8235 verifyFormat("auto Function(T t) & -> void {}", AlignLeft); 8236 verifyFormat("auto Function(T... t) & -> void {}", AlignLeft); 8237 verifyFormat("auto Function(T) & -> void {}", AlignLeft); 8238 verifyFormat("auto Function(T) & -> void;", AlignLeft); 8239 verifyFormat("void Fn(T const&) const&;", AlignLeft); 8240 verifyFormat("void Fn(T const volatile&&) const volatile&&;", AlignLeft); 8241 8242 FormatStyle Spaces = getLLVMStyle(); 8243 Spaces.SpacesInCStyleCastParentheses = true; 8244 verifyFormat("Deleted &operator=(const Deleted &) & = default;", Spaces); 8245 verifyFormat("SomeType MemberFunction(const Deleted &) & = delete;", Spaces); 8246 verifyFormat("Deleted &operator=(const Deleted &) &;", Spaces); 8247 verifyFormat("SomeType MemberFunction(const Deleted &) &;", Spaces); 8248 8249 Spaces.SpacesInCStyleCastParentheses = false; 8250 Spaces.SpacesInParentheses = true; 8251 verifyFormat("Deleted &operator=( const Deleted & ) & = default;", Spaces); 8252 verifyFormat("SomeType MemberFunction( const Deleted & ) & = delete;", 8253 Spaces); 8254 verifyFormat("Deleted &operator=( const Deleted & ) &;", Spaces); 8255 verifyFormat("SomeType MemberFunction( const Deleted & ) &;", Spaces); 8256 8257 FormatStyle BreakTemplate = getLLVMStyle(); 8258 BreakTemplate.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes; 8259 8260 verifyFormat("struct f {\n" 8261 " template <class T>\n" 8262 " int &foo(const std::string &str) &noexcept {}\n" 8263 "};", 8264 BreakTemplate); 8265 8266 verifyFormat("struct f {\n" 8267 " template <class T>\n" 8268 " int &foo(const std::string &str) &&noexcept {}\n" 8269 "};", 8270 BreakTemplate); 8271 8272 verifyFormat("struct f {\n" 8273 " template <class T>\n" 8274 " int &foo(const std::string &str) const &noexcept {}\n" 8275 "};", 8276 BreakTemplate); 8277 8278 verifyFormat("struct f {\n" 8279 " template <class T>\n" 8280 " int &foo(const std::string &str) const &noexcept {}\n" 8281 "};", 8282 BreakTemplate); 8283 8284 verifyFormat("struct f {\n" 8285 " template <class T>\n" 8286 " auto foo(const std::string &str) &&noexcept -> int & {}\n" 8287 "};", 8288 BreakTemplate); 8289 8290 FormatStyle AlignLeftBreakTemplate = getLLVMStyle(); 8291 AlignLeftBreakTemplate.AlwaysBreakTemplateDeclarations = 8292 FormatStyle::BTDS_Yes; 8293 AlignLeftBreakTemplate.PointerAlignment = FormatStyle::PAS_Left; 8294 8295 verifyFormat("struct f {\n" 8296 " template <class T>\n" 8297 " int& foo(const std::string& str) & noexcept {}\n" 8298 "};", 8299 AlignLeftBreakTemplate); 8300 8301 verifyFormat("struct f {\n" 8302 " template <class T>\n" 8303 " int& foo(const std::string& str) && noexcept {}\n" 8304 "};", 8305 AlignLeftBreakTemplate); 8306 8307 verifyFormat("struct f {\n" 8308 " template <class T>\n" 8309 " int& foo(const std::string& str) const& noexcept {}\n" 8310 "};", 8311 AlignLeftBreakTemplate); 8312 8313 verifyFormat("struct f {\n" 8314 " template <class T>\n" 8315 " int& foo(const std::string& str) const&& noexcept {}\n" 8316 "};", 8317 AlignLeftBreakTemplate); 8318 8319 verifyFormat("struct f {\n" 8320 " template <class T>\n" 8321 " auto foo(const std::string& str) && noexcept -> int& {}\n" 8322 "};", 8323 AlignLeftBreakTemplate); 8324 8325 // The `&` in `Type&` should not be confused with a trailing `&` of 8326 // DEPRECATED(reason) member function. 8327 verifyFormat("struct f {\n" 8328 " template <class T>\n" 8329 " DEPRECATED(reason)\n" 8330 " Type &foo(arguments) {}\n" 8331 "};", 8332 BreakTemplate); 8333 8334 verifyFormat("struct f {\n" 8335 " template <class T>\n" 8336 " DEPRECATED(reason)\n" 8337 " Type& foo(arguments) {}\n" 8338 "};", 8339 AlignLeftBreakTemplate); 8340 8341 verifyFormat("void (*foopt)(int) = &func;"); 8342 } 8343 8344 TEST_F(FormatTest, UnderstandsNewAndDelete) { 8345 verifyFormat("void f() {\n" 8346 " A *a = new A;\n" 8347 " A *a = new (placement) A;\n" 8348 " delete a;\n" 8349 " delete (A *)a;\n" 8350 "}"); 8351 verifyFormat("new (aaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaa))\n" 8352 " typename aaaaaaaaaaaaaaaaaaaaaaaa();"); 8353 verifyFormat("auto aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n" 8354 " new (aaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaa))\n" 8355 " typename aaaaaaaaaaaaaaaaaaaaaaaa();"); 8356 verifyFormat("delete[] h->p;"); 8357 } 8358 8359 TEST_F(FormatTest, UnderstandsUsesOfStarAndAmp) { 8360 verifyFormat("int *f(int *a) {}"); 8361 verifyFormat("int main(int argc, char **argv) {}"); 8362 verifyFormat("Test::Test(int b) : a(b * b) {}"); 8363 verifyIndependentOfContext("f(a, *a);"); 8364 verifyFormat("void g() { f(*a); }"); 8365 verifyIndependentOfContext("int a = b * 10;"); 8366 verifyIndependentOfContext("int a = 10 * b;"); 8367 verifyIndependentOfContext("int a = b * c;"); 8368 verifyIndependentOfContext("int a += b * c;"); 8369 verifyIndependentOfContext("int a -= b * c;"); 8370 verifyIndependentOfContext("int a *= b * c;"); 8371 verifyIndependentOfContext("int a /= b * c;"); 8372 verifyIndependentOfContext("int a = *b;"); 8373 verifyIndependentOfContext("int a = *b * c;"); 8374 verifyIndependentOfContext("int a = b * *c;"); 8375 verifyIndependentOfContext("int a = b * (10);"); 8376 verifyIndependentOfContext("S << b * (10);"); 8377 verifyIndependentOfContext("return 10 * b;"); 8378 verifyIndependentOfContext("return *b * *c;"); 8379 verifyIndependentOfContext("return a & ~b;"); 8380 verifyIndependentOfContext("f(b ? *c : *d);"); 8381 verifyIndependentOfContext("int a = b ? *c : *d;"); 8382 verifyIndependentOfContext("*b = a;"); 8383 verifyIndependentOfContext("a * ~b;"); 8384 verifyIndependentOfContext("a * !b;"); 8385 verifyIndependentOfContext("a * +b;"); 8386 verifyIndependentOfContext("a * -b;"); 8387 verifyIndependentOfContext("a * ++b;"); 8388 verifyIndependentOfContext("a * --b;"); 8389 verifyIndependentOfContext("a[4] * b;"); 8390 verifyIndependentOfContext("a[a * a] = 1;"); 8391 verifyIndependentOfContext("f() * b;"); 8392 verifyIndependentOfContext("a * [self dostuff];"); 8393 verifyIndependentOfContext("int x = a * (a + b);"); 8394 verifyIndependentOfContext("(a *)(a + b);"); 8395 verifyIndependentOfContext("*(int *)(p & ~3UL) = 0;"); 8396 verifyIndependentOfContext("int *pa = (int *)&a;"); 8397 verifyIndependentOfContext("return sizeof(int **);"); 8398 verifyIndependentOfContext("return sizeof(int ******);"); 8399 verifyIndependentOfContext("return (int **&)a;"); 8400 verifyIndependentOfContext("f((*PointerToArray)[10]);"); 8401 verifyFormat("void f(Type (*parameter)[10]) {}"); 8402 verifyFormat("void f(Type (¶meter)[10]) {}"); 8403 verifyGoogleFormat("return sizeof(int**);"); 8404 verifyIndependentOfContext("Type **A = static_cast<Type **>(P);"); 8405 verifyGoogleFormat("Type** A = static_cast<Type**>(P);"); 8406 verifyFormat("auto a = [](int **&, int ***) {};"); 8407 verifyFormat("auto PointerBinding = [](const char *S) {};"); 8408 verifyFormat("typedef typeof(int(int, int)) *MyFunc;"); 8409 verifyFormat("[](const decltype(*a) &value) {}"); 8410 verifyFormat("[](const typeof(*a) &value) {}"); 8411 verifyFormat("[](const _Atomic(a *) &value) {}"); 8412 verifyFormat("[](const __underlying_type(a) &value) {}"); 8413 verifyFormat("decltype(a * b) F();"); 8414 verifyFormat("typeof(a * b) F();"); 8415 verifyFormat("#define MACRO() [](A *a) { return 1; }"); 8416 verifyFormat("Constructor() : member([](A *a, B *b) {}) {}"); 8417 verifyIndependentOfContext("typedef void (*f)(int *a);"); 8418 verifyIndependentOfContext("int i{a * b};"); 8419 verifyIndependentOfContext("aaa && aaa->f();"); 8420 verifyIndependentOfContext("int x = ~*p;"); 8421 verifyFormat("Constructor() : a(a), area(width * height) {}"); 8422 verifyFormat("Constructor() : a(a), area(a, width * height) {}"); 8423 verifyGoogleFormat("MACRO Constructor(const int& i) : a(a), b(b) {}"); 8424 verifyFormat("void f() { f(a, c * d); }"); 8425 verifyFormat("void f() { f(new a(), c * d); }"); 8426 verifyFormat("void f(const MyOverride &override);"); 8427 verifyFormat("void f(const MyFinal &final);"); 8428 verifyIndependentOfContext("bool a = f() && override.f();"); 8429 verifyIndependentOfContext("bool a = f() && final.f();"); 8430 8431 verifyIndependentOfContext("InvalidRegions[*R] = 0;"); 8432 8433 verifyIndependentOfContext("A<int *> a;"); 8434 verifyIndependentOfContext("A<int **> a;"); 8435 verifyIndependentOfContext("A<int *, int *> a;"); 8436 verifyIndependentOfContext("A<int *[]> a;"); 8437 verifyIndependentOfContext( 8438 "const char *const p = reinterpret_cast<const char *const>(q);"); 8439 verifyIndependentOfContext("A<int **, int **> a;"); 8440 verifyIndependentOfContext("void f(int *a = d * e, int *b = c * d);"); 8441 verifyFormat("for (char **a = b; *a; ++a) {\n}"); 8442 verifyFormat("for (; a && b;) {\n}"); 8443 verifyFormat("bool foo = true && [] { return false; }();"); 8444 8445 verifyFormat( 8446 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8447 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa, *aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 8448 8449 verifyGoogleFormat("int const* a = &b;"); 8450 verifyGoogleFormat("**outparam = 1;"); 8451 verifyGoogleFormat("*outparam = a * b;"); 8452 verifyGoogleFormat("int main(int argc, char** argv) {}"); 8453 verifyGoogleFormat("A<int*> a;"); 8454 verifyGoogleFormat("A<int**> a;"); 8455 verifyGoogleFormat("A<int*, int*> a;"); 8456 verifyGoogleFormat("A<int**, int**> a;"); 8457 verifyGoogleFormat("f(b ? *c : *d);"); 8458 verifyGoogleFormat("int a = b ? *c : *d;"); 8459 verifyGoogleFormat("Type* t = **x;"); 8460 verifyGoogleFormat("Type* t = *++*x;"); 8461 verifyGoogleFormat("*++*x;"); 8462 verifyGoogleFormat("Type* t = const_cast<T*>(&*x);"); 8463 verifyGoogleFormat("Type* t = x++ * y;"); 8464 verifyGoogleFormat( 8465 "const char* const p = reinterpret_cast<const char* const>(q);"); 8466 verifyGoogleFormat("void f(int i = 0, SomeType** temps = NULL);"); 8467 verifyGoogleFormat("void f(Bar* a = nullptr, Bar* b);"); 8468 verifyGoogleFormat("template <typename T>\n" 8469 "void f(int i = 0, SomeType** temps = NULL);"); 8470 8471 FormatStyle Left = getLLVMStyle(); 8472 Left.PointerAlignment = FormatStyle::PAS_Left; 8473 verifyFormat("x = *a(x) = *a(y);", Left); 8474 verifyFormat("for (;; *a = b) {\n}", Left); 8475 verifyFormat("return *this += 1;", Left); 8476 verifyFormat("throw *x;", Left); 8477 verifyFormat("delete *x;", Left); 8478 verifyFormat("typedef typeof(int(int, int))* MyFuncPtr;", Left); 8479 verifyFormat("[](const decltype(*a)* ptr) {}", Left); 8480 verifyFormat("[](const typeof(*a)* ptr) {}", Left); 8481 verifyFormat("[](const _Atomic(a*)* ptr) {}", Left); 8482 verifyFormat("[](const __underlying_type(a)* ptr) {}", Left); 8483 verifyFormat("typedef typeof /*comment*/ (int(int, int))* MyFuncPtr;", Left); 8484 verifyFormat("auto x(A&&, B&&, C&&) -> D;", Left); 8485 verifyFormat("auto x = [](A&&, B&&, C&&) -> D {};", Left); 8486 verifyFormat("template <class T> X(T&&, T&&, T&&) -> X<T>;", Left); 8487 8488 verifyIndependentOfContext("a = *(x + y);"); 8489 verifyIndependentOfContext("a = &(x + y);"); 8490 verifyIndependentOfContext("*(x + y).call();"); 8491 verifyIndependentOfContext("&(x + y)->call();"); 8492 verifyFormat("void f() { &(*I).first; }"); 8493 8494 verifyIndependentOfContext("f(b * /* confusing comment */ ++c);"); 8495 verifyFormat( 8496 "int *MyValues = {\n" 8497 " *A, // Operator detection might be confused by the '{'\n" 8498 " *BB // Operator detection might be confused by previous comment\n" 8499 "};"); 8500 8501 verifyIndependentOfContext("if (int *a = &b)"); 8502 verifyIndependentOfContext("if (int &a = *b)"); 8503 verifyIndependentOfContext("if (a & b[i])"); 8504 verifyIndependentOfContext("if constexpr (a & b[i])"); 8505 verifyIndependentOfContext("if CONSTEXPR (a & b[i])"); 8506 verifyIndependentOfContext("if (a * (b * c))"); 8507 verifyIndependentOfContext("if constexpr (a * (b * c))"); 8508 verifyIndependentOfContext("if CONSTEXPR (a * (b * c))"); 8509 verifyIndependentOfContext("if (a::b::c::d & b[i])"); 8510 verifyIndependentOfContext("if (*b[i])"); 8511 verifyIndependentOfContext("if (int *a = (&b))"); 8512 verifyIndependentOfContext("while (int *a = &b)"); 8513 verifyIndependentOfContext("while (a * (b * c))"); 8514 verifyIndependentOfContext("size = sizeof *a;"); 8515 verifyIndependentOfContext("if (a && (b = c))"); 8516 verifyFormat("void f() {\n" 8517 " for (const int &v : Values) {\n" 8518 " }\n" 8519 "}"); 8520 verifyFormat("for (int i = a * a; i < 10; ++i) {\n}"); 8521 verifyFormat("for (int i = 0; i < a * a; ++i) {\n}"); 8522 verifyGoogleFormat("for (int i = 0; i * 2 < z; i *= 2) {\n}"); 8523 8524 verifyFormat("#define A (!a * b)"); 8525 verifyFormat("#define MACRO \\\n" 8526 " int *i = a * b; \\\n" 8527 " void f(a *b);", 8528 getLLVMStyleWithColumns(19)); 8529 8530 verifyIndependentOfContext("A = new SomeType *[Length];"); 8531 verifyIndependentOfContext("A = new SomeType *[Length]();"); 8532 verifyIndependentOfContext("T **t = new T *;"); 8533 verifyIndependentOfContext("T **t = new T *();"); 8534 verifyGoogleFormat("A = new SomeType*[Length]();"); 8535 verifyGoogleFormat("A = new SomeType*[Length];"); 8536 verifyGoogleFormat("T** t = new T*;"); 8537 verifyGoogleFormat("T** t = new T*();"); 8538 8539 verifyFormat("STATIC_ASSERT((a & b) == 0);"); 8540 verifyFormat("STATIC_ASSERT(0 == (a & b));"); 8541 verifyFormat("template <bool a, bool b> " 8542 "typename t::if<x && y>::type f() {}"); 8543 verifyFormat("template <int *y> f() {}"); 8544 verifyFormat("vector<int *> v;"); 8545 verifyFormat("vector<int *const> v;"); 8546 verifyFormat("vector<int *const **const *> v;"); 8547 verifyFormat("vector<int *volatile> v;"); 8548 verifyFormat("vector<a *_Nonnull> v;"); 8549 verifyFormat("vector<a *_Nullable> v;"); 8550 verifyFormat("vector<a *_Null_unspecified> v;"); 8551 verifyFormat("vector<a *__ptr32> v;"); 8552 verifyFormat("vector<a *__ptr64> v;"); 8553 verifyFormat("vector<a *__capability> v;"); 8554 FormatStyle TypeMacros = getLLVMStyle(); 8555 TypeMacros.TypenameMacros = {"LIST"}; 8556 verifyFormat("vector<LIST(uint64_t)> v;", TypeMacros); 8557 verifyFormat("vector<LIST(uint64_t) *> v;", TypeMacros); 8558 verifyFormat("vector<LIST(uint64_t) **> v;", TypeMacros); 8559 verifyFormat("vector<LIST(uint64_t) *attr> v;", TypeMacros); 8560 verifyFormat("vector<A(uint64_t) * attr> v;", TypeMacros); // multiplication 8561 8562 FormatStyle CustomQualifier = getLLVMStyle(); 8563 // Add indentifers that should not be parsed as a qualifier by default. 8564 CustomQualifier.AttributeMacros.push_back("__my_qualifier"); 8565 CustomQualifier.AttributeMacros.push_back("_My_qualifier"); 8566 CustomQualifier.AttributeMacros.push_back("my_other_qualifier"); 8567 verifyFormat("vector<a * __my_qualifier> parse_as_multiply;"); 8568 verifyFormat("vector<a *__my_qualifier> v;", CustomQualifier); 8569 verifyFormat("vector<a * _My_qualifier> parse_as_multiply;"); 8570 verifyFormat("vector<a *_My_qualifier> v;", CustomQualifier); 8571 verifyFormat("vector<a * my_other_qualifier> parse_as_multiply;"); 8572 verifyFormat("vector<a *my_other_qualifier> v;", CustomQualifier); 8573 verifyFormat("vector<a * _NotAQualifier> v;"); 8574 verifyFormat("vector<a * __not_a_qualifier> v;"); 8575 verifyFormat("vector<a * b> v;"); 8576 verifyFormat("foo<b && false>();"); 8577 verifyFormat("foo<b & 1>();"); 8578 verifyFormat("decltype(*::std::declval<const T &>()) void F();"); 8579 verifyFormat("typeof(*::std::declval<const T &>()) void F();"); 8580 verifyFormat("_Atomic(*::std::declval<const T &>()) void F();"); 8581 verifyFormat("__underlying_type(*::std::declval<const T &>()) void F();"); 8582 verifyFormat( 8583 "template <class T, class = typename std::enable_if<\n" 8584 " std::is_integral<T>::value &&\n" 8585 " (sizeof(T) > 1 || sizeof(T) < 8)>::type>\n" 8586 "void F();", 8587 getLLVMStyleWithColumns(70)); 8588 verifyFormat("template <class T,\n" 8589 " class = typename std::enable_if<\n" 8590 " std::is_integral<T>::value &&\n" 8591 " (sizeof(T) > 1 || sizeof(T) < 8)>::type,\n" 8592 " class U>\n" 8593 "void F();", 8594 getLLVMStyleWithColumns(70)); 8595 verifyFormat( 8596 "template <class T,\n" 8597 " class = typename ::std::enable_if<\n" 8598 " ::std::is_array<T>{} && ::std::is_array<T>{}>::type>\n" 8599 "void F();", 8600 getGoogleStyleWithColumns(68)); 8601 8602 verifyIndependentOfContext("MACRO(int *i);"); 8603 verifyIndependentOfContext("MACRO(auto *a);"); 8604 verifyIndependentOfContext("MACRO(const A *a);"); 8605 verifyIndependentOfContext("MACRO(_Atomic(A) *a);"); 8606 verifyIndependentOfContext("MACRO(decltype(A) *a);"); 8607 verifyIndependentOfContext("MACRO(typeof(A) *a);"); 8608 verifyIndependentOfContext("MACRO(__underlying_type(A) *a);"); 8609 verifyIndependentOfContext("MACRO(A *const a);"); 8610 verifyIndependentOfContext("MACRO(A *restrict a);"); 8611 verifyIndependentOfContext("MACRO(A *__restrict__ a);"); 8612 verifyIndependentOfContext("MACRO(A *__restrict a);"); 8613 verifyIndependentOfContext("MACRO(A *volatile a);"); 8614 verifyIndependentOfContext("MACRO(A *__volatile a);"); 8615 verifyIndependentOfContext("MACRO(A *__volatile__ a);"); 8616 verifyIndependentOfContext("MACRO(A *_Nonnull a);"); 8617 verifyIndependentOfContext("MACRO(A *_Nullable a);"); 8618 verifyIndependentOfContext("MACRO(A *_Null_unspecified a);"); 8619 verifyIndependentOfContext("MACRO(A *__attribute__((foo)) a);"); 8620 verifyIndependentOfContext("MACRO(A *__attribute((foo)) a);"); 8621 verifyIndependentOfContext("MACRO(A *[[clang::attr]] a);"); 8622 verifyIndependentOfContext("MACRO(A *[[clang::attr(\"foo\")]] a);"); 8623 verifyIndependentOfContext("MACRO(A *__ptr32 a);"); 8624 verifyIndependentOfContext("MACRO(A *__ptr64 a);"); 8625 verifyIndependentOfContext("MACRO(A *__capability);"); 8626 verifyIndependentOfContext("MACRO(A &__capability);"); 8627 verifyFormat("MACRO(A *__my_qualifier);"); // type declaration 8628 verifyFormat("void f() { MACRO(A * __my_qualifier); }"); // multiplication 8629 // If we add __my_qualifier to AttributeMacros it should always be parsed as 8630 // a type declaration: 8631 verifyFormat("MACRO(A *__my_qualifier);", CustomQualifier); 8632 verifyFormat("void f() { MACRO(A *__my_qualifier); }", CustomQualifier); 8633 // Also check that TypenameMacros prevents parsing it as multiplication: 8634 verifyIndependentOfContext("MACRO(LIST(uint64_t) * a);"); // multiplication 8635 verifyIndependentOfContext("MACRO(LIST(uint64_t) *a);", TypeMacros); // type 8636 8637 verifyIndependentOfContext("MACRO('0' <= c && c <= '9');"); 8638 verifyFormat("void f() { f(float{1}, a * a); }"); 8639 // FIXME: Is there a way to make this work? 8640 // verifyIndependentOfContext("MACRO(A *a);"); 8641 verifyFormat("MACRO(A &B);"); 8642 verifyFormat("MACRO(A *B);"); 8643 verifyFormat("void f() { MACRO(A * B); }"); 8644 verifyFormat("void f() { MACRO(A & B); }"); 8645 8646 // This lambda was mis-formatted after D88956 (treating it as a binop): 8647 verifyFormat("auto x = [](const decltype(x) &ptr) {};"); 8648 verifyFormat("auto x = [](const decltype(x) *ptr) {};"); 8649 verifyFormat("#define lambda [](const decltype(x) &ptr) {}"); 8650 verifyFormat("#define lambda [](const decltype(x) *ptr) {}"); 8651 8652 verifyFormat("DatumHandle const *operator->() const { return input_; }"); 8653 verifyFormat("return options != nullptr && operator==(*options);"); 8654 8655 EXPECT_EQ("#define OP(x) \\\n" 8656 " ostream &operator<<(ostream &s, const A &a) { \\\n" 8657 " return s << a.DebugString(); \\\n" 8658 " }", 8659 format("#define OP(x) \\\n" 8660 " ostream &operator<<(ostream &s, const A &a) { \\\n" 8661 " return s << a.DebugString(); \\\n" 8662 " }", 8663 getLLVMStyleWithColumns(50))); 8664 8665 // FIXME: We cannot handle this case yet; we might be able to figure out that 8666 // foo<x> d > v; doesn't make sense. 8667 verifyFormat("foo<a<b && c> d> v;"); 8668 8669 FormatStyle PointerMiddle = getLLVMStyle(); 8670 PointerMiddle.PointerAlignment = FormatStyle::PAS_Middle; 8671 verifyFormat("delete *x;", PointerMiddle); 8672 verifyFormat("int * x;", PointerMiddle); 8673 verifyFormat("int *[] x;", PointerMiddle); 8674 verifyFormat("template <int * y> f() {}", PointerMiddle); 8675 verifyFormat("int * f(int * a) {}", PointerMiddle); 8676 verifyFormat("int main(int argc, char ** argv) {}", PointerMiddle); 8677 verifyFormat("Test::Test(int b) : a(b * b) {}", PointerMiddle); 8678 verifyFormat("A<int *> a;", PointerMiddle); 8679 verifyFormat("A<int **> a;", PointerMiddle); 8680 verifyFormat("A<int *, int *> a;", PointerMiddle); 8681 verifyFormat("A<int *[]> a;", PointerMiddle); 8682 verifyFormat("A = new SomeType *[Length]();", PointerMiddle); 8683 verifyFormat("A = new SomeType *[Length];", PointerMiddle); 8684 verifyFormat("T ** t = new T *;", PointerMiddle); 8685 8686 // Member function reference qualifiers aren't binary operators. 8687 verifyFormat("string // break\n" 8688 "operator()() & {}"); 8689 verifyFormat("string // break\n" 8690 "operator()() && {}"); 8691 verifyGoogleFormat("template <typename T>\n" 8692 "auto x() & -> int {}"); 8693 } 8694 8695 TEST_F(FormatTest, UnderstandsAttributes) { 8696 verifyFormat("SomeType s __attribute__((unused)) (InitValue);"); 8697 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa __attribute__((unused))\n" 8698 "aaaaaaaaaaaaaaaaaaaaaaa(int i);"); 8699 FormatStyle AfterType = getLLVMStyle(); 8700 AfterType.AlwaysBreakAfterReturnType = FormatStyle::RTBS_All; 8701 verifyFormat("__attribute__((nodebug)) void\n" 8702 "foo() {}\n", 8703 AfterType); 8704 verifyFormat("__unused void\n" 8705 "foo() {}", 8706 AfterType); 8707 8708 FormatStyle CustomAttrs = getLLVMStyle(); 8709 CustomAttrs.AttributeMacros.push_back("__unused"); 8710 CustomAttrs.AttributeMacros.push_back("__attr1"); 8711 CustomAttrs.AttributeMacros.push_back("__attr2"); 8712 CustomAttrs.AttributeMacros.push_back("no_underscore_attr"); 8713 verifyFormat("vector<SomeType *__attribute((foo))> v;"); 8714 verifyFormat("vector<SomeType *__attribute__((foo))> v;"); 8715 verifyFormat("vector<SomeType * __not_attribute__((foo))> v;"); 8716 // Check that it is parsed as a multiplication without AttributeMacros and 8717 // as a pointer qualifier when we add __attr1/__attr2 to AttributeMacros. 8718 verifyFormat("vector<SomeType * __attr1> v;"); 8719 verifyFormat("vector<SomeType __attr1 *> v;"); 8720 verifyFormat("vector<SomeType __attr1 *const> v;"); 8721 verifyFormat("vector<SomeType __attr1 * __attr2> v;"); 8722 verifyFormat("vector<SomeType *__attr1> v;", CustomAttrs); 8723 verifyFormat("vector<SomeType *__attr2> v;", CustomAttrs); 8724 verifyFormat("vector<SomeType *no_underscore_attr> v;", CustomAttrs); 8725 verifyFormat("vector<SomeType __attr1 *> v;", CustomAttrs); 8726 verifyFormat("vector<SomeType __attr1 *const> v;", CustomAttrs); 8727 verifyFormat("vector<SomeType __attr1 *__attr2> v;", CustomAttrs); 8728 verifyFormat("vector<SomeType __attr1 *no_underscore_attr> v;", CustomAttrs); 8729 8730 // Check that these are not parsed as function declarations: 8731 CustomAttrs.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 8732 CustomAttrs.BreakBeforeBraces = FormatStyle::BS_Allman; 8733 verifyFormat("SomeType s(InitValue);", CustomAttrs); 8734 verifyFormat("SomeType s{InitValue};", CustomAttrs); 8735 verifyFormat("SomeType *__unused s(InitValue);", CustomAttrs); 8736 verifyFormat("SomeType *__unused s{InitValue};", CustomAttrs); 8737 verifyFormat("SomeType s __unused(InitValue);", CustomAttrs); 8738 verifyFormat("SomeType s __unused{InitValue};", CustomAttrs); 8739 verifyFormat("SomeType *__capability s(InitValue);", CustomAttrs); 8740 verifyFormat("SomeType *__capability s{InitValue};", CustomAttrs); 8741 } 8742 8743 TEST_F(FormatTest, UnderstandsPointerQualifiersInCast) { 8744 // Check that qualifiers on pointers don't break parsing of casts. 8745 verifyFormat("x = (foo *const)*v;"); 8746 verifyFormat("x = (foo *volatile)*v;"); 8747 verifyFormat("x = (foo *restrict)*v;"); 8748 verifyFormat("x = (foo *__attribute__((foo)))*v;"); 8749 verifyFormat("x = (foo *_Nonnull)*v;"); 8750 verifyFormat("x = (foo *_Nullable)*v;"); 8751 verifyFormat("x = (foo *_Null_unspecified)*v;"); 8752 verifyFormat("x = (foo *_Nonnull)*v;"); 8753 verifyFormat("x = (foo *[[clang::attr]])*v;"); 8754 verifyFormat("x = (foo *[[clang::attr(\"foo\")]])*v;"); 8755 verifyFormat("x = (foo *__ptr32)*v;"); 8756 verifyFormat("x = (foo *__ptr64)*v;"); 8757 verifyFormat("x = (foo *__capability)*v;"); 8758 8759 // Check that we handle multiple trailing qualifiers and skip them all to 8760 // determine that the expression is a cast to a pointer type. 8761 FormatStyle LongPointerRight = getLLVMStyleWithColumns(999); 8762 FormatStyle LongPointerLeft = getLLVMStyleWithColumns(999); 8763 LongPointerLeft.PointerAlignment = FormatStyle::PAS_Left; 8764 StringRef AllQualifiers = 8765 "const volatile restrict __attribute__((foo)) _Nonnull _Null_unspecified " 8766 "_Nonnull [[clang::attr]] __ptr32 __ptr64 __capability"; 8767 verifyFormat(("x = (foo *" + AllQualifiers + ")*v;").str(), LongPointerRight); 8768 verifyFormat(("x = (foo* " + AllQualifiers + ")*v;").str(), LongPointerLeft); 8769 8770 // Also check that address-of is not parsed as a binary bitwise-and: 8771 verifyFormat("x = (foo *const)&v;"); 8772 verifyFormat(("x = (foo *" + AllQualifiers + ")&v;").str(), LongPointerRight); 8773 verifyFormat(("x = (foo* " + AllQualifiers + ")&v;").str(), LongPointerLeft); 8774 8775 // Check custom qualifiers: 8776 FormatStyle CustomQualifier = getLLVMStyleWithColumns(999); 8777 CustomQualifier.AttributeMacros.push_back("__my_qualifier"); 8778 verifyFormat("x = (foo * __my_qualifier) * v;"); // not parsed as qualifier. 8779 verifyFormat("x = (foo *__my_qualifier)*v;", CustomQualifier); 8780 verifyFormat(("x = (foo *" + AllQualifiers + " __my_qualifier)*v;").str(), 8781 CustomQualifier); 8782 verifyFormat(("x = (foo *" + AllQualifiers + " __my_qualifier)&v;").str(), 8783 CustomQualifier); 8784 8785 // Check that unknown identifiers result in binary operator parsing: 8786 verifyFormat("x = (foo * __unknown_qualifier) * v;"); 8787 verifyFormat("x = (foo * __unknown_qualifier) & v;"); 8788 } 8789 8790 TEST_F(FormatTest, UnderstandsSquareAttributes) { 8791 verifyFormat("SomeType s [[unused]] (InitValue);"); 8792 verifyFormat("SomeType s [[gnu::unused]] (InitValue);"); 8793 verifyFormat("SomeType s [[using gnu: unused]] (InitValue);"); 8794 verifyFormat("[[gsl::suppress(\"clang-tidy-check-name\")]] void f() {}"); 8795 verifyFormat("void f() [[deprecated(\"so sorry\")]];"); 8796 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8797 " [[unused]] aaaaaaaaaaaaaaaaaaaaaaa(int i);"); 8798 verifyFormat("[[nodiscard]] bool f() { return false; }"); 8799 verifyFormat("class [[nodiscard]] f {\npublic:\n f() {}\n}"); 8800 verifyFormat("class [[deprecated(\"so sorry\")]] f {\npublic:\n f() {}\n}"); 8801 verifyFormat("class [[gnu::unused]] f {\npublic:\n f() {}\n}"); 8802 8803 // Make sure we do not mistake attributes for array subscripts. 8804 verifyFormat("int a() {}\n" 8805 "[[unused]] int b() {}\n"); 8806 verifyFormat("NSArray *arr;\n" 8807 "arr[[Foo() bar]];"); 8808 8809 // On the other hand, we still need to correctly find array subscripts. 8810 verifyFormat("int a = std::vector<int>{1, 2, 3}[0];"); 8811 8812 // Make sure that we do not mistake Objective-C method inside array literals 8813 // as attributes, even if those method names are also keywords. 8814 verifyFormat("@[ [foo bar] ];"); 8815 verifyFormat("@[ [NSArray class] ];"); 8816 verifyFormat("@[ [foo enum] ];"); 8817 8818 verifyFormat("template <typename T> [[nodiscard]] int a() { return 1; }"); 8819 8820 // Make sure we do not parse attributes as lambda introducers. 8821 FormatStyle MultiLineFunctions = getLLVMStyle(); 8822 MultiLineFunctions.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 8823 verifyFormat("[[unused]] int b() {\n" 8824 " return 42;\n" 8825 "}\n", 8826 MultiLineFunctions); 8827 } 8828 8829 TEST_F(FormatTest, AttributeClass) { 8830 FormatStyle Style = getChromiumStyle(FormatStyle::LK_Cpp); 8831 verifyFormat("class S {\n" 8832 " S(S&&) = default;\n" 8833 "};", 8834 Style); 8835 verifyFormat("class [[nodiscard]] S {\n" 8836 " S(S&&) = default;\n" 8837 "};", 8838 Style); 8839 verifyFormat("class __attribute((maybeunused)) S {\n" 8840 " S(S&&) = default;\n" 8841 "};", 8842 Style); 8843 verifyFormat("struct S {\n" 8844 " S(S&&) = default;\n" 8845 "};", 8846 Style); 8847 verifyFormat("struct [[nodiscard]] S {\n" 8848 " S(S&&) = default;\n" 8849 "};", 8850 Style); 8851 } 8852 8853 TEST_F(FormatTest, AttributesAfterMacro) { 8854 FormatStyle Style = getLLVMStyle(); 8855 verifyFormat("MACRO;\n" 8856 "__attribute__((maybe_unused)) int foo() {\n" 8857 " //...\n" 8858 "}"); 8859 8860 verifyFormat("MACRO;\n" 8861 "[[nodiscard]] int foo() {\n" 8862 " //...\n" 8863 "}"); 8864 8865 EXPECT_EQ("MACRO\n\n" 8866 "__attribute__((maybe_unused)) int foo() {\n" 8867 " //...\n" 8868 "}", 8869 format("MACRO\n\n" 8870 "__attribute__((maybe_unused)) int foo() {\n" 8871 " //...\n" 8872 "}")); 8873 8874 EXPECT_EQ("MACRO\n\n" 8875 "[[nodiscard]] int foo() {\n" 8876 " //...\n" 8877 "}", 8878 format("MACRO\n\n" 8879 "[[nodiscard]] int foo() {\n" 8880 " //...\n" 8881 "}")); 8882 } 8883 8884 TEST_F(FormatTest, AttributePenaltyBreaking) { 8885 FormatStyle Style = getLLVMStyle(); 8886 verifyFormat("void ABCDEFGH::ABCDEFGHIJKLMN(\n" 8887 " [[maybe_unused]] const shared_ptr<ALongTypeName> &C d) {}", 8888 Style); 8889 verifyFormat("void ABCDEFGH::ABCDEFGHIJK(\n" 8890 " [[maybe_unused]] const shared_ptr<ALongTypeName> &C d) {}", 8891 Style); 8892 verifyFormat("void ABCDEFGH::ABCDEFGH([[maybe_unused]] const " 8893 "shared_ptr<ALongTypeName> &C d) {\n}", 8894 Style); 8895 } 8896 8897 TEST_F(FormatTest, UnderstandsEllipsis) { 8898 FormatStyle Style = getLLVMStyle(); 8899 verifyFormat("int printf(const char *fmt, ...);"); 8900 verifyFormat("template <class... Ts> void Foo(Ts... ts) { Foo(ts...); }"); 8901 verifyFormat("template <class... Ts> void Foo(Ts *...ts) {}"); 8902 8903 verifyFormat("template <int *...PP> a;", Style); 8904 8905 Style.PointerAlignment = FormatStyle::PAS_Left; 8906 verifyFormat("template <class... Ts> void Foo(Ts*... ts) {}", Style); 8907 8908 verifyFormat("template <int*... PP> a;", Style); 8909 8910 Style.PointerAlignment = FormatStyle::PAS_Middle; 8911 verifyFormat("template <int *... PP> a;", Style); 8912 } 8913 8914 TEST_F(FormatTest, AdaptivelyFormatsPointersAndReferences) { 8915 EXPECT_EQ("int *a;\n" 8916 "int *a;\n" 8917 "int *a;", 8918 format("int *a;\n" 8919 "int* a;\n" 8920 "int *a;", 8921 getGoogleStyle())); 8922 EXPECT_EQ("int* a;\n" 8923 "int* a;\n" 8924 "int* a;", 8925 format("int* a;\n" 8926 "int* a;\n" 8927 "int *a;", 8928 getGoogleStyle())); 8929 EXPECT_EQ("int *a;\n" 8930 "int *a;\n" 8931 "int *a;", 8932 format("int *a;\n" 8933 "int * a;\n" 8934 "int * a;", 8935 getGoogleStyle())); 8936 EXPECT_EQ("auto x = [] {\n" 8937 " int *a;\n" 8938 " int *a;\n" 8939 " int *a;\n" 8940 "};", 8941 format("auto x=[]{int *a;\n" 8942 "int * a;\n" 8943 "int * a;};", 8944 getGoogleStyle())); 8945 } 8946 8947 TEST_F(FormatTest, UnderstandsRvalueReferences) { 8948 verifyFormat("int f(int &&a) {}"); 8949 verifyFormat("int f(int a, char &&b) {}"); 8950 verifyFormat("void f() { int &&a = b; }"); 8951 verifyGoogleFormat("int f(int a, char&& b) {}"); 8952 verifyGoogleFormat("void f() { int&& a = b; }"); 8953 8954 verifyIndependentOfContext("A<int &&> a;"); 8955 verifyIndependentOfContext("A<int &&, int &&> a;"); 8956 verifyGoogleFormat("A<int&&> a;"); 8957 verifyGoogleFormat("A<int&&, int&&> a;"); 8958 8959 // Not rvalue references: 8960 verifyFormat("template <bool B, bool C> class A {\n" 8961 " static_assert(B && C, \"Something is wrong\");\n" 8962 "};"); 8963 verifyGoogleFormat("#define IF(a, b, c) if (a && (b == c))"); 8964 verifyGoogleFormat("#define WHILE(a, b, c) while (a && (b == c))"); 8965 verifyFormat("#define A(a, b) (a && b)"); 8966 } 8967 8968 TEST_F(FormatTest, FormatsBinaryOperatorsPrecedingEquals) { 8969 verifyFormat("void f() {\n" 8970 " x[aaaaaaaaa -\n" 8971 " b] = 23;\n" 8972 "}", 8973 getLLVMStyleWithColumns(15)); 8974 } 8975 8976 TEST_F(FormatTest, FormatsCasts) { 8977 verifyFormat("Type *A = static_cast<Type *>(P);"); 8978 verifyFormat("Type *A = (Type *)P;"); 8979 verifyFormat("Type *A = (vector<Type *, int *>)P;"); 8980 verifyFormat("int a = (int)(2.0f);"); 8981 verifyFormat("int a = (int)2.0f;"); 8982 verifyFormat("x[(int32)y];"); 8983 verifyFormat("x = (int32)y;"); 8984 verifyFormat("#define AA(X) sizeof(((X *)NULL)->a)"); 8985 verifyFormat("int a = (int)*b;"); 8986 verifyFormat("int a = (int)2.0f;"); 8987 verifyFormat("int a = (int)~0;"); 8988 verifyFormat("int a = (int)++a;"); 8989 verifyFormat("int a = (int)sizeof(int);"); 8990 verifyFormat("int a = (int)+2;"); 8991 verifyFormat("my_int a = (my_int)2.0f;"); 8992 verifyFormat("my_int a = (my_int)sizeof(int);"); 8993 verifyFormat("return (my_int)aaa;"); 8994 verifyFormat("#define x ((int)-1)"); 8995 verifyFormat("#define LENGTH(x, y) (x) - (y) + 1"); 8996 verifyFormat("#define p(q) ((int *)&q)"); 8997 verifyFormat("fn(a)(b) + 1;"); 8998 8999 verifyFormat("void f() { my_int a = (my_int)*b; }"); 9000 verifyFormat("void f() { return P ? (my_int)*P : (my_int)0; }"); 9001 verifyFormat("my_int a = (my_int)~0;"); 9002 verifyFormat("my_int a = (my_int)++a;"); 9003 verifyFormat("my_int a = (my_int)-2;"); 9004 verifyFormat("my_int a = (my_int)1;"); 9005 verifyFormat("my_int a = (my_int *)1;"); 9006 verifyFormat("my_int a = (const my_int)-1;"); 9007 verifyFormat("my_int a = (const my_int *)-1;"); 9008 verifyFormat("my_int a = (my_int)(my_int)-1;"); 9009 verifyFormat("my_int a = (ns::my_int)-2;"); 9010 verifyFormat("case (my_int)ONE:"); 9011 verifyFormat("auto x = (X)this;"); 9012 // Casts in Obj-C style calls used to not be recognized as such. 9013 verifyFormat("int a = [(type*)[((type*)val) arg] arg];", getGoogleStyle()); 9014 9015 // FIXME: single value wrapped with paren will be treated as cast. 9016 verifyFormat("void f(int i = (kValue)*kMask) {}"); 9017 9018 verifyFormat("{ (void)F; }"); 9019 9020 // Don't break after a cast's 9021 verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaaa =\n" 9022 " (aaaaaaaaaaaaaaaaaaaaaaaaaa *)(aaaaaaaaaaaaaaaaaaaaaa +\n" 9023 " bbbbbbbbbbbbbbbbbbbbbb);"); 9024 9025 // These are not casts. 9026 verifyFormat("void f(int *) {}"); 9027 verifyFormat("f(foo)->b;"); 9028 verifyFormat("f(foo).b;"); 9029 verifyFormat("f(foo)(b);"); 9030 verifyFormat("f(foo)[b];"); 9031 verifyFormat("[](foo) { return 4; }(bar);"); 9032 verifyFormat("(*funptr)(foo)[4];"); 9033 verifyFormat("funptrs[4](foo)[4];"); 9034 verifyFormat("void f(int *);"); 9035 verifyFormat("void f(int *) = 0;"); 9036 verifyFormat("void f(SmallVector<int>) {}"); 9037 verifyFormat("void f(SmallVector<int>);"); 9038 verifyFormat("void f(SmallVector<int>) = 0;"); 9039 verifyFormat("void f(int i = (kA * kB) & kMask) {}"); 9040 verifyFormat("int a = sizeof(int) * b;"); 9041 verifyFormat("int a = alignof(int) * b;", getGoogleStyle()); 9042 verifyFormat("template <> void f<int>(int i) SOME_ANNOTATION;"); 9043 verifyFormat("f(\"%\" SOME_MACRO(ll) \"d\");"); 9044 verifyFormat("aaaaa &operator=(const aaaaa &) LLVM_DELETED_FUNCTION;"); 9045 9046 // These are not casts, but at some point were confused with casts. 9047 verifyFormat("virtual void foo(int *) override;"); 9048 verifyFormat("virtual void foo(char &) const;"); 9049 verifyFormat("virtual void foo(int *a, char *) const;"); 9050 verifyFormat("int a = sizeof(int *) + b;"); 9051 verifyFormat("int a = alignof(int *) + b;", getGoogleStyle()); 9052 verifyFormat("bool b = f(g<int>) && c;"); 9053 verifyFormat("typedef void (*f)(int i) func;"); 9054 verifyFormat("void operator++(int) noexcept;"); 9055 verifyFormat("void operator++(int &) noexcept;"); 9056 verifyFormat("void operator delete(void *, std::size_t, const std::nothrow_t " 9057 "&) noexcept;"); 9058 verifyFormat( 9059 "void operator delete(std::size_t, const std::nothrow_t &) noexcept;"); 9060 verifyFormat("void operator delete(const std::nothrow_t &) noexcept;"); 9061 verifyFormat("void operator delete(std::nothrow_t &) noexcept;"); 9062 verifyFormat("void operator delete(nothrow_t &) noexcept;"); 9063 verifyFormat("void operator delete(foo &) noexcept;"); 9064 verifyFormat("void operator delete(foo) noexcept;"); 9065 verifyFormat("void operator delete(int) noexcept;"); 9066 verifyFormat("void operator delete(int &) noexcept;"); 9067 verifyFormat("void operator delete(int &) volatile noexcept;"); 9068 verifyFormat("void operator delete(int &) const"); 9069 verifyFormat("void operator delete(int &) = default"); 9070 verifyFormat("void operator delete(int &) = delete"); 9071 verifyFormat("void operator delete(int &) [[noreturn]]"); 9072 verifyFormat("void operator delete(int &) throw();"); 9073 verifyFormat("void operator delete(int &) throw(int);"); 9074 verifyFormat("auto operator delete(int &) -> int;"); 9075 verifyFormat("auto operator delete(int &) override"); 9076 verifyFormat("auto operator delete(int &) final"); 9077 9078 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *foo = (aaaaaaaaaaaaaaaaa *)\n" 9079 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;"); 9080 // FIXME: The indentation here is not ideal. 9081 verifyFormat( 9082 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9083 " [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = (*cccccccccccccccc)\n" 9084 " [dddddddddddddddddddddddddddddddddddddddddddddddddddddddd];"); 9085 } 9086 9087 TEST_F(FormatTest, FormatsFunctionTypes) { 9088 verifyFormat("A<bool()> a;"); 9089 verifyFormat("A<SomeType()> a;"); 9090 verifyFormat("A<void (*)(int, std::string)> a;"); 9091 verifyFormat("A<void *(int)>;"); 9092 verifyFormat("void *(*a)(int *, SomeType *);"); 9093 verifyFormat("int (*func)(void *);"); 9094 verifyFormat("void f() { int (*func)(void *); }"); 9095 verifyFormat("template <class CallbackClass>\n" 9096 "using MyCallback = void (CallbackClass::*)(SomeObject *Data);"); 9097 9098 verifyGoogleFormat("A<void*(int*, SomeType*)>;"); 9099 verifyGoogleFormat("void* (*a)(int);"); 9100 verifyGoogleFormat( 9101 "template <class CallbackClass>\n" 9102 "using MyCallback = void (CallbackClass::*)(SomeObject* Data);"); 9103 9104 // Other constructs can look somewhat like function types: 9105 verifyFormat("A<sizeof(*x)> a;"); 9106 verifyFormat("#define DEREF_AND_CALL_F(x) f(*x)"); 9107 verifyFormat("some_var = function(*some_pointer_var)[0];"); 9108 verifyFormat("void f() { function(*some_pointer_var)[0] = 10; }"); 9109 verifyFormat("int x = f(&h)();"); 9110 verifyFormat("returnsFunction(¶m1, ¶m2)(param);"); 9111 verifyFormat("std::function<\n" 9112 " LooooooooooongTemplatedType<\n" 9113 " SomeType>*(\n" 9114 " LooooooooooooooooongType type)>\n" 9115 " function;", 9116 getGoogleStyleWithColumns(40)); 9117 } 9118 9119 TEST_F(FormatTest, FormatsPointersToArrayTypes) { 9120 verifyFormat("A (*foo_)[6];"); 9121 verifyFormat("vector<int> (*foo_)[6];"); 9122 } 9123 9124 TEST_F(FormatTest, BreaksLongVariableDeclarations) { 9125 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n" 9126 " LoooooooooooooooooooooooooooooooooooooooongVariable;"); 9127 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType const\n" 9128 " LoooooooooooooooooooooooooooooooooooooooongVariable;"); 9129 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n" 9130 " *LoooooooooooooooooooooooooooooooooooooooongVariable;"); 9131 9132 // Different ways of ()-initializiation. 9133 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n" 9134 " LoooooooooooooooooooooooooooooooooooooooongVariable(1);"); 9135 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n" 9136 " LoooooooooooooooooooooooooooooooooooooooongVariable(a);"); 9137 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n" 9138 " LoooooooooooooooooooooooooooooooooooooooongVariable({});"); 9139 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n" 9140 " LoooooooooooooooooooooooooooooooooooooongVariable([A a]);"); 9141 9142 // Lambdas should not confuse the variable declaration heuristic. 9143 verifyFormat("LooooooooooooooooongType\n" 9144 " variable(nullptr, [](A *a) {});", 9145 getLLVMStyleWithColumns(40)); 9146 } 9147 9148 TEST_F(FormatTest, BreaksLongDeclarations) { 9149 verifyFormat("typedef LoooooooooooooooooooooooooooooooooooooooongType\n" 9150 " AnotherNameForTheLongType;"); 9151 verifyFormat("typedef LongTemplateType<aaaaaaaaaaaaaaaaaaa()>\n" 9152 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 9153 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n" 9154 "LoooooooooooooooooooooooooooooooongFunctionDeclaration();"); 9155 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType *\n" 9156 "LoooooooooooooooooooooooooooooooongFunctionDeclaration();"); 9157 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n" 9158 "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}"); 9159 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType MACRO\n" 9160 "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}"); 9161 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType const\n" 9162 "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}"); 9163 verifyFormat("decltype(LoooooooooooooooooooooooooooooooooooooooongName)\n" 9164 "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}"); 9165 verifyFormat("typeof(LoooooooooooooooooooooooooooooooooooooooooongName)\n" 9166 "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}"); 9167 verifyFormat("_Atomic(LooooooooooooooooooooooooooooooooooooooooongName)\n" 9168 "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}"); 9169 verifyFormat("__underlying_type(LooooooooooooooooooooooooooooooongName)\n" 9170 "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}"); 9171 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n" 9172 "LooooooooooooooooooooooooooongFunctionDeclaration(T... t);"); 9173 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n" 9174 "LooooooooooooooooooooooooooongFunctionDeclaration(T /*t*/) {}"); 9175 FormatStyle Indented = getLLVMStyle(); 9176 Indented.IndentWrappedFunctionNames = true; 9177 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n" 9178 " LoooooooooooooooooooooooooooooooongFunctionDeclaration();", 9179 Indented); 9180 verifyFormat( 9181 "LoooooooooooooooooooooooooooooooooooooooongReturnType\n" 9182 " LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}", 9183 Indented); 9184 verifyFormat( 9185 "LoooooooooooooooooooooooooooooooooooooooongReturnType const\n" 9186 " LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}", 9187 Indented); 9188 verifyFormat( 9189 "decltype(LoooooooooooooooooooooooooooooooooooooooongName)\n" 9190 " LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}", 9191 Indented); 9192 9193 // FIXME: Without the comment, this breaks after "(". 9194 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType // break\n" 9195 " (*LoooooooooooooooooooooooooooongFunctionTypeVarialbe)();", 9196 getGoogleStyle()); 9197 9198 verifyFormat("int *someFunction(int LoooooooooooooooooooongParam1,\n" 9199 " int LoooooooooooooooooooongParam2) {}"); 9200 verifyFormat( 9201 "TypeSpecDecl *TypeSpecDecl::Create(ASTContext &C, DeclContext *DC,\n" 9202 " SourceLocation L, IdentifierIn *II,\n" 9203 " Type *T) {}"); 9204 verifyFormat("ReallyLongReturnType<TemplateParam1, TemplateParam2>\n" 9205 "ReallyReaaallyLongFunctionName(\n" 9206 " const std::string &SomeParameter,\n" 9207 " const SomeType<string, SomeOtherTemplateParameter>\n" 9208 " &ReallyReallyLongParameterName,\n" 9209 " const SomeType<string, SomeOtherTemplateParameter>\n" 9210 " &AnotherLongParameterName) {}"); 9211 verifyFormat("template <typename A>\n" 9212 "SomeLoooooooooooooooooooooongType<\n" 9213 " typename some_namespace::SomeOtherType<A>::Type>\n" 9214 "Function() {}"); 9215 9216 verifyGoogleFormat( 9217 "aaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaa<aaaaaaaaaaaaa, aaaaaaaaaaaa>\n" 9218 " aaaaaaaaaaaaaaaaaaaaaaa;"); 9219 verifyGoogleFormat( 9220 "TypeSpecDecl* TypeSpecDecl::Create(ASTContext& C, DeclContext* DC,\n" 9221 " SourceLocation L) {}"); 9222 verifyGoogleFormat( 9223 "some_namespace::LongReturnType\n" 9224 "long_namespace::SomeVeryLongClass::SomeVeryLongFunction(\n" 9225 " int first_long_parameter, int second_parameter) {}"); 9226 9227 verifyGoogleFormat("template <typename T>\n" 9228 "aaaaaaaa::aaaaa::aaaaaa<T, aaaaaaaaaaaaaaaaaaaaaaaaa>\n" 9229 "aaaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaa() {}"); 9230 verifyGoogleFormat("A<A<A>> aaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9231 " int aaaaaaaaaaaaaaaaaaaaaaa);"); 9232 9233 verifyFormat("typedef size_t (*aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)(\n" 9234 " const aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9235 " *aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 9236 verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9237 " vector<aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>\n" 9238 " aaaaaaaaaaaaaaaaaaaaaaaa);"); 9239 verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9240 " vector<aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<\n" 9241 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>>\n" 9242 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 9243 9244 verifyFormat("template <typename T> // Templates on own line.\n" 9245 "static int // Some comment.\n" 9246 "MyFunction(int a);", 9247 getLLVMStyle()); 9248 } 9249 9250 TEST_F(FormatTest, FormatsAccessModifiers) { 9251 FormatStyle Style = getLLVMStyle(); 9252 EXPECT_EQ(Style.EmptyLineBeforeAccessModifier, 9253 FormatStyle::ELBAMS_LogicalBlock); 9254 verifyFormat("struct foo {\n" 9255 "private:\n" 9256 " void f() {}\n" 9257 "\n" 9258 "private:\n" 9259 " int i;\n" 9260 "\n" 9261 "protected:\n" 9262 " int j;\n" 9263 "};\n", 9264 Style); 9265 verifyFormat("struct foo {\n" 9266 "private:\n" 9267 " void f() {}\n" 9268 "\n" 9269 "private:\n" 9270 " int i;\n" 9271 "\n" 9272 "protected:\n" 9273 " int j;\n" 9274 "};\n", 9275 "struct foo {\n" 9276 "private:\n" 9277 " void f() {}\n" 9278 "private:\n" 9279 " int i;\n" 9280 "protected:\n" 9281 " int j;\n" 9282 "};\n", 9283 Style); 9284 verifyFormat("struct foo { /* comment */\n" 9285 "private:\n" 9286 " int i;\n" 9287 " // comment\n" 9288 "private:\n" 9289 " int j;\n" 9290 "};\n", 9291 Style); 9292 verifyFormat("struct foo {\n" 9293 "#ifdef FOO\n" 9294 "#endif\n" 9295 "private:\n" 9296 " int i;\n" 9297 "#ifdef FOO\n" 9298 "private:\n" 9299 "#endif\n" 9300 " int j;\n" 9301 "};\n", 9302 Style); 9303 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never; 9304 verifyFormat("struct foo {\n" 9305 "private:\n" 9306 " void f() {}\n" 9307 "private:\n" 9308 " int i;\n" 9309 "protected:\n" 9310 " int j;\n" 9311 "};\n", 9312 Style); 9313 verifyFormat("struct foo {\n" 9314 "private:\n" 9315 " void f() {}\n" 9316 "private:\n" 9317 " int i;\n" 9318 "protected:\n" 9319 " int j;\n" 9320 "};\n", 9321 "struct foo {\n" 9322 "\n" 9323 "private:\n" 9324 " void f() {}\n" 9325 "\n" 9326 "private:\n" 9327 " int i;\n" 9328 "\n" 9329 "protected:\n" 9330 " int j;\n" 9331 "};\n", 9332 Style); 9333 verifyFormat("struct foo { /* comment */\n" 9334 "private:\n" 9335 " int i;\n" 9336 " // comment\n" 9337 "private:\n" 9338 " int j;\n" 9339 "};\n", 9340 "struct foo { /* comment */\n" 9341 "\n" 9342 "private:\n" 9343 " int i;\n" 9344 " // comment\n" 9345 "\n" 9346 "private:\n" 9347 " int j;\n" 9348 "};\n", 9349 Style); 9350 verifyFormat("struct foo {\n" 9351 "#ifdef FOO\n" 9352 "#endif\n" 9353 "private:\n" 9354 " int i;\n" 9355 "#ifdef FOO\n" 9356 "private:\n" 9357 "#endif\n" 9358 " int j;\n" 9359 "};\n", 9360 "struct foo {\n" 9361 "#ifdef FOO\n" 9362 "#endif\n" 9363 "\n" 9364 "private:\n" 9365 " int i;\n" 9366 "#ifdef FOO\n" 9367 "\n" 9368 "private:\n" 9369 "#endif\n" 9370 " int j;\n" 9371 "};\n", 9372 Style); 9373 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always; 9374 verifyFormat("struct foo {\n" 9375 "private:\n" 9376 " void f() {}\n" 9377 "\n" 9378 "private:\n" 9379 " int i;\n" 9380 "\n" 9381 "protected:\n" 9382 " int j;\n" 9383 "};\n", 9384 Style); 9385 verifyFormat("struct foo {\n" 9386 "private:\n" 9387 " void f() {}\n" 9388 "\n" 9389 "private:\n" 9390 " int i;\n" 9391 "\n" 9392 "protected:\n" 9393 " int j;\n" 9394 "};\n", 9395 "struct foo {\n" 9396 "private:\n" 9397 " void f() {}\n" 9398 "private:\n" 9399 " int i;\n" 9400 "protected:\n" 9401 " int j;\n" 9402 "};\n", 9403 Style); 9404 verifyFormat("struct foo { /* comment */\n" 9405 "private:\n" 9406 " int i;\n" 9407 " // comment\n" 9408 "\n" 9409 "private:\n" 9410 " int j;\n" 9411 "};\n", 9412 "struct foo { /* comment */\n" 9413 "private:\n" 9414 " int i;\n" 9415 " // comment\n" 9416 "\n" 9417 "private:\n" 9418 " int j;\n" 9419 "};\n", 9420 Style); 9421 verifyFormat("struct foo {\n" 9422 "#ifdef FOO\n" 9423 "#endif\n" 9424 "\n" 9425 "private:\n" 9426 " int i;\n" 9427 "#ifdef FOO\n" 9428 "\n" 9429 "private:\n" 9430 "#endif\n" 9431 " int j;\n" 9432 "};\n", 9433 "struct foo {\n" 9434 "#ifdef FOO\n" 9435 "#endif\n" 9436 "private:\n" 9437 " int i;\n" 9438 "#ifdef FOO\n" 9439 "private:\n" 9440 "#endif\n" 9441 " int j;\n" 9442 "};\n", 9443 Style); 9444 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave; 9445 EXPECT_EQ("struct foo {\n" 9446 "\n" 9447 "private:\n" 9448 " void f() {}\n" 9449 "\n" 9450 "private:\n" 9451 " int i;\n" 9452 "\n" 9453 "protected:\n" 9454 " int j;\n" 9455 "};\n", 9456 format("struct foo {\n" 9457 "\n" 9458 "private:\n" 9459 " void f() {}\n" 9460 "\n" 9461 "private:\n" 9462 " int i;\n" 9463 "\n" 9464 "protected:\n" 9465 " int j;\n" 9466 "};\n", 9467 Style)); 9468 verifyFormat("struct foo {\n" 9469 "private:\n" 9470 " void f() {}\n" 9471 "private:\n" 9472 " int i;\n" 9473 "protected:\n" 9474 " int j;\n" 9475 "};\n", 9476 Style); 9477 EXPECT_EQ("struct foo { /* comment */\n" 9478 "\n" 9479 "private:\n" 9480 " int i;\n" 9481 " // comment\n" 9482 "\n" 9483 "private:\n" 9484 " int j;\n" 9485 "};\n", 9486 format("struct foo { /* comment */\n" 9487 "\n" 9488 "private:\n" 9489 " int i;\n" 9490 " // comment\n" 9491 "\n" 9492 "private:\n" 9493 " int j;\n" 9494 "};\n", 9495 Style)); 9496 verifyFormat("struct foo { /* comment */\n" 9497 "private:\n" 9498 " int i;\n" 9499 " // comment\n" 9500 "private:\n" 9501 " int j;\n" 9502 "};\n", 9503 Style); 9504 EXPECT_EQ("struct foo {\n" 9505 "#ifdef FOO\n" 9506 "#endif\n" 9507 "\n" 9508 "private:\n" 9509 " int i;\n" 9510 "#ifdef FOO\n" 9511 "\n" 9512 "private:\n" 9513 "#endif\n" 9514 " int j;\n" 9515 "};\n", 9516 format("struct foo {\n" 9517 "#ifdef FOO\n" 9518 "#endif\n" 9519 "\n" 9520 "private:\n" 9521 " int i;\n" 9522 "#ifdef FOO\n" 9523 "\n" 9524 "private:\n" 9525 "#endif\n" 9526 " int j;\n" 9527 "};\n", 9528 Style)); 9529 verifyFormat("struct foo {\n" 9530 "#ifdef FOO\n" 9531 "#endif\n" 9532 "private:\n" 9533 " int i;\n" 9534 "#ifdef FOO\n" 9535 "private:\n" 9536 "#endif\n" 9537 " int j;\n" 9538 "};\n", 9539 Style); 9540 9541 FormatStyle NoEmptyLines = getLLVMStyle(); 9542 NoEmptyLines.MaxEmptyLinesToKeep = 0; 9543 verifyFormat("struct foo {\n" 9544 "private:\n" 9545 " void f() {}\n" 9546 "\n" 9547 "private:\n" 9548 " int i;\n" 9549 "\n" 9550 "public:\n" 9551 "protected:\n" 9552 " int j;\n" 9553 "};\n", 9554 NoEmptyLines); 9555 9556 NoEmptyLines.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never; 9557 verifyFormat("struct foo {\n" 9558 "private:\n" 9559 " void f() {}\n" 9560 "private:\n" 9561 " int i;\n" 9562 "public:\n" 9563 "protected:\n" 9564 " int j;\n" 9565 "};\n", 9566 NoEmptyLines); 9567 9568 NoEmptyLines.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always; 9569 verifyFormat("struct foo {\n" 9570 "private:\n" 9571 " void f() {}\n" 9572 "\n" 9573 "private:\n" 9574 " int i;\n" 9575 "\n" 9576 "public:\n" 9577 "\n" 9578 "protected:\n" 9579 " int j;\n" 9580 "};\n", 9581 NoEmptyLines); 9582 } 9583 9584 TEST_F(FormatTest, FormatsAfterAccessModifiers) { 9585 9586 FormatStyle Style = getLLVMStyle(); 9587 EXPECT_EQ(Style.EmptyLineAfterAccessModifier, FormatStyle::ELAAMS_Never); 9588 verifyFormat("struct foo {\n" 9589 "private:\n" 9590 " void f() {}\n" 9591 "\n" 9592 "private:\n" 9593 " int i;\n" 9594 "\n" 9595 "protected:\n" 9596 " int j;\n" 9597 "};\n", 9598 Style); 9599 9600 // Check if lines are removed. 9601 verifyFormat("struct foo {\n" 9602 "private:\n" 9603 " void f() {}\n" 9604 "\n" 9605 "private:\n" 9606 " int i;\n" 9607 "\n" 9608 "protected:\n" 9609 " int j;\n" 9610 "};\n", 9611 "struct foo {\n" 9612 "private:\n" 9613 "\n" 9614 " void f() {}\n" 9615 "\n" 9616 "private:\n" 9617 "\n" 9618 " int i;\n" 9619 "\n" 9620 "protected:\n" 9621 "\n" 9622 " int j;\n" 9623 "};\n", 9624 Style); 9625 9626 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always; 9627 verifyFormat("struct foo {\n" 9628 "private:\n" 9629 "\n" 9630 " void f() {}\n" 9631 "\n" 9632 "private:\n" 9633 "\n" 9634 " int i;\n" 9635 "\n" 9636 "protected:\n" 9637 "\n" 9638 " int j;\n" 9639 "};\n", 9640 Style); 9641 9642 // Check if lines are added. 9643 verifyFormat("struct foo {\n" 9644 "private:\n" 9645 "\n" 9646 " void f() {}\n" 9647 "\n" 9648 "private:\n" 9649 "\n" 9650 " int i;\n" 9651 "\n" 9652 "protected:\n" 9653 "\n" 9654 " int j;\n" 9655 "};\n", 9656 "struct foo {\n" 9657 "private:\n" 9658 " void f() {}\n" 9659 "\n" 9660 "private:\n" 9661 " int i;\n" 9662 "\n" 9663 "protected:\n" 9664 " int j;\n" 9665 "};\n", 9666 Style); 9667 9668 // Leave tests rely on the code layout, test::messUp can not be used. 9669 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave; 9670 Style.MaxEmptyLinesToKeep = 0u; 9671 verifyFormat("struct foo {\n" 9672 "private:\n" 9673 " void f() {}\n" 9674 "\n" 9675 "private:\n" 9676 " int i;\n" 9677 "\n" 9678 "protected:\n" 9679 " int j;\n" 9680 "};\n", 9681 Style); 9682 9683 // Check if MaxEmptyLinesToKeep is respected. 9684 EXPECT_EQ("struct foo {\n" 9685 "private:\n" 9686 " void f() {}\n" 9687 "\n" 9688 "private:\n" 9689 " int i;\n" 9690 "\n" 9691 "protected:\n" 9692 " int j;\n" 9693 "};\n", 9694 format("struct foo {\n" 9695 "private:\n" 9696 "\n\n\n" 9697 " void f() {}\n" 9698 "\n" 9699 "private:\n" 9700 "\n\n\n" 9701 " int i;\n" 9702 "\n" 9703 "protected:\n" 9704 "\n\n\n" 9705 " int j;\n" 9706 "};\n", 9707 Style)); 9708 9709 Style.MaxEmptyLinesToKeep = 1u; 9710 EXPECT_EQ("struct foo {\n" 9711 "private:\n" 9712 "\n" 9713 " void f() {}\n" 9714 "\n" 9715 "private:\n" 9716 "\n" 9717 " int i;\n" 9718 "\n" 9719 "protected:\n" 9720 "\n" 9721 " int j;\n" 9722 "};\n", 9723 format("struct foo {\n" 9724 "private:\n" 9725 "\n" 9726 " void f() {}\n" 9727 "\n" 9728 "private:\n" 9729 "\n" 9730 " int i;\n" 9731 "\n" 9732 "protected:\n" 9733 "\n" 9734 " int j;\n" 9735 "};\n", 9736 Style)); 9737 // Check if no lines are kept. 9738 EXPECT_EQ("struct foo {\n" 9739 "private:\n" 9740 " void f() {}\n" 9741 "\n" 9742 "private:\n" 9743 " int i;\n" 9744 "\n" 9745 "protected:\n" 9746 " int j;\n" 9747 "};\n", 9748 format("struct foo {\n" 9749 "private:\n" 9750 " void f() {}\n" 9751 "\n" 9752 "private:\n" 9753 " int i;\n" 9754 "\n" 9755 "protected:\n" 9756 " int j;\n" 9757 "};\n", 9758 Style)); 9759 // Check if MaxEmptyLinesToKeep is respected. 9760 EXPECT_EQ("struct foo {\n" 9761 "private:\n" 9762 "\n" 9763 " void f() {}\n" 9764 "\n" 9765 "private:\n" 9766 "\n" 9767 " int i;\n" 9768 "\n" 9769 "protected:\n" 9770 "\n" 9771 " int j;\n" 9772 "};\n", 9773 format("struct foo {\n" 9774 "private:\n" 9775 "\n\n\n" 9776 " void f() {}\n" 9777 "\n" 9778 "private:\n" 9779 "\n\n\n" 9780 " int i;\n" 9781 "\n" 9782 "protected:\n" 9783 "\n\n\n" 9784 " int j;\n" 9785 "};\n", 9786 Style)); 9787 9788 Style.MaxEmptyLinesToKeep = 10u; 9789 EXPECT_EQ("struct foo {\n" 9790 "private:\n" 9791 "\n\n\n" 9792 " void f() {}\n" 9793 "\n" 9794 "private:\n" 9795 "\n\n\n" 9796 " int i;\n" 9797 "\n" 9798 "protected:\n" 9799 "\n\n\n" 9800 " int j;\n" 9801 "};\n", 9802 format("struct foo {\n" 9803 "private:\n" 9804 "\n\n\n" 9805 " void f() {}\n" 9806 "\n" 9807 "private:\n" 9808 "\n\n\n" 9809 " int i;\n" 9810 "\n" 9811 "protected:\n" 9812 "\n\n\n" 9813 " int j;\n" 9814 "};\n", 9815 Style)); 9816 9817 // Test with comments. 9818 Style = getLLVMStyle(); 9819 verifyFormat("struct foo {\n" 9820 "private:\n" 9821 " // comment\n" 9822 " void f() {}\n" 9823 "\n" 9824 "private: /* comment */\n" 9825 " int i;\n" 9826 "};\n", 9827 Style); 9828 verifyFormat("struct foo {\n" 9829 "private:\n" 9830 " // comment\n" 9831 " void f() {}\n" 9832 "\n" 9833 "private: /* comment */\n" 9834 " int i;\n" 9835 "};\n", 9836 "struct foo {\n" 9837 "private:\n" 9838 "\n" 9839 " // comment\n" 9840 " void f() {}\n" 9841 "\n" 9842 "private: /* comment */\n" 9843 "\n" 9844 " int i;\n" 9845 "};\n", 9846 Style); 9847 9848 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always; 9849 verifyFormat("struct foo {\n" 9850 "private:\n" 9851 "\n" 9852 " // comment\n" 9853 " void f() {}\n" 9854 "\n" 9855 "private: /* comment */\n" 9856 "\n" 9857 " int i;\n" 9858 "};\n", 9859 "struct foo {\n" 9860 "private:\n" 9861 " // comment\n" 9862 " void f() {}\n" 9863 "\n" 9864 "private: /* comment */\n" 9865 " int i;\n" 9866 "};\n", 9867 Style); 9868 verifyFormat("struct foo {\n" 9869 "private:\n" 9870 "\n" 9871 " // comment\n" 9872 " void f() {}\n" 9873 "\n" 9874 "private: /* comment */\n" 9875 "\n" 9876 " int i;\n" 9877 "};\n", 9878 Style); 9879 9880 // Test with preprocessor defines. 9881 Style = getLLVMStyle(); 9882 verifyFormat("struct foo {\n" 9883 "private:\n" 9884 "#ifdef FOO\n" 9885 "#endif\n" 9886 " void f() {}\n" 9887 "};\n", 9888 Style); 9889 verifyFormat("struct foo {\n" 9890 "private:\n" 9891 "#ifdef FOO\n" 9892 "#endif\n" 9893 " void f() {}\n" 9894 "};\n", 9895 "struct foo {\n" 9896 "private:\n" 9897 "\n" 9898 "#ifdef FOO\n" 9899 "#endif\n" 9900 " void f() {}\n" 9901 "};\n", 9902 Style); 9903 9904 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always; 9905 verifyFormat("struct foo {\n" 9906 "private:\n" 9907 "\n" 9908 "#ifdef FOO\n" 9909 "#endif\n" 9910 " void f() {}\n" 9911 "};\n", 9912 "struct foo {\n" 9913 "private:\n" 9914 "#ifdef FOO\n" 9915 "#endif\n" 9916 " void f() {}\n" 9917 "};\n", 9918 Style); 9919 verifyFormat("struct foo {\n" 9920 "private:\n" 9921 "\n" 9922 "#ifdef FOO\n" 9923 "#endif\n" 9924 " void f() {}\n" 9925 "};\n", 9926 Style); 9927 } 9928 9929 TEST_F(FormatTest, FormatsAfterAndBeforeAccessModifiersInteraction) { 9930 // Combined tests of EmptyLineAfterAccessModifier and 9931 // EmptyLineBeforeAccessModifier. 9932 FormatStyle Style = getLLVMStyle(); 9933 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always; 9934 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always; 9935 verifyFormat("struct foo {\n" 9936 "private:\n" 9937 "\n" 9938 "protected:\n" 9939 "};\n", 9940 Style); 9941 9942 Style.MaxEmptyLinesToKeep = 10u; 9943 // Both remove all new lines. 9944 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never; 9945 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never; 9946 verifyFormat("struct foo {\n" 9947 "private:\n" 9948 "protected:\n" 9949 "};\n", 9950 "struct foo {\n" 9951 "private:\n" 9952 "\n\n\n" 9953 "protected:\n" 9954 "};\n", 9955 Style); 9956 9957 // Leave tests rely on the code layout, test::messUp can not be used. 9958 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave; 9959 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave; 9960 Style.MaxEmptyLinesToKeep = 10u; 9961 EXPECT_EQ("struct foo {\n" 9962 "private:\n" 9963 "\n\n\n" 9964 "protected:\n" 9965 "};\n", 9966 format("struct foo {\n" 9967 "private:\n" 9968 "\n\n\n" 9969 "protected:\n" 9970 "};\n", 9971 Style)); 9972 Style.MaxEmptyLinesToKeep = 3u; 9973 EXPECT_EQ("struct foo {\n" 9974 "private:\n" 9975 "\n\n\n" 9976 "protected:\n" 9977 "};\n", 9978 format("struct foo {\n" 9979 "private:\n" 9980 "\n\n\n" 9981 "protected:\n" 9982 "};\n", 9983 Style)); 9984 Style.MaxEmptyLinesToKeep = 1u; 9985 EXPECT_EQ("struct foo {\n" 9986 "private:\n" 9987 "\n\n\n" 9988 "protected:\n" 9989 "};\n", 9990 format("struct foo {\n" 9991 "private:\n" 9992 "\n\n\n" 9993 "protected:\n" 9994 "};\n", 9995 Style)); // Based on new lines in original document and not 9996 // on the setting. 9997 9998 Style.MaxEmptyLinesToKeep = 10u; 9999 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always; 10000 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave; 10001 // Newlines are kept if they are greater than zero, 10002 // test::messUp removes all new lines which changes the logic 10003 EXPECT_EQ("struct foo {\n" 10004 "private:\n" 10005 "\n\n\n" 10006 "protected:\n" 10007 "};\n", 10008 format("struct foo {\n" 10009 "private:\n" 10010 "\n\n\n" 10011 "protected:\n" 10012 "};\n", 10013 Style)); 10014 10015 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave; 10016 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always; 10017 // test::messUp removes all new lines which changes the logic 10018 EXPECT_EQ("struct foo {\n" 10019 "private:\n" 10020 "\n\n\n" 10021 "protected:\n" 10022 "};\n", 10023 format("struct foo {\n" 10024 "private:\n" 10025 "\n\n\n" 10026 "protected:\n" 10027 "};\n", 10028 Style)); 10029 10030 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave; 10031 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never; 10032 EXPECT_EQ("struct foo {\n" 10033 "private:\n" 10034 "\n\n\n" 10035 "protected:\n" 10036 "};\n", 10037 format("struct foo {\n" 10038 "private:\n" 10039 "\n\n\n" 10040 "protected:\n" 10041 "};\n", 10042 Style)); // test::messUp removes all new lines which changes 10043 // the logic. 10044 10045 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never; 10046 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave; 10047 verifyFormat("struct foo {\n" 10048 "private:\n" 10049 "protected:\n" 10050 "};\n", 10051 "struct foo {\n" 10052 "private:\n" 10053 "\n\n\n" 10054 "protected:\n" 10055 "};\n", 10056 Style); 10057 10058 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always; 10059 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never; 10060 EXPECT_EQ("struct foo {\n" 10061 "private:\n" 10062 "\n\n\n" 10063 "protected:\n" 10064 "};\n", 10065 format("struct foo {\n" 10066 "private:\n" 10067 "\n\n\n" 10068 "protected:\n" 10069 "};\n", 10070 Style)); // test::messUp removes all new lines which changes 10071 // the logic. 10072 10073 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never; 10074 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always; 10075 verifyFormat("struct foo {\n" 10076 "private:\n" 10077 "protected:\n" 10078 "};\n", 10079 "struct foo {\n" 10080 "private:\n" 10081 "\n\n\n" 10082 "protected:\n" 10083 "};\n", 10084 Style); 10085 10086 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock; 10087 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always; 10088 verifyFormat("struct foo {\n" 10089 "private:\n" 10090 "protected:\n" 10091 "};\n", 10092 "struct foo {\n" 10093 "private:\n" 10094 "\n\n\n" 10095 "protected:\n" 10096 "};\n", 10097 Style); 10098 10099 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock; 10100 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave; 10101 verifyFormat("struct foo {\n" 10102 "private:\n" 10103 "protected:\n" 10104 "};\n", 10105 "struct foo {\n" 10106 "private:\n" 10107 "\n\n\n" 10108 "protected:\n" 10109 "};\n", 10110 Style); 10111 10112 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock; 10113 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never; 10114 verifyFormat("struct foo {\n" 10115 "private:\n" 10116 "protected:\n" 10117 "};\n", 10118 "struct foo {\n" 10119 "private:\n" 10120 "\n\n\n" 10121 "protected:\n" 10122 "};\n", 10123 Style); 10124 } 10125 10126 TEST_F(FormatTest, FormatsArrays) { 10127 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaaaaaaaaaaaaaa]\n" 10128 " [bbbbbbbbbbbbbbbbbbbbbbbbb] = c;"); 10129 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaa(aaaaaaaaaaaa)]\n" 10130 " [bbbbbbbbbbb(bbbbbbbbbbbb)] = c;"); 10131 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaa &&\n" 10132 " aaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaa][aaaaaaaaaaaaa]) {\n}"); 10133 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 10134 " [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = ccccccccccc;"); 10135 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 10136 " [a][bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = cccccccc;"); 10137 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 10138 " [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]\n" 10139 " [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = ccccccccccc;"); 10140 verifyFormat( 10141 "llvm::outs() << \"aaaaaaaaaaaa: \"\n" 10142 " << (*aaaaaaaiaaaaaaa)[aaaaaaaaaaaaaaaaaaaaaaaaa]\n" 10143 " [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa];"); 10144 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaaaaaa][a]\n" 10145 " .aaaaaaaaaaaaaaaaaaaaaa();"); 10146 10147 verifyGoogleFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<int>\n" 10148 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaa];"); 10149 verifyFormat( 10150 "aaaaaaaaaaa aaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaa->aaaaaaaaa[0]\n" 10151 " .aaaaaaa[0]\n" 10152 " .aaaaaaaaaaaaaaaaaaaaaa();"); 10153 verifyFormat("a[::b::c];"); 10154 10155 verifyNoCrash("a[,Y?)]", getLLVMStyleWithColumns(10)); 10156 10157 FormatStyle NoColumnLimit = getLLVMStyleWithColumns(0); 10158 verifyFormat("aaaaa[bbbbbb].cccccc()", NoColumnLimit); 10159 } 10160 10161 TEST_F(FormatTest, LineStartsWithSpecialCharacter) { 10162 verifyFormat("(a)->b();"); 10163 verifyFormat("--a;"); 10164 } 10165 10166 TEST_F(FormatTest, HandlesIncludeDirectives) { 10167 verifyFormat("#include <string>\n" 10168 "#include <a/b/c.h>\n" 10169 "#include \"a/b/string\"\n" 10170 "#include \"string.h\"\n" 10171 "#include \"string.h\"\n" 10172 "#include <a-a>\n" 10173 "#include < path with space >\n" 10174 "#include_next <test.h>" 10175 "#include \"abc.h\" // this is included for ABC\n" 10176 "#include \"some long include\" // with a comment\n" 10177 "#include \"some very long include path\"\n" 10178 "#include <some/very/long/include/path>\n", 10179 getLLVMStyleWithColumns(35)); 10180 EXPECT_EQ("#include \"a.h\"", format("#include \"a.h\"")); 10181 EXPECT_EQ("#include <a>", format("#include<a>")); 10182 10183 verifyFormat("#import <string>"); 10184 verifyFormat("#import <a/b/c.h>"); 10185 verifyFormat("#import \"a/b/string\""); 10186 verifyFormat("#import \"string.h\""); 10187 verifyFormat("#import \"string.h\""); 10188 verifyFormat("#if __has_include(<strstream>)\n" 10189 "#include <strstream>\n" 10190 "#endif"); 10191 10192 verifyFormat("#define MY_IMPORT <a/b>"); 10193 10194 verifyFormat("#if __has_include(<a/b>)"); 10195 verifyFormat("#if __has_include_next(<a/b>)"); 10196 verifyFormat("#define F __has_include(<a/b>)"); 10197 verifyFormat("#define F __has_include_next(<a/b>)"); 10198 10199 // Protocol buffer definition or missing "#". 10200 verifyFormat("import \"aaaaaaaaaaaaaaaaa/aaaaaaaaaaaaaaa\";", 10201 getLLVMStyleWithColumns(30)); 10202 10203 FormatStyle Style = getLLVMStyle(); 10204 Style.AlwaysBreakBeforeMultilineStrings = true; 10205 Style.ColumnLimit = 0; 10206 verifyFormat("#import \"abc.h\"", Style); 10207 10208 // But 'import' might also be a regular C++ namespace. 10209 verifyFormat("import::SomeFunction(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 10210 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 10211 } 10212 10213 //===----------------------------------------------------------------------===// 10214 // Error recovery tests. 10215 //===----------------------------------------------------------------------===// 10216 10217 TEST_F(FormatTest, IncompleteParameterLists) { 10218 FormatStyle NoBinPacking = getLLVMStyle(); 10219 NoBinPacking.BinPackParameters = false; 10220 verifyFormat("void aaaaaaaaaaaaaaaaaa(int level,\n" 10221 " double *min_x,\n" 10222 " double *max_x,\n" 10223 " double *min_y,\n" 10224 " double *max_y,\n" 10225 " double *min_z,\n" 10226 " double *max_z, ) {}", 10227 NoBinPacking); 10228 } 10229 10230 TEST_F(FormatTest, IncorrectCodeTrailingStuff) { 10231 verifyFormat("void f() { return; }\n42"); 10232 verifyFormat("void f() {\n" 10233 " if (0)\n" 10234 " return;\n" 10235 "}\n" 10236 "42"); 10237 verifyFormat("void f() { return }\n42"); 10238 verifyFormat("void f() {\n" 10239 " if (0)\n" 10240 " return\n" 10241 "}\n" 10242 "42"); 10243 } 10244 10245 TEST_F(FormatTest, IncorrectCodeMissingSemicolon) { 10246 EXPECT_EQ("void f() { return }", format("void f ( ) { return }")); 10247 EXPECT_EQ("void f() {\n" 10248 " if (a)\n" 10249 " return\n" 10250 "}", 10251 format("void f ( ) { if ( a ) return }")); 10252 EXPECT_EQ("namespace N {\n" 10253 "void f()\n" 10254 "}", 10255 format("namespace N { void f() }")); 10256 EXPECT_EQ("namespace N {\n" 10257 "void f() {}\n" 10258 "void g()\n" 10259 "} // namespace N", 10260 format("namespace N { void f( ) { } void g( ) }")); 10261 } 10262 10263 TEST_F(FormatTest, IndentationWithinColumnLimitNotPossible) { 10264 verifyFormat("int aaaaaaaa =\n" 10265 " // Overlylongcomment\n" 10266 " b;", 10267 getLLVMStyleWithColumns(20)); 10268 verifyFormat("function(\n" 10269 " ShortArgument,\n" 10270 " LoooooooooooongArgument);\n", 10271 getLLVMStyleWithColumns(20)); 10272 } 10273 10274 TEST_F(FormatTest, IncorrectAccessSpecifier) { 10275 verifyFormat("public:"); 10276 verifyFormat("class A {\n" 10277 "public\n" 10278 " void f() {}\n" 10279 "};"); 10280 verifyFormat("public\n" 10281 "int qwerty;"); 10282 verifyFormat("public\n" 10283 "B {}"); 10284 verifyFormat("public\n" 10285 "{}"); 10286 verifyFormat("public\n" 10287 "B { int x; }"); 10288 } 10289 10290 TEST_F(FormatTest, IncorrectCodeUnbalancedBraces) { 10291 verifyFormat("{"); 10292 verifyFormat("#})"); 10293 verifyNoCrash("(/**/[:!] ?[)."); 10294 } 10295 10296 TEST_F(FormatTest, IncorrectUnbalancedBracesInMacrosWithUnicode) { 10297 // Found by oss-fuzz: 10298 // https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=8212 10299 FormatStyle Style = getGoogleStyle(FormatStyle::LK_Cpp); 10300 Style.ColumnLimit = 60; 10301 verifyNoCrash( 10302 "\x23\x47\xff\x20\x28\xff\x3c\xff\x3f\xff\x20\x2f\x7b\x7a\xff\x20" 10303 "\xff\xff\xff\xca\xb5\xff\xff\xff\xff\x3a\x7b\x7d\xff\x20\xff\x20" 10304 "\xff\x74\xff\x20\x7d\x7d\xff\x7b\x3a\xff\x20\x71\xff\x20\xff\x0a", 10305 Style); 10306 } 10307 10308 TEST_F(FormatTest, IncorrectCodeDoNoWhile) { 10309 verifyFormat("do {\n}"); 10310 verifyFormat("do {\n}\n" 10311 "f();"); 10312 verifyFormat("do {\n}\n" 10313 "wheeee(fun);"); 10314 verifyFormat("do {\n" 10315 " f();\n" 10316 "}"); 10317 } 10318 10319 TEST_F(FormatTest, IncorrectCodeMissingParens) { 10320 verifyFormat("if {\n foo;\n foo();\n}"); 10321 verifyFormat("switch {\n foo;\n foo();\n}"); 10322 verifyIncompleteFormat("for {\n foo;\n foo();\n}"); 10323 verifyFormat("while {\n foo;\n foo();\n}"); 10324 verifyFormat("do {\n foo;\n foo();\n} while;"); 10325 } 10326 10327 TEST_F(FormatTest, DoesNotTouchUnwrappedLinesWithErrors) { 10328 verifyIncompleteFormat("namespace {\n" 10329 "class Foo { Foo (\n" 10330 "};\n" 10331 "} // namespace"); 10332 } 10333 10334 TEST_F(FormatTest, IncorrectCodeErrorDetection) { 10335 EXPECT_EQ("{\n {}\n", format("{\n{\n}\n")); 10336 EXPECT_EQ("{\n {}\n", format("{\n {\n}\n")); 10337 EXPECT_EQ("{\n {}\n", format("{\n {\n }\n")); 10338 EXPECT_EQ("{\n {}\n}\n}\n", format("{\n {\n }\n }\n}\n")); 10339 10340 EXPECT_EQ("{\n" 10341 " {\n" 10342 " breakme(\n" 10343 " qwe);\n" 10344 " }\n", 10345 format("{\n" 10346 " {\n" 10347 " breakme(qwe);\n" 10348 "}\n", 10349 getLLVMStyleWithColumns(10))); 10350 } 10351 10352 TEST_F(FormatTest, LayoutCallsInsideBraceInitializers) { 10353 verifyFormat("int x = {\n" 10354 " avariable,\n" 10355 " b(alongervariable)};", 10356 getLLVMStyleWithColumns(25)); 10357 } 10358 10359 TEST_F(FormatTest, LayoutBraceInitializersInReturnStatement) { 10360 verifyFormat("return (a)(b){1, 2, 3};"); 10361 } 10362 10363 TEST_F(FormatTest, LayoutCxx11BraceInitializers) { 10364 verifyFormat("vector<int> x{1, 2, 3, 4};"); 10365 verifyFormat("vector<int> x{\n" 10366 " 1,\n" 10367 " 2,\n" 10368 " 3,\n" 10369 " 4,\n" 10370 "};"); 10371 verifyFormat("vector<T> x{{}, {}, {}, {}};"); 10372 verifyFormat("f({1, 2});"); 10373 verifyFormat("auto v = Foo{-1};"); 10374 verifyFormat("f({1, 2}, {{2, 3}, {4, 5}}, c, {d});"); 10375 verifyFormat("Class::Class : member{1, 2, 3} {}"); 10376 verifyFormat("new vector<int>{1, 2, 3};"); 10377 verifyFormat("new int[3]{1, 2, 3};"); 10378 verifyFormat("new int{1};"); 10379 verifyFormat("return {arg1, arg2};"); 10380 verifyFormat("return {arg1, SomeType{parameter}};"); 10381 verifyFormat("int count = set<int>{f(), g(), h()}.size();"); 10382 verifyFormat("new T{arg1, arg2};"); 10383 verifyFormat("f(MyMap[{composite, key}]);"); 10384 verifyFormat("class Class {\n" 10385 " T member = {arg1, arg2};\n" 10386 "};"); 10387 verifyFormat("vector<int> foo = {::SomeGlobalFunction()};"); 10388 verifyFormat("const struct A a = {.a = 1, .b = 2};"); 10389 verifyFormat("const struct A a = {[0] = 1, [1] = 2};"); 10390 verifyFormat("static_assert(std::is_integral<int>{} + 0, \"\");"); 10391 verifyFormat("int a = std::is_integral<int>{} + 0;"); 10392 10393 verifyFormat("int foo(int i) { return fo1{}(i); }"); 10394 verifyFormat("int foo(int i) { return fo1{}(i); }"); 10395 verifyFormat("auto i = decltype(x){};"); 10396 verifyFormat("auto i = typeof(x){};"); 10397 verifyFormat("auto i = _Atomic(x){};"); 10398 verifyFormat("std::vector<int> v = {1, 0 /* comment */};"); 10399 verifyFormat("Node n{1, Node{1000}, //\n" 10400 " 2};"); 10401 verifyFormat("Aaaa aaaaaaa{\n" 10402 " {\n" 10403 " aaaa,\n" 10404 " },\n" 10405 "};"); 10406 verifyFormat("class C : public D {\n" 10407 " SomeClass SC{2};\n" 10408 "};"); 10409 verifyFormat("class C : public A {\n" 10410 " class D : public B {\n" 10411 " void f() { int i{2}; }\n" 10412 " };\n" 10413 "};"); 10414 verifyFormat("#define A {a, a},"); 10415 10416 // Avoid breaking between equal sign and opening brace 10417 FormatStyle AvoidBreakingFirstArgument = getLLVMStyle(); 10418 AvoidBreakingFirstArgument.PenaltyBreakBeforeFirstCallParameter = 200; 10419 verifyFormat("const std::unordered_map<std::string, int> MyHashTable =\n" 10420 " {{\"aaaaaaaaaaaaaaaaaaaaa\", 0},\n" 10421 " {\"bbbbbbbbbbbbbbbbbbbbb\", 1},\n" 10422 " {\"ccccccccccccccccccccc\", 2}};", 10423 AvoidBreakingFirstArgument); 10424 10425 // Binpacking only if there is no trailing comma 10426 verifyFormat("const Aaaaaa aaaaa = {aaaaaaaaaa, bbbbbbbbbb,\n" 10427 " cccccccccc, dddddddddd};", 10428 getLLVMStyleWithColumns(50)); 10429 verifyFormat("const Aaaaaa aaaaa = {\n" 10430 " aaaaaaaaaaa,\n" 10431 " bbbbbbbbbbb,\n" 10432 " ccccccccccc,\n" 10433 " ddddddddddd,\n" 10434 "};", 10435 getLLVMStyleWithColumns(50)); 10436 10437 // Cases where distinguising braced lists and blocks is hard. 10438 verifyFormat("vector<int> v{12} GUARDED_BY(mutex);"); 10439 verifyFormat("void f() {\n" 10440 " return; // comment\n" 10441 "}\n" 10442 "SomeType t;"); 10443 verifyFormat("void f() {\n" 10444 " if (a) {\n" 10445 " f();\n" 10446 " }\n" 10447 "}\n" 10448 "SomeType t;"); 10449 10450 // In combination with BinPackArguments = false. 10451 FormatStyle NoBinPacking = getLLVMStyle(); 10452 NoBinPacking.BinPackArguments = false; 10453 verifyFormat("const Aaaaaa aaaaa = {aaaaa,\n" 10454 " bbbbb,\n" 10455 " ccccc,\n" 10456 " ddddd,\n" 10457 " eeeee,\n" 10458 " ffffff,\n" 10459 " ggggg,\n" 10460 " hhhhhh,\n" 10461 " iiiiii,\n" 10462 " jjjjjj,\n" 10463 " kkkkkk};", 10464 NoBinPacking); 10465 verifyFormat("const Aaaaaa aaaaa = {\n" 10466 " aaaaa,\n" 10467 " bbbbb,\n" 10468 " ccccc,\n" 10469 " ddddd,\n" 10470 " eeeee,\n" 10471 " ffffff,\n" 10472 " ggggg,\n" 10473 " hhhhhh,\n" 10474 " iiiiii,\n" 10475 " jjjjjj,\n" 10476 " kkkkkk,\n" 10477 "};", 10478 NoBinPacking); 10479 verifyFormat( 10480 "const Aaaaaa aaaaa = {\n" 10481 " aaaaa, bbbbb, ccccc, ddddd, eeeee, ffffff, ggggg, hhhhhh,\n" 10482 " iiiiii, jjjjjj, kkkkkk, aaaaa, bbbbb, ccccc, ddddd, eeeee,\n" 10483 " ffffff, ggggg, hhhhhh, iiiiii, jjjjjj, kkkkkk,\n" 10484 "};", 10485 NoBinPacking); 10486 10487 NoBinPacking.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 10488 EXPECT_EQ("static uint8 CddDp83848Reg[] = {\n" 10489 " CDDDP83848_BMCR_REGISTER,\n" 10490 " CDDDP83848_BMSR_REGISTER,\n" 10491 " CDDDP83848_RBR_REGISTER};", 10492 format("static uint8 CddDp83848Reg[] = {CDDDP83848_BMCR_REGISTER,\n" 10493 " CDDDP83848_BMSR_REGISTER,\n" 10494 " CDDDP83848_RBR_REGISTER};", 10495 NoBinPacking)); 10496 10497 // FIXME: The alignment of these trailing comments might be bad. Then again, 10498 // this might be utterly useless in real code. 10499 verifyFormat("Constructor::Constructor()\n" 10500 " : some_value{ //\n" 10501 " aaaaaaa, //\n" 10502 " bbbbbbb} {}"); 10503 10504 // In braced lists, the first comment is always assumed to belong to the 10505 // first element. Thus, it can be moved to the next or previous line as 10506 // appropriate. 10507 EXPECT_EQ("function({// First element:\n" 10508 " 1,\n" 10509 " // Second element:\n" 10510 " 2});", 10511 format("function({\n" 10512 " // First element:\n" 10513 " 1,\n" 10514 " // Second element:\n" 10515 " 2});")); 10516 EXPECT_EQ("std::vector<int> MyNumbers{\n" 10517 " // First element:\n" 10518 " 1,\n" 10519 " // Second element:\n" 10520 " 2};", 10521 format("std::vector<int> MyNumbers{// First element:\n" 10522 " 1,\n" 10523 " // Second element:\n" 10524 " 2};", 10525 getLLVMStyleWithColumns(30))); 10526 // A trailing comma should still lead to an enforced line break and no 10527 // binpacking. 10528 EXPECT_EQ("vector<int> SomeVector = {\n" 10529 " // aaa\n" 10530 " 1,\n" 10531 " 2,\n" 10532 "};", 10533 format("vector<int> SomeVector = { // aaa\n" 10534 " 1, 2, };")); 10535 10536 // C++11 brace initializer list l-braces should not be treated any differently 10537 // when breaking before lambda bodies is enabled 10538 FormatStyle BreakBeforeLambdaBody = getLLVMStyle(); 10539 BreakBeforeLambdaBody.BreakBeforeBraces = FormatStyle::BS_Custom; 10540 BreakBeforeLambdaBody.BraceWrapping.BeforeLambdaBody = true; 10541 BreakBeforeLambdaBody.AlwaysBreakBeforeMultilineStrings = true; 10542 verifyFormat( 10543 "std::runtime_error{\n" 10544 " \"Long string which will force a break onto the next line...\"};", 10545 BreakBeforeLambdaBody); 10546 10547 FormatStyle ExtraSpaces = getLLVMStyle(); 10548 ExtraSpaces.Cpp11BracedListStyle = false; 10549 ExtraSpaces.ColumnLimit = 75; 10550 verifyFormat("vector<int> x{ 1, 2, 3, 4 };", ExtraSpaces); 10551 verifyFormat("vector<T> x{ {}, {}, {}, {} };", ExtraSpaces); 10552 verifyFormat("f({ 1, 2 });", ExtraSpaces); 10553 verifyFormat("auto v = Foo{ 1 };", ExtraSpaces); 10554 verifyFormat("f({ 1, 2 }, { { 2, 3 }, { 4, 5 } }, c, { d });", ExtraSpaces); 10555 verifyFormat("Class::Class : member{ 1, 2, 3 } {}", ExtraSpaces); 10556 verifyFormat("new vector<int>{ 1, 2, 3 };", ExtraSpaces); 10557 verifyFormat("new int[3]{ 1, 2, 3 };", ExtraSpaces); 10558 verifyFormat("return { arg1, arg2 };", ExtraSpaces); 10559 verifyFormat("return { arg1, SomeType{ parameter } };", ExtraSpaces); 10560 verifyFormat("int count = set<int>{ f(), g(), h() }.size();", ExtraSpaces); 10561 verifyFormat("new T{ arg1, arg2 };", ExtraSpaces); 10562 verifyFormat("f(MyMap[{ composite, key }]);", ExtraSpaces); 10563 verifyFormat("class Class {\n" 10564 " T member = { arg1, arg2 };\n" 10565 "};", 10566 ExtraSpaces); 10567 verifyFormat( 10568 "foo = aaaaaaaaaaa ? vector<int>{ aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 10569 " aaaaaaaaaaaaaaaaaaaa, aaaaa }\n" 10570 " : vector<int>{ bbbbbbbbbbbbbbbbbbbbbbbbbbb,\n" 10571 " bbbbbbbbbbbbbbbbbbbb, bbbbb };", 10572 ExtraSpaces); 10573 verifyFormat("DoSomethingWithVector({} /* No data */);", ExtraSpaces); 10574 verifyFormat("DoSomethingWithVector({ {} /* No data */ }, { { 1, 2 } });", 10575 ExtraSpaces); 10576 verifyFormat( 10577 "someFunction(OtherParam,\n" 10578 " BracedList{ // comment 1 (Forcing interesting break)\n" 10579 " param1, param2,\n" 10580 " // comment 2\n" 10581 " param3, param4 });", 10582 ExtraSpaces); 10583 verifyFormat( 10584 "std::this_thread::sleep_for(\n" 10585 " std::chrono::nanoseconds{ std::chrono::seconds{ 1 } } / 5);", 10586 ExtraSpaces); 10587 verifyFormat("std::vector<MyValues> aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa{\n" 10588 " aaaaaaa,\n" 10589 " aaaaaaaaaa,\n" 10590 " aaaaa,\n" 10591 " aaaaaaaaaaaaaaa,\n" 10592 " aaa,\n" 10593 " aaaaaaaaaa,\n" 10594 " a,\n" 10595 " aaaaaaaaaaaaaaaaaaaaa,\n" 10596 " aaaaaaaaaaaa,\n" 10597 " aaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaa,\n" 10598 " aaaaaaa,\n" 10599 " a};"); 10600 verifyFormat("vector<int> foo = { ::SomeGlobalFunction() };", ExtraSpaces); 10601 verifyFormat("const struct A a = { .a = 1, .b = 2 };", ExtraSpaces); 10602 verifyFormat("const struct A a = { [0] = 1, [1] = 2 };", ExtraSpaces); 10603 10604 // Avoid breaking between initializer/equal sign and opening brace 10605 ExtraSpaces.PenaltyBreakBeforeFirstCallParameter = 200; 10606 verifyFormat("const std::unordered_map<std::string, int> MyHashTable = {\n" 10607 " { \"aaaaaaaaaaaaaaaaaaaaa\", 0 },\n" 10608 " { \"bbbbbbbbbbbbbbbbbbbbb\", 1 },\n" 10609 " { \"ccccccccccccccccccccc\", 2 }\n" 10610 "};", 10611 ExtraSpaces); 10612 verifyFormat("const std::unordered_map<std::string, int> MyHashTable{\n" 10613 " { \"aaaaaaaaaaaaaaaaaaaaa\", 0 },\n" 10614 " { \"bbbbbbbbbbbbbbbbbbbbb\", 1 },\n" 10615 " { \"ccccccccccccccccccccc\", 2 }\n" 10616 "};", 10617 ExtraSpaces); 10618 10619 FormatStyle SpaceBeforeBrace = getLLVMStyle(); 10620 SpaceBeforeBrace.SpaceBeforeCpp11BracedList = true; 10621 verifyFormat("vector<int> x {1, 2, 3, 4};", SpaceBeforeBrace); 10622 verifyFormat("f({}, {{}, {}}, MyMap[{k, v}]);", SpaceBeforeBrace); 10623 10624 FormatStyle SpaceBetweenBraces = getLLVMStyle(); 10625 SpaceBetweenBraces.SpacesInAngles = FormatStyle::SIAS_Always; 10626 SpaceBetweenBraces.SpacesInParentheses = true; 10627 SpaceBetweenBraces.SpacesInSquareBrackets = true; 10628 verifyFormat("vector< int > x{ 1, 2, 3, 4 };", SpaceBetweenBraces); 10629 verifyFormat("f( {}, { {}, {} }, MyMap[ { k, v } ] );", SpaceBetweenBraces); 10630 verifyFormat("vector< int > x{ // comment 1\n" 10631 " 1, 2, 3, 4 };", 10632 SpaceBetweenBraces); 10633 SpaceBetweenBraces.ColumnLimit = 20; 10634 EXPECT_EQ("vector< int > x{\n" 10635 " 1, 2, 3, 4 };", 10636 format("vector<int>x{1,2,3,4};", SpaceBetweenBraces)); 10637 SpaceBetweenBraces.ColumnLimit = 24; 10638 EXPECT_EQ("vector< int > x{ 1, 2,\n" 10639 " 3, 4 };", 10640 format("vector<int>x{1,2,3,4};", SpaceBetweenBraces)); 10641 EXPECT_EQ("vector< int > x{\n" 10642 " 1,\n" 10643 " 2,\n" 10644 " 3,\n" 10645 " 4,\n" 10646 "};", 10647 format("vector<int>x{1,2,3,4,};", SpaceBetweenBraces)); 10648 verifyFormat("vector< int > x{};", SpaceBetweenBraces); 10649 SpaceBetweenBraces.SpaceInEmptyParentheses = true; 10650 verifyFormat("vector< int > x{ };", SpaceBetweenBraces); 10651 } 10652 10653 TEST_F(FormatTest, FormatsBracedListsInColumnLayout) { 10654 verifyFormat("vector<int> x = {1, 22, 333, 4444, 55555, 666666, 7777777,\n" 10655 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 10656 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 10657 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 10658 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 10659 " 1, 22, 333, 4444, 55555, 666666, 7777777};"); 10660 verifyFormat("vector<int> x = {1, 22, 333, 4444, 55555, 666666, 7777777, //\n" 10661 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 10662 " 1, 22, 333, 4444, 55555, //\n" 10663 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 10664 " 1, 22, 333, 4444, 55555, 666666, 7777777};"); 10665 verifyFormat( 10666 "vector<int> x = {1, 22, 333, 4444, 55555, 666666, 7777777,\n" 10667 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 10668 " 1, 22, 333, 4444, 55555, 666666, // comment\n" 10669 " 7777777, 1, 22, 333, 4444, 55555, 666666,\n" 10670 " 7777777, 1, 22, 333, 4444, 55555, 666666,\n" 10671 " 7777777, 1, 22, 333, 4444, 55555, 666666,\n" 10672 " 7777777};"); 10673 verifyFormat("static const uint16_t CallerSavedRegs64Bittttt[] = {\n" 10674 " X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,\n" 10675 " X86::R8, X86::R9, X86::R10, X86::R11, 0};"); 10676 verifyFormat("static const uint16_t CallerSavedRegs64Bittttt[] = {\n" 10677 " X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,\n" 10678 " // Separating comment.\n" 10679 " X86::R8, X86::R9, X86::R10, X86::R11, 0};"); 10680 verifyFormat("static const uint16_t CallerSavedRegs64Bittttt[] = {\n" 10681 " // Leading comment\n" 10682 " X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,\n" 10683 " X86::R8, X86::R9, X86::R10, X86::R11, 0};"); 10684 verifyFormat("vector<int> x = {1, 1, 1, 1,\n" 10685 " 1, 1, 1, 1};", 10686 getLLVMStyleWithColumns(39)); 10687 verifyFormat("vector<int> x = {1, 1, 1, 1,\n" 10688 " 1, 1, 1, 1};", 10689 getLLVMStyleWithColumns(38)); 10690 verifyFormat("vector<int> aaaaaaaaaaaaaaaaaaaaaa = {\n" 10691 " 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1};", 10692 getLLVMStyleWithColumns(43)); 10693 verifyFormat( 10694 "static unsigned SomeValues[10][3] = {\n" 10695 " {1, 4, 0}, {4, 9, 0}, {4, 5, 9}, {8, 5, 4}, {1, 8, 4},\n" 10696 " {10, 1, 6}, {11, 0, 9}, {2, 11, 9}, {5, 2, 9}, {11, 2, 7}};"); 10697 verifyFormat("static auto fields = new vector<string>{\n" 10698 " \"aaaaaaaaaaaaa\",\n" 10699 " \"aaaaaaaaaaaaa\",\n" 10700 " \"aaaaaaaaaaaa\",\n" 10701 " \"aaaaaaaaaaaaaa\",\n" 10702 " \"aaaaaaaaaaaaaaaaaaaaaaaaa\",\n" 10703 " \"aaaaaaaaaaaa\",\n" 10704 " \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\n" 10705 "};"); 10706 verifyFormat("vector<int> x = {1, 2, 3, 4, aaaaaaaaaaaaaaaaa, 6};"); 10707 verifyFormat("vector<int> x = {1, aaaaaaaaaaaaaaaaaaaaaa,\n" 10708 " 2, bbbbbbbbbbbbbbbbbbbbbb,\n" 10709 " 3, cccccccccccccccccccccc};", 10710 getLLVMStyleWithColumns(60)); 10711 10712 // Trailing commas. 10713 verifyFormat("vector<int> x = {\n" 10714 " 1, 1, 1, 1, 1, 1, 1, 1,\n" 10715 "};", 10716 getLLVMStyleWithColumns(39)); 10717 verifyFormat("vector<int> x = {\n" 10718 " 1, 1, 1, 1, 1, 1, 1, 1, //\n" 10719 "};", 10720 getLLVMStyleWithColumns(39)); 10721 verifyFormat("vector<int> x = {1, 1, 1, 1,\n" 10722 " 1, 1, 1, 1,\n" 10723 " /**/ /**/};", 10724 getLLVMStyleWithColumns(39)); 10725 10726 // Trailing comment in the first line. 10727 verifyFormat("vector<int> iiiiiiiiiiiiiii = { //\n" 10728 " 1111111111, 2222222222, 33333333333, 4444444444, //\n" 10729 " 111111111, 222222222, 3333333333, 444444444, //\n" 10730 " 11111111, 22222222, 333333333, 44444444};"); 10731 // Trailing comment in the last line. 10732 verifyFormat("int aaaaa[] = {\n" 10733 " 1, 2, 3, // comment\n" 10734 " 4, 5, 6 // comment\n" 10735 "};"); 10736 10737 // With nested lists, we should either format one item per line or all nested 10738 // lists one on line. 10739 // FIXME: For some nested lists, we can do better. 10740 verifyFormat("return {{aaaaaaaaaaaaaaaaaaaaa},\n" 10741 " {aaaaaaaaaaaaaaaaaaa},\n" 10742 " {aaaaaaaaaaaaaaaaaaaaa},\n" 10743 " {aaaaaaaaaaaaaaaaa}};", 10744 getLLVMStyleWithColumns(60)); 10745 verifyFormat( 10746 "SomeStruct my_struct_array = {\n" 10747 " {aaaaaa, aaaaaaaa, aaaaaaaaaa, aaaaaaaaa, aaaaaaaaa, aaaaaaaaaa,\n" 10748 " aaaaaaaaaaaaa, aaaaaaa, aaa},\n" 10749 " {aaa, aaa},\n" 10750 " {aaa, aaa},\n" 10751 " {aaaa, aaaa, aaaa, aaaa, aaaa, aaaa, aaaa, aaa},\n" 10752 " {aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaa,\n" 10753 " aaaaaaaaaaaa, a, aaaaaaaaaa, aaaaaaaaa, aaa}};"); 10754 10755 // No column layout should be used here. 10756 verifyFormat("aaaaaaaaaaaaaaa = {aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, 0, 0,\n" 10757 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb};"); 10758 10759 verifyNoCrash("a<,"); 10760 10761 // No braced initializer here. 10762 verifyFormat("void f() {\n" 10763 " struct Dummy {};\n" 10764 " f(v);\n" 10765 "}"); 10766 10767 // Long lists should be formatted in columns even if they are nested. 10768 verifyFormat( 10769 "vector<int> x = function({1, 22, 333, 4444, 55555, 666666, 7777777,\n" 10770 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 10771 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 10772 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 10773 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 10774 " 1, 22, 333, 4444, 55555, 666666, 7777777});"); 10775 10776 // Allow "single-column" layout even if that violates the column limit. There 10777 // isn't going to be a better way. 10778 verifyFormat("std::vector<int> a = {\n" 10779 " aaaaaaaa,\n" 10780 " aaaaaaaa,\n" 10781 " aaaaaaaa,\n" 10782 " aaaaaaaa,\n" 10783 " aaaaaaaaaa,\n" 10784 " aaaaaaaa,\n" 10785 " aaaaaaaaaaaaaaaaaaaaaaaaaaa};", 10786 getLLVMStyleWithColumns(30)); 10787 verifyFormat("vector<int> aaaa = {\n" 10788 " aaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 10789 " aaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 10790 " aaaaaa.aaaaaaa,\n" 10791 " aaaaaa.aaaaaaa,\n" 10792 " aaaaaa.aaaaaaa,\n" 10793 " aaaaaa.aaaaaaa,\n" 10794 "};"); 10795 10796 // Don't create hanging lists. 10797 verifyFormat("someFunction(Param, {List1, List2,\n" 10798 " List3});", 10799 getLLVMStyleWithColumns(35)); 10800 verifyFormat("someFunction(Param, Param,\n" 10801 " {List1, List2,\n" 10802 " List3});", 10803 getLLVMStyleWithColumns(35)); 10804 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaa, {},\n" 10805 " aaaaaaaaaaaaaaaaaaaaaaa);"); 10806 } 10807 10808 TEST_F(FormatTest, PullTrivialFunctionDefinitionsIntoSingleLine) { 10809 FormatStyle DoNotMerge = getLLVMStyle(); 10810 DoNotMerge.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 10811 10812 verifyFormat("void f() { return 42; }"); 10813 verifyFormat("void f() {\n" 10814 " return 42;\n" 10815 "}", 10816 DoNotMerge); 10817 verifyFormat("void f() {\n" 10818 " // Comment\n" 10819 "}"); 10820 verifyFormat("{\n" 10821 "#error {\n" 10822 " int a;\n" 10823 "}"); 10824 verifyFormat("{\n" 10825 " int a;\n" 10826 "#error {\n" 10827 "}"); 10828 verifyFormat("void f() {} // comment"); 10829 verifyFormat("void f() { int a; } // comment"); 10830 verifyFormat("void f() {\n" 10831 "} // comment", 10832 DoNotMerge); 10833 verifyFormat("void f() {\n" 10834 " int a;\n" 10835 "} // comment", 10836 DoNotMerge); 10837 verifyFormat("void f() {\n" 10838 "} // comment", 10839 getLLVMStyleWithColumns(15)); 10840 10841 verifyFormat("void f() { return 42; }", getLLVMStyleWithColumns(23)); 10842 verifyFormat("void f() {\n return 42;\n}", getLLVMStyleWithColumns(22)); 10843 10844 verifyFormat("void f() {}", getLLVMStyleWithColumns(11)); 10845 verifyFormat("void f() {\n}", getLLVMStyleWithColumns(10)); 10846 verifyFormat("class C {\n" 10847 " C()\n" 10848 " : iiiiiiii(nullptr),\n" 10849 " kkkkkkk(nullptr),\n" 10850 " mmmmmmm(nullptr),\n" 10851 " nnnnnnn(nullptr) {}\n" 10852 "};", 10853 getGoogleStyle()); 10854 10855 FormatStyle NoColumnLimit = getLLVMStyle(); 10856 NoColumnLimit.ColumnLimit = 0; 10857 EXPECT_EQ("A() : b(0) {}", format("A():b(0){}", NoColumnLimit)); 10858 EXPECT_EQ("class C {\n" 10859 " A() : b(0) {}\n" 10860 "};", 10861 format("class C{A():b(0){}};", NoColumnLimit)); 10862 EXPECT_EQ("A()\n" 10863 " : b(0) {\n" 10864 "}", 10865 format("A()\n:b(0)\n{\n}", NoColumnLimit)); 10866 10867 FormatStyle DoNotMergeNoColumnLimit = NoColumnLimit; 10868 DoNotMergeNoColumnLimit.AllowShortFunctionsOnASingleLine = 10869 FormatStyle::SFS_None; 10870 EXPECT_EQ("A()\n" 10871 " : b(0) {\n" 10872 "}", 10873 format("A():b(0){}", DoNotMergeNoColumnLimit)); 10874 EXPECT_EQ("A()\n" 10875 " : b(0) {\n" 10876 "}", 10877 format("A()\n:b(0)\n{\n}", DoNotMergeNoColumnLimit)); 10878 10879 verifyFormat("#define A \\\n" 10880 " void f() { \\\n" 10881 " int i; \\\n" 10882 " }", 10883 getLLVMStyleWithColumns(20)); 10884 verifyFormat("#define A \\\n" 10885 " void f() { int i; }", 10886 getLLVMStyleWithColumns(21)); 10887 verifyFormat("#define A \\\n" 10888 " void f() { \\\n" 10889 " int i; \\\n" 10890 " } \\\n" 10891 " int j;", 10892 getLLVMStyleWithColumns(22)); 10893 verifyFormat("#define A \\\n" 10894 " void f() { int i; } \\\n" 10895 " int j;", 10896 getLLVMStyleWithColumns(23)); 10897 } 10898 10899 TEST_F(FormatTest, PullEmptyFunctionDefinitionsIntoSingleLine) { 10900 FormatStyle MergeEmptyOnly = getLLVMStyle(); 10901 MergeEmptyOnly.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty; 10902 verifyFormat("class C {\n" 10903 " int f() {}\n" 10904 "};", 10905 MergeEmptyOnly); 10906 verifyFormat("class C {\n" 10907 " int f() {\n" 10908 " return 42;\n" 10909 " }\n" 10910 "};", 10911 MergeEmptyOnly); 10912 verifyFormat("int f() {}", MergeEmptyOnly); 10913 verifyFormat("int f() {\n" 10914 " return 42;\n" 10915 "}", 10916 MergeEmptyOnly); 10917 10918 // Also verify behavior when BraceWrapping.AfterFunction = true 10919 MergeEmptyOnly.BreakBeforeBraces = FormatStyle::BS_Custom; 10920 MergeEmptyOnly.BraceWrapping.AfterFunction = true; 10921 verifyFormat("int f() {}", MergeEmptyOnly); 10922 verifyFormat("class C {\n" 10923 " int f() {}\n" 10924 "};", 10925 MergeEmptyOnly); 10926 } 10927 10928 TEST_F(FormatTest, PullInlineFunctionDefinitionsIntoSingleLine) { 10929 FormatStyle MergeInlineOnly = getLLVMStyle(); 10930 MergeInlineOnly.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline; 10931 verifyFormat("class C {\n" 10932 " int f() { return 42; }\n" 10933 "};", 10934 MergeInlineOnly); 10935 verifyFormat("int f() {\n" 10936 " return 42;\n" 10937 "}", 10938 MergeInlineOnly); 10939 10940 // SFS_Inline implies SFS_Empty 10941 verifyFormat("class C {\n" 10942 " int f() {}\n" 10943 "};", 10944 MergeInlineOnly); 10945 verifyFormat("int f() {}", MergeInlineOnly); 10946 10947 // Also verify behavior when BraceWrapping.AfterFunction = true 10948 MergeInlineOnly.BreakBeforeBraces = FormatStyle::BS_Custom; 10949 MergeInlineOnly.BraceWrapping.AfterFunction = true; 10950 verifyFormat("class C {\n" 10951 " int f() { return 42; }\n" 10952 "};", 10953 MergeInlineOnly); 10954 verifyFormat("int f()\n" 10955 "{\n" 10956 " return 42;\n" 10957 "}", 10958 MergeInlineOnly); 10959 10960 // SFS_Inline implies SFS_Empty 10961 verifyFormat("int f() {}", MergeInlineOnly); 10962 verifyFormat("class C {\n" 10963 " int f() {}\n" 10964 "};", 10965 MergeInlineOnly); 10966 } 10967 10968 TEST_F(FormatTest, PullInlineOnlyFunctionDefinitionsIntoSingleLine) { 10969 FormatStyle MergeInlineOnly = getLLVMStyle(); 10970 MergeInlineOnly.AllowShortFunctionsOnASingleLine = 10971 FormatStyle::SFS_InlineOnly; 10972 verifyFormat("class C {\n" 10973 " int f() { return 42; }\n" 10974 "};", 10975 MergeInlineOnly); 10976 verifyFormat("int f() {\n" 10977 " return 42;\n" 10978 "}", 10979 MergeInlineOnly); 10980 10981 // SFS_InlineOnly does not imply SFS_Empty 10982 verifyFormat("class C {\n" 10983 " int f() {}\n" 10984 "};", 10985 MergeInlineOnly); 10986 verifyFormat("int f() {\n" 10987 "}", 10988 MergeInlineOnly); 10989 10990 // Also verify behavior when BraceWrapping.AfterFunction = true 10991 MergeInlineOnly.BreakBeforeBraces = FormatStyle::BS_Custom; 10992 MergeInlineOnly.BraceWrapping.AfterFunction = true; 10993 verifyFormat("class C {\n" 10994 " int f() { return 42; }\n" 10995 "};", 10996 MergeInlineOnly); 10997 verifyFormat("int f()\n" 10998 "{\n" 10999 " return 42;\n" 11000 "}", 11001 MergeInlineOnly); 11002 11003 // SFS_InlineOnly does not imply SFS_Empty 11004 verifyFormat("int f()\n" 11005 "{\n" 11006 "}", 11007 MergeInlineOnly); 11008 verifyFormat("class C {\n" 11009 " int f() {}\n" 11010 "};", 11011 MergeInlineOnly); 11012 } 11013 11014 TEST_F(FormatTest, SplitEmptyFunction) { 11015 FormatStyle Style = getLLVMStyle(); 11016 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 11017 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 11018 Style.BraceWrapping.AfterFunction = true; 11019 Style.BraceWrapping.SplitEmptyFunction = false; 11020 Style.ColumnLimit = 40; 11021 11022 verifyFormat("int f()\n" 11023 "{}", 11024 Style); 11025 verifyFormat("int f()\n" 11026 "{\n" 11027 " return 42;\n" 11028 "}", 11029 Style); 11030 verifyFormat("int f()\n" 11031 "{\n" 11032 " // some comment\n" 11033 "}", 11034 Style); 11035 11036 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty; 11037 verifyFormat("int f() {}", Style); 11038 verifyFormat("int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n" 11039 "{}", 11040 Style); 11041 verifyFormat("int f()\n" 11042 "{\n" 11043 " return 0;\n" 11044 "}", 11045 Style); 11046 11047 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline; 11048 verifyFormat("class Foo {\n" 11049 " int f() {}\n" 11050 "};\n", 11051 Style); 11052 verifyFormat("class Foo {\n" 11053 " int f() { return 0; }\n" 11054 "};\n", 11055 Style); 11056 verifyFormat("class Foo {\n" 11057 " int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n" 11058 " {}\n" 11059 "};\n", 11060 Style); 11061 verifyFormat("class Foo {\n" 11062 " int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n" 11063 " {\n" 11064 " return 0;\n" 11065 " }\n" 11066 "};\n", 11067 Style); 11068 11069 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All; 11070 verifyFormat("int f() {}", Style); 11071 verifyFormat("int f() { return 0; }", Style); 11072 verifyFormat("int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n" 11073 "{}", 11074 Style); 11075 verifyFormat("int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n" 11076 "{\n" 11077 " return 0;\n" 11078 "}", 11079 Style); 11080 } 11081 TEST_F(FormatTest, KeepShortFunctionAfterPPElse) { 11082 FormatStyle Style = getLLVMStyle(); 11083 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All; 11084 verifyFormat("#ifdef A\n" 11085 "int f() {}\n" 11086 "#else\n" 11087 "int g() {}\n" 11088 "#endif", 11089 Style); 11090 } 11091 11092 TEST_F(FormatTest, SplitEmptyClass) { 11093 FormatStyle Style = getLLVMStyle(); 11094 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 11095 Style.BraceWrapping.AfterClass = true; 11096 Style.BraceWrapping.SplitEmptyRecord = false; 11097 11098 verifyFormat("class Foo\n" 11099 "{};", 11100 Style); 11101 verifyFormat("/* something */ class Foo\n" 11102 "{};", 11103 Style); 11104 verifyFormat("template <typename X> class Foo\n" 11105 "{};", 11106 Style); 11107 verifyFormat("class Foo\n" 11108 "{\n" 11109 " Foo();\n" 11110 "};", 11111 Style); 11112 verifyFormat("typedef class Foo\n" 11113 "{\n" 11114 "} Foo_t;", 11115 Style); 11116 11117 Style.BraceWrapping.SplitEmptyRecord = true; 11118 Style.BraceWrapping.AfterStruct = true; 11119 verifyFormat("class rep\n" 11120 "{\n" 11121 "};", 11122 Style); 11123 verifyFormat("struct rep\n" 11124 "{\n" 11125 "};", 11126 Style); 11127 verifyFormat("template <typename T> class rep\n" 11128 "{\n" 11129 "};", 11130 Style); 11131 verifyFormat("template <typename T> struct rep\n" 11132 "{\n" 11133 "};", 11134 Style); 11135 verifyFormat("class rep\n" 11136 "{\n" 11137 " int x;\n" 11138 "};", 11139 Style); 11140 verifyFormat("struct rep\n" 11141 "{\n" 11142 " int x;\n" 11143 "};", 11144 Style); 11145 verifyFormat("template <typename T> class rep\n" 11146 "{\n" 11147 " int x;\n" 11148 "};", 11149 Style); 11150 verifyFormat("template <typename T> struct rep\n" 11151 "{\n" 11152 " int x;\n" 11153 "};", 11154 Style); 11155 verifyFormat("template <typename T> class rep // Foo\n" 11156 "{\n" 11157 " int x;\n" 11158 "};", 11159 Style); 11160 verifyFormat("template <typename T> struct rep // Bar\n" 11161 "{\n" 11162 " int x;\n" 11163 "};", 11164 Style); 11165 11166 verifyFormat("template <typename T> class rep<T>\n" 11167 "{\n" 11168 " int x;\n" 11169 "};", 11170 Style); 11171 11172 verifyFormat("template <typename T> class rep<std::complex<T>>\n" 11173 "{\n" 11174 " int x;\n" 11175 "};", 11176 Style); 11177 verifyFormat("template <typename T> class rep<std::complex<T>>\n" 11178 "{\n" 11179 "};", 11180 Style); 11181 11182 verifyFormat("#include \"stdint.h\"\n" 11183 "namespace rep {}", 11184 Style); 11185 verifyFormat("#include <stdint.h>\n" 11186 "namespace rep {}", 11187 Style); 11188 verifyFormat("#include <stdint.h>\n" 11189 "namespace rep {}", 11190 "#include <stdint.h>\n" 11191 "namespace rep {\n" 11192 "\n" 11193 "\n" 11194 "}", 11195 Style); 11196 } 11197 11198 TEST_F(FormatTest, SplitEmptyStruct) { 11199 FormatStyle Style = getLLVMStyle(); 11200 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 11201 Style.BraceWrapping.AfterStruct = true; 11202 Style.BraceWrapping.SplitEmptyRecord = false; 11203 11204 verifyFormat("struct Foo\n" 11205 "{};", 11206 Style); 11207 verifyFormat("/* something */ struct Foo\n" 11208 "{};", 11209 Style); 11210 verifyFormat("template <typename X> struct Foo\n" 11211 "{};", 11212 Style); 11213 verifyFormat("struct Foo\n" 11214 "{\n" 11215 " Foo();\n" 11216 "};", 11217 Style); 11218 verifyFormat("typedef struct Foo\n" 11219 "{\n" 11220 "} Foo_t;", 11221 Style); 11222 // typedef struct Bar {} Bar_t; 11223 } 11224 11225 TEST_F(FormatTest, SplitEmptyUnion) { 11226 FormatStyle Style = getLLVMStyle(); 11227 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 11228 Style.BraceWrapping.AfterUnion = true; 11229 Style.BraceWrapping.SplitEmptyRecord = false; 11230 11231 verifyFormat("union Foo\n" 11232 "{};", 11233 Style); 11234 verifyFormat("/* something */ union Foo\n" 11235 "{};", 11236 Style); 11237 verifyFormat("union Foo\n" 11238 "{\n" 11239 " A,\n" 11240 "};", 11241 Style); 11242 verifyFormat("typedef union Foo\n" 11243 "{\n" 11244 "} Foo_t;", 11245 Style); 11246 } 11247 11248 TEST_F(FormatTest, SplitEmptyNamespace) { 11249 FormatStyle Style = getLLVMStyle(); 11250 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 11251 Style.BraceWrapping.AfterNamespace = true; 11252 Style.BraceWrapping.SplitEmptyNamespace = false; 11253 11254 verifyFormat("namespace Foo\n" 11255 "{};", 11256 Style); 11257 verifyFormat("/* something */ namespace Foo\n" 11258 "{};", 11259 Style); 11260 verifyFormat("inline namespace Foo\n" 11261 "{};", 11262 Style); 11263 verifyFormat("/* something */ inline namespace Foo\n" 11264 "{};", 11265 Style); 11266 verifyFormat("export namespace Foo\n" 11267 "{};", 11268 Style); 11269 verifyFormat("namespace Foo\n" 11270 "{\n" 11271 "void Bar();\n" 11272 "};", 11273 Style); 11274 } 11275 11276 TEST_F(FormatTest, NeverMergeShortRecords) { 11277 FormatStyle Style = getLLVMStyle(); 11278 11279 verifyFormat("class Foo {\n" 11280 " Foo();\n" 11281 "};", 11282 Style); 11283 verifyFormat("typedef class Foo {\n" 11284 " Foo();\n" 11285 "} Foo_t;", 11286 Style); 11287 verifyFormat("struct Foo {\n" 11288 " Foo();\n" 11289 "};", 11290 Style); 11291 verifyFormat("typedef struct Foo {\n" 11292 " Foo();\n" 11293 "} Foo_t;", 11294 Style); 11295 verifyFormat("union Foo {\n" 11296 " A,\n" 11297 "};", 11298 Style); 11299 verifyFormat("typedef union Foo {\n" 11300 " A,\n" 11301 "} Foo_t;", 11302 Style); 11303 verifyFormat("namespace Foo {\n" 11304 "void Bar();\n" 11305 "};", 11306 Style); 11307 11308 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 11309 Style.BraceWrapping.AfterClass = true; 11310 Style.BraceWrapping.AfterStruct = true; 11311 Style.BraceWrapping.AfterUnion = true; 11312 Style.BraceWrapping.AfterNamespace = true; 11313 verifyFormat("class Foo\n" 11314 "{\n" 11315 " Foo();\n" 11316 "};", 11317 Style); 11318 verifyFormat("typedef class Foo\n" 11319 "{\n" 11320 " Foo();\n" 11321 "} Foo_t;", 11322 Style); 11323 verifyFormat("struct Foo\n" 11324 "{\n" 11325 " Foo();\n" 11326 "};", 11327 Style); 11328 verifyFormat("typedef struct Foo\n" 11329 "{\n" 11330 " Foo();\n" 11331 "} Foo_t;", 11332 Style); 11333 verifyFormat("union Foo\n" 11334 "{\n" 11335 " A,\n" 11336 "};", 11337 Style); 11338 verifyFormat("typedef union Foo\n" 11339 "{\n" 11340 " A,\n" 11341 "} Foo_t;", 11342 Style); 11343 verifyFormat("namespace Foo\n" 11344 "{\n" 11345 "void Bar();\n" 11346 "};", 11347 Style); 11348 } 11349 11350 TEST_F(FormatTest, UnderstandContextOfRecordTypeKeywords) { 11351 // Elaborate type variable declarations. 11352 verifyFormat("struct foo a = {bar};\nint n;"); 11353 verifyFormat("class foo a = {bar};\nint n;"); 11354 verifyFormat("union foo a = {bar};\nint n;"); 11355 11356 // Elaborate types inside function definitions. 11357 verifyFormat("struct foo f() {}\nint n;"); 11358 verifyFormat("class foo f() {}\nint n;"); 11359 verifyFormat("union foo f() {}\nint n;"); 11360 11361 // Templates. 11362 verifyFormat("template <class X> void f() {}\nint n;"); 11363 verifyFormat("template <struct X> void f() {}\nint n;"); 11364 verifyFormat("template <union X> void f() {}\nint n;"); 11365 11366 // Actual definitions... 11367 verifyFormat("struct {\n} n;"); 11368 verifyFormat( 11369 "template <template <class T, class Y>, class Z> class X {\n} n;"); 11370 verifyFormat("union Z {\n int n;\n} x;"); 11371 verifyFormat("class MACRO Z {\n} n;"); 11372 verifyFormat("class MACRO(X) Z {\n} n;"); 11373 verifyFormat("class __attribute__(X) Z {\n} n;"); 11374 verifyFormat("class __declspec(X) Z {\n} n;"); 11375 verifyFormat("class A##B##C {\n} n;"); 11376 verifyFormat("class alignas(16) Z {\n} n;"); 11377 verifyFormat("class MACRO(X) alignas(16) Z {\n} n;"); 11378 verifyFormat("class MACROA MACRO(X) Z {\n} n;"); 11379 11380 // Redefinition from nested context: 11381 verifyFormat("class A::B::C {\n} n;"); 11382 11383 // Template definitions. 11384 verifyFormat( 11385 "template <typename F>\n" 11386 "Matcher(const Matcher<F> &Other,\n" 11387 " typename enable_if_c<is_base_of<F, T>::value &&\n" 11388 " !is_same<F, T>::value>::type * = 0)\n" 11389 " : Implementation(new ImplicitCastMatcher<F>(Other)) {}"); 11390 11391 // FIXME: This is still incorrectly handled at the formatter side. 11392 verifyFormat("template <> struct X < 15, i<3 && 42 < 50 && 33 < 28> {};"); 11393 verifyFormat("int i = SomeFunction(a<b, a> b);"); 11394 11395 // FIXME: 11396 // This now gets parsed incorrectly as class definition. 11397 // verifyFormat("class A<int> f() {\n}\nint n;"); 11398 11399 // Elaborate types where incorrectly parsing the structural element would 11400 // break the indent. 11401 verifyFormat("if (true)\n" 11402 " class X x;\n" 11403 "else\n" 11404 " f();\n"); 11405 11406 // This is simply incomplete. Formatting is not important, but must not crash. 11407 verifyFormat("class A:"); 11408 } 11409 11410 TEST_F(FormatTest, DoNotInterfereWithErrorAndWarning) { 11411 EXPECT_EQ("#error Leave all white!!!!! space* alone!\n", 11412 format("#error Leave all white!!!!! space* alone!\n")); 11413 EXPECT_EQ( 11414 "#warning Leave all white!!!!! space* alone!\n", 11415 format("#warning Leave all white!!!!! space* alone!\n")); 11416 EXPECT_EQ("#error 1", format(" # error 1")); 11417 EXPECT_EQ("#warning 1", format(" # warning 1")); 11418 } 11419 11420 TEST_F(FormatTest, FormatHashIfExpressions) { 11421 verifyFormat("#if AAAA && BBBB"); 11422 verifyFormat("#if (AAAA && BBBB)"); 11423 verifyFormat("#elif (AAAA && BBBB)"); 11424 // FIXME: Come up with a better indentation for #elif. 11425 verifyFormat( 11426 "#if !defined(AAAAAAA) && (defined CCCCCC || defined DDDDDD) && \\\n" 11427 " defined(BBBBBBBB)\n" 11428 "#elif !defined(AAAAAA) && (defined CCCCC || defined DDDDDD) && \\\n" 11429 " defined(BBBBBBBB)\n" 11430 "#endif", 11431 getLLVMStyleWithColumns(65)); 11432 } 11433 11434 TEST_F(FormatTest, MergeHandlingInTheFaceOfPreprocessorDirectives) { 11435 FormatStyle AllowsMergedIf = getGoogleStyle(); 11436 AllowsMergedIf.AllowShortIfStatementsOnASingleLine = 11437 FormatStyle::SIS_WithoutElse; 11438 verifyFormat("void f() { f(); }\n#error E", AllowsMergedIf); 11439 verifyFormat("if (true) return 42;\n#error E", AllowsMergedIf); 11440 verifyFormat("if (true)\n#error E\n return 42;", AllowsMergedIf); 11441 EXPECT_EQ("if (true) return 42;", 11442 format("if (true)\nreturn 42;", AllowsMergedIf)); 11443 FormatStyle ShortMergedIf = AllowsMergedIf; 11444 ShortMergedIf.ColumnLimit = 25; 11445 verifyFormat("#define A \\\n" 11446 " if (true) return 42;", 11447 ShortMergedIf); 11448 verifyFormat("#define A \\\n" 11449 " f(); \\\n" 11450 " if (true)\n" 11451 "#define B", 11452 ShortMergedIf); 11453 verifyFormat("#define A \\\n" 11454 " f(); \\\n" 11455 " if (true)\n" 11456 "g();", 11457 ShortMergedIf); 11458 verifyFormat("{\n" 11459 "#ifdef A\n" 11460 " // Comment\n" 11461 " if (true) continue;\n" 11462 "#endif\n" 11463 " // Comment\n" 11464 " if (true) continue;\n" 11465 "}", 11466 ShortMergedIf); 11467 ShortMergedIf.ColumnLimit = 33; 11468 verifyFormat("#define A \\\n" 11469 " if constexpr (true) return 42;", 11470 ShortMergedIf); 11471 verifyFormat("#define A \\\n" 11472 " if CONSTEXPR (true) return 42;", 11473 ShortMergedIf); 11474 ShortMergedIf.ColumnLimit = 29; 11475 verifyFormat("#define A \\\n" 11476 " if (aaaaaaaaaa) return 1; \\\n" 11477 " return 2;", 11478 ShortMergedIf); 11479 ShortMergedIf.ColumnLimit = 28; 11480 verifyFormat("#define A \\\n" 11481 " if (aaaaaaaaaa) \\\n" 11482 " return 1; \\\n" 11483 " return 2;", 11484 ShortMergedIf); 11485 verifyFormat("#define A \\\n" 11486 " if constexpr (aaaaaaa) \\\n" 11487 " return 1; \\\n" 11488 " return 2;", 11489 ShortMergedIf); 11490 verifyFormat("#define A \\\n" 11491 " if CONSTEXPR (aaaaaaa) \\\n" 11492 " return 1; \\\n" 11493 " return 2;", 11494 ShortMergedIf); 11495 } 11496 11497 TEST_F(FormatTest, FormatStarDependingOnContext) { 11498 verifyFormat("void f(int *a);"); 11499 verifyFormat("void f() { f(fint * b); }"); 11500 verifyFormat("class A {\n void f(int *a);\n};"); 11501 verifyFormat("class A {\n int *a;\n};"); 11502 verifyFormat("namespace a {\n" 11503 "namespace b {\n" 11504 "class A {\n" 11505 " void f() {}\n" 11506 " int *a;\n" 11507 "};\n" 11508 "} // namespace b\n" 11509 "} // namespace a"); 11510 } 11511 11512 TEST_F(FormatTest, SpecialTokensAtEndOfLine) { 11513 verifyFormat("while"); 11514 verifyFormat("operator"); 11515 } 11516 11517 TEST_F(FormatTest, SkipsDeeplyNestedLines) { 11518 // This code would be painfully slow to format if we didn't skip it. 11519 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 11520 "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n" 11521 "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n" 11522 "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n" 11523 "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n" 11524 "A(1, 1)\n" 11525 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" // 10x 11526 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 11527 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 11528 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 11529 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 11530 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 11531 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 11532 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 11533 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 11534 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1);\n"); 11535 // Deeply nested part is untouched, rest is formatted. 11536 EXPECT_EQ(std::string("int i;\n") + Code + "int j;\n", 11537 format(std::string("int i;\n") + Code + "int j;\n", 11538 getLLVMStyle(), SC_ExpectIncomplete)); 11539 } 11540 11541 //===----------------------------------------------------------------------===// 11542 // Objective-C tests. 11543 //===----------------------------------------------------------------------===// 11544 11545 TEST_F(FormatTest, FormatForObjectiveCMethodDecls) { 11546 verifyFormat("- (void)sendAction:(SEL)aSelector to:(BOOL)anObject;"); 11547 EXPECT_EQ("- (NSUInteger)indexOfObject:(id)anObject;", 11548 format("-(NSUInteger)indexOfObject:(id)anObject;")); 11549 EXPECT_EQ("- (NSInteger)Mthod1;", format("-(NSInteger)Mthod1;")); 11550 EXPECT_EQ("+ (id)Mthod2;", format("+(id)Mthod2;")); 11551 EXPECT_EQ("- (NSInteger)Method3:(id)anObject;", 11552 format("-(NSInteger)Method3:(id)anObject;")); 11553 EXPECT_EQ("- (NSInteger)Method4:(id)anObject;", 11554 format("-(NSInteger)Method4:(id)anObject;")); 11555 EXPECT_EQ("- (NSInteger)Method5:(id)anObject:(id)AnotherObject;", 11556 format("-(NSInteger)Method5:(id)anObject:(id)AnotherObject;")); 11557 EXPECT_EQ("- (id)Method6:(id)A:(id)B:(id)C:(id)D;", 11558 format("- (id)Method6:(id)A:(id)B:(id)C:(id)D;")); 11559 EXPECT_EQ("- (void)sendAction:(SEL)aSelector to:(id)anObject " 11560 "forAllCells:(BOOL)flag;", 11561 format("- (void)sendAction:(SEL)aSelector to:(id)anObject " 11562 "forAllCells:(BOOL)flag;")); 11563 11564 // Very long objectiveC method declaration. 11565 verifyFormat("- (void)aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa:\n" 11566 " (SoooooooooooooooooooooomeType *)bbbbbbbbbb;"); 11567 verifyFormat("- (NSUInteger)indexOfObject:(id)anObject\n" 11568 " inRange:(NSRange)range\n" 11569 " outRange:(NSRange)out_range\n" 11570 " outRange1:(NSRange)out_range1\n" 11571 " outRange2:(NSRange)out_range2\n" 11572 " outRange3:(NSRange)out_range3\n" 11573 " outRange4:(NSRange)out_range4\n" 11574 " outRange5:(NSRange)out_range5\n" 11575 " outRange6:(NSRange)out_range6\n" 11576 " outRange7:(NSRange)out_range7\n" 11577 " outRange8:(NSRange)out_range8\n" 11578 " outRange9:(NSRange)out_range9;"); 11579 11580 // When the function name has to be wrapped. 11581 FormatStyle Style = getLLVMStyle(); 11582 // ObjC ignores IndentWrappedFunctionNames when wrapping methods 11583 // and always indents instead. 11584 Style.IndentWrappedFunctionNames = false; 11585 verifyFormat("- (SomeLooooooooooooooooooooongType *)\n" 11586 " veryLooooooooooongName:(NSString)aaaaaaaaaaaaaa\n" 11587 " anotherName:(NSString)bbbbbbbbbbbbbb {\n" 11588 "}", 11589 Style); 11590 Style.IndentWrappedFunctionNames = true; 11591 verifyFormat("- (SomeLooooooooooooooooooooongType *)\n" 11592 " veryLooooooooooongName:(NSString)cccccccccccccc\n" 11593 " anotherName:(NSString)dddddddddddddd {\n" 11594 "}", 11595 Style); 11596 11597 verifyFormat("- (int)sum:(vector<int>)numbers;"); 11598 verifyGoogleFormat("- (void)setDelegate:(id<Protocol>)delegate;"); 11599 // FIXME: In LLVM style, there should be a space in front of a '<' for ObjC 11600 // protocol lists (but not for template classes): 11601 // verifyFormat("- (void)setDelegate:(id <Protocol>)delegate;"); 11602 11603 verifyFormat("- (int (*)())foo:(int (*)())f;"); 11604 verifyGoogleFormat("- (int (*)())foo:(int (*)())foo;"); 11605 11606 // If there's no return type (very rare in practice!), LLVM and Google style 11607 // agree. 11608 verifyFormat("- foo;"); 11609 verifyFormat("- foo:(int)f;"); 11610 verifyGoogleFormat("- foo:(int)foo;"); 11611 } 11612 11613 TEST_F(FormatTest, BreaksStringLiterals) { 11614 EXPECT_EQ("\"some text \"\n" 11615 "\"other\";", 11616 format("\"some text other\";", getLLVMStyleWithColumns(12))); 11617 EXPECT_EQ("\"some text \"\n" 11618 "\"other\";", 11619 format("\\\n\"some text other\";", getLLVMStyleWithColumns(12))); 11620 EXPECT_EQ( 11621 "#define A \\\n" 11622 " \"some \" \\\n" 11623 " \"text \" \\\n" 11624 " \"other\";", 11625 format("#define A \"some text other\";", getLLVMStyleWithColumns(12))); 11626 EXPECT_EQ( 11627 "#define A \\\n" 11628 " \"so \" \\\n" 11629 " \"text \" \\\n" 11630 " \"other\";", 11631 format("#define A \"so text other\";", getLLVMStyleWithColumns(12))); 11632 11633 EXPECT_EQ("\"some text\"", 11634 format("\"some text\"", getLLVMStyleWithColumns(1))); 11635 EXPECT_EQ("\"some text\"", 11636 format("\"some text\"", getLLVMStyleWithColumns(11))); 11637 EXPECT_EQ("\"some \"\n" 11638 "\"text\"", 11639 format("\"some text\"", getLLVMStyleWithColumns(10))); 11640 EXPECT_EQ("\"some \"\n" 11641 "\"text\"", 11642 format("\"some text\"", getLLVMStyleWithColumns(7))); 11643 EXPECT_EQ("\"some\"\n" 11644 "\" tex\"\n" 11645 "\"t\"", 11646 format("\"some text\"", getLLVMStyleWithColumns(6))); 11647 EXPECT_EQ("\"some\"\n" 11648 "\" tex\"\n" 11649 "\" and\"", 11650 format("\"some tex and\"", getLLVMStyleWithColumns(6))); 11651 EXPECT_EQ("\"some\"\n" 11652 "\"/tex\"\n" 11653 "\"/and\"", 11654 format("\"some/tex/and\"", getLLVMStyleWithColumns(6))); 11655 11656 EXPECT_EQ("variable =\n" 11657 " \"long string \"\n" 11658 " \"literal\";", 11659 format("variable = \"long string literal\";", 11660 getLLVMStyleWithColumns(20))); 11661 11662 EXPECT_EQ("variable = f(\n" 11663 " \"long string \"\n" 11664 " \"literal\",\n" 11665 " short,\n" 11666 " loooooooooooooooooooong);", 11667 format("variable = f(\"long string literal\", short, " 11668 "loooooooooooooooooooong);", 11669 getLLVMStyleWithColumns(20))); 11670 11671 EXPECT_EQ( 11672 "f(g(\"long string \"\n" 11673 " \"literal\"),\n" 11674 " b);", 11675 format("f(g(\"long string literal\"), b);", getLLVMStyleWithColumns(20))); 11676 EXPECT_EQ("f(g(\"long string \"\n" 11677 " \"literal\",\n" 11678 " a),\n" 11679 " b);", 11680 format("f(g(\"long string literal\", a), b);", 11681 getLLVMStyleWithColumns(20))); 11682 EXPECT_EQ( 11683 "f(\"one two\".split(\n" 11684 " variable));", 11685 format("f(\"one two\".split(variable));", getLLVMStyleWithColumns(20))); 11686 EXPECT_EQ("f(\"one two three four five six \"\n" 11687 " \"seven\".split(\n" 11688 " really_looooong_variable));", 11689 format("f(\"one two three four five six seven\"." 11690 "split(really_looooong_variable));", 11691 getLLVMStyleWithColumns(33))); 11692 11693 EXPECT_EQ("f(\"some \"\n" 11694 " \"text\",\n" 11695 " other);", 11696 format("f(\"some text\", other);", getLLVMStyleWithColumns(10))); 11697 11698 // Only break as a last resort. 11699 verifyFormat( 11700 "aaaaaaaaaaaaaaaaaaaa(\n" 11701 " aaaaaaaaaaaaaaaaaaaa,\n" 11702 " aaaaaa(\"aaa aaaaa aaa aaa aaaaa aaa aaaaa aaa aaa aaaaaa\"));"); 11703 11704 EXPECT_EQ("\"splitmea\"\n" 11705 "\"trandomp\"\n" 11706 "\"oint\"", 11707 format("\"splitmeatrandompoint\"", getLLVMStyleWithColumns(10))); 11708 11709 EXPECT_EQ("\"split/\"\n" 11710 "\"pathat/\"\n" 11711 "\"slashes\"", 11712 format("\"split/pathat/slashes\"", getLLVMStyleWithColumns(10))); 11713 11714 EXPECT_EQ("\"split/\"\n" 11715 "\"pathat/\"\n" 11716 "\"slashes\"", 11717 format("\"split/pathat/slashes\"", getLLVMStyleWithColumns(10))); 11718 EXPECT_EQ("\"split at \"\n" 11719 "\"spaces/at/\"\n" 11720 "\"slashes.at.any$\"\n" 11721 "\"non-alphanumeric%\"\n" 11722 "\"1111111111characte\"\n" 11723 "\"rs\"", 11724 format("\"split at " 11725 "spaces/at/" 11726 "slashes.at." 11727 "any$non-" 11728 "alphanumeric%" 11729 "1111111111characte" 11730 "rs\"", 11731 getLLVMStyleWithColumns(20))); 11732 11733 // Verify that splitting the strings understands 11734 // Style::AlwaysBreakBeforeMultilineStrings. 11735 EXPECT_EQ("aaaaaaaaaaaa(\n" 11736 " \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa \"\n" 11737 " \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa\");", 11738 format("aaaaaaaaaaaa(\"aaaaaaaaaaaaaaaaaaaaaaaaaa " 11739 "aaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa " 11740 "aaaaaaaaaaaaaaaaaaaaaa\");", 11741 getGoogleStyle())); 11742 EXPECT_EQ("return \"aaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa \"\n" 11743 " \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa\";", 11744 format("return \"aaaaaaaaaaaaaaaaaaaaaa " 11745 "aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa " 11746 "aaaaaaaaaaaaaaaaaaaaaa\";", 11747 getGoogleStyle())); 11748 EXPECT_EQ("llvm::outs() << \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n" 11749 " \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";", 11750 format("llvm::outs() << " 11751 "\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaa" 11752 "aaaaaaaaaaaaaaaaaaa\";")); 11753 EXPECT_EQ("ffff(\n" 11754 " {\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n" 11755 " \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"});", 11756 format("ffff({\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa " 11757 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"});", 11758 getGoogleStyle())); 11759 11760 FormatStyle Style = getLLVMStyleWithColumns(12); 11761 Style.BreakStringLiterals = false; 11762 EXPECT_EQ("\"some text other\";", format("\"some text other\";", Style)); 11763 11764 FormatStyle AlignLeft = getLLVMStyleWithColumns(12); 11765 AlignLeft.AlignEscapedNewlines = FormatStyle::ENAS_Left; 11766 EXPECT_EQ("#define A \\\n" 11767 " \"some \" \\\n" 11768 " \"text \" \\\n" 11769 " \"other\";", 11770 format("#define A \"some text other\";", AlignLeft)); 11771 } 11772 11773 TEST_F(FormatTest, BreaksStringLiteralsAtColumnLimit) { 11774 EXPECT_EQ("C a = \"some more \"\n" 11775 " \"text\";", 11776 format("C a = \"some more text\";", getLLVMStyleWithColumns(18))); 11777 } 11778 11779 TEST_F(FormatTest, FullyRemoveEmptyLines) { 11780 FormatStyle NoEmptyLines = getLLVMStyleWithColumns(80); 11781 NoEmptyLines.MaxEmptyLinesToKeep = 0; 11782 EXPECT_EQ("int i = a(b());", 11783 format("int i=a(\n\n b(\n\n\n )\n\n);", NoEmptyLines)); 11784 } 11785 11786 TEST_F(FormatTest, BreaksStringLiteralsWithTabs) { 11787 EXPECT_EQ( 11788 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" 11789 "(\n" 11790 " \"x\t\");", 11791 format("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" 11792 "aaaaaaa(" 11793 "\"x\t\");")); 11794 } 11795 11796 TEST_F(FormatTest, BreaksWideAndNSStringLiterals) { 11797 EXPECT_EQ( 11798 "u8\"utf8 string \"\n" 11799 "u8\"literal\";", 11800 format("u8\"utf8 string literal\";", getGoogleStyleWithColumns(16))); 11801 EXPECT_EQ( 11802 "u\"utf16 string \"\n" 11803 "u\"literal\";", 11804 format("u\"utf16 string literal\";", getGoogleStyleWithColumns(16))); 11805 EXPECT_EQ( 11806 "U\"utf32 string \"\n" 11807 "U\"literal\";", 11808 format("U\"utf32 string literal\";", getGoogleStyleWithColumns(16))); 11809 EXPECT_EQ("L\"wide string \"\n" 11810 "L\"literal\";", 11811 format("L\"wide string literal\";", getGoogleStyleWithColumns(16))); 11812 EXPECT_EQ("@\"NSString \"\n" 11813 "@\"literal\";", 11814 format("@\"NSString literal\";", getGoogleStyleWithColumns(19))); 11815 verifyFormat(R"(NSString *s = @"那那那那";)", getLLVMStyleWithColumns(26)); 11816 11817 // This input makes clang-format try to split the incomplete unicode escape 11818 // sequence, which used to lead to a crasher. 11819 verifyNoCrash( 11820 "aaaaaaaaaaaaaaaaaaaa = L\"\\udff\"'; // aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", 11821 getLLVMStyleWithColumns(60)); 11822 } 11823 11824 TEST_F(FormatTest, DoesNotBreakRawStringLiterals) { 11825 FormatStyle Style = getGoogleStyleWithColumns(15); 11826 EXPECT_EQ("R\"x(raw literal)x\";", format("R\"x(raw literal)x\";", Style)); 11827 EXPECT_EQ("uR\"x(raw literal)x\";", format("uR\"x(raw literal)x\";", Style)); 11828 EXPECT_EQ("LR\"x(raw literal)x\";", format("LR\"x(raw literal)x\";", Style)); 11829 EXPECT_EQ("UR\"x(raw literal)x\";", format("UR\"x(raw literal)x\";", Style)); 11830 EXPECT_EQ("u8R\"x(raw literal)x\";", 11831 format("u8R\"x(raw literal)x\";", Style)); 11832 } 11833 11834 TEST_F(FormatTest, BreaksStringLiteralsWithin_TMacro) { 11835 FormatStyle Style = getLLVMStyleWithColumns(20); 11836 EXPECT_EQ( 11837 "_T(\"aaaaaaaaaaaaaa\")\n" 11838 "_T(\"aaaaaaaaaaaaaa\")\n" 11839 "_T(\"aaaaaaaaaaaa\")", 11840 format(" _T(\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\")", Style)); 11841 EXPECT_EQ("f(x,\n" 11842 " _T(\"aaaaaaaaaaaa\")\n" 11843 " _T(\"aaa\"),\n" 11844 " z);", 11845 format("f(x, _T(\"aaaaaaaaaaaaaaa\"), z);", Style)); 11846 11847 // FIXME: Handle embedded spaces in one iteration. 11848 // EXPECT_EQ("_T(\"aaaaaaaaaaaaa\")\n" 11849 // "_T(\"aaaaaaaaaaaaa\")\n" 11850 // "_T(\"aaaaaaaaaaaaa\")\n" 11851 // "_T(\"a\")", 11852 // format(" _T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )", 11853 // getLLVMStyleWithColumns(20))); 11854 EXPECT_EQ( 11855 "_T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )", 11856 format(" _T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )", Style)); 11857 EXPECT_EQ("f(\n" 11858 "#if !TEST\n" 11859 " _T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\")\n" 11860 "#endif\n" 11861 ");", 11862 format("f(\n" 11863 "#if !TEST\n" 11864 "_T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\")\n" 11865 "#endif\n" 11866 ");")); 11867 EXPECT_EQ("f(\n" 11868 "\n" 11869 " _T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\"));", 11870 format("f(\n" 11871 "\n" 11872 "_T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\"));")); 11873 } 11874 11875 TEST_F(FormatTest, BreaksStringLiteralOperands) { 11876 // In a function call with two operands, the second can be broken with no line 11877 // break before it. 11878 EXPECT_EQ( 11879 "func(a, \"long long \"\n" 11880 " \"long long\");", 11881 format("func(a, \"long long long long\");", getLLVMStyleWithColumns(24))); 11882 // In a function call with three operands, the second must be broken with a 11883 // line break before it. 11884 EXPECT_EQ("func(a,\n" 11885 " \"long long long \"\n" 11886 " \"long\",\n" 11887 " c);", 11888 format("func(a, \"long long long long\", c);", 11889 getLLVMStyleWithColumns(24))); 11890 // In a function call with three operands, the third must be broken with a 11891 // line break before it. 11892 EXPECT_EQ("func(a, b,\n" 11893 " \"long long long \"\n" 11894 " \"long\");", 11895 format("func(a, b, \"long long long long\");", 11896 getLLVMStyleWithColumns(24))); 11897 // In a function call with three operands, both the second and the third must 11898 // be broken with a line break before them. 11899 EXPECT_EQ("func(a,\n" 11900 " \"long long long \"\n" 11901 " \"long\",\n" 11902 " \"long long long \"\n" 11903 " \"long\");", 11904 format("func(a, \"long long long long\", \"long long long long\");", 11905 getLLVMStyleWithColumns(24))); 11906 // In a chain of << with two operands, the second can be broken with no line 11907 // break before it. 11908 EXPECT_EQ("a << \"line line \"\n" 11909 " \"line\";", 11910 format("a << \"line line line\";", getLLVMStyleWithColumns(20))); 11911 // In a chain of << with three operands, the second can be broken with no line 11912 // break before it. 11913 EXPECT_EQ( 11914 "abcde << \"line \"\n" 11915 " \"line line\"\n" 11916 " << c;", 11917 format("abcde << \"line line line\" << c;", getLLVMStyleWithColumns(20))); 11918 // In a chain of << with three operands, the third must be broken with a line 11919 // break before it. 11920 EXPECT_EQ( 11921 "a << b\n" 11922 " << \"line line \"\n" 11923 " \"line\";", 11924 format("a << b << \"line line line\";", getLLVMStyleWithColumns(20))); 11925 // In a chain of << with three operands, the second can be broken with no line 11926 // break before it and the third must be broken with a line break before it. 11927 EXPECT_EQ("abcd << \"line line \"\n" 11928 " \"line\"\n" 11929 " << \"line line \"\n" 11930 " \"line\";", 11931 format("abcd << \"line line line\" << \"line line line\";", 11932 getLLVMStyleWithColumns(20))); 11933 // In a chain of binary operators with two operands, the second can be broken 11934 // with no line break before it. 11935 EXPECT_EQ( 11936 "abcd + \"line line \"\n" 11937 " \"line line\";", 11938 format("abcd + \"line line line line\";", getLLVMStyleWithColumns(20))); 11939 // In a chain of binary operators with three operands, the second must be 11940 // broken with a line break before it. 11941 EXPECT_EQ("abcd +\n" 11942 " \"line line \"\n" 11943 " \"line line\" +\n" 11944 " e;", 11945 format("abcd + \"line line line line\" + e;", 11946 getLLVMStyleWithColumns(20))); 11947 // In a function call with two operands, with AlignAfterOpenBracket enabled, 11948 // the first must be broken with a line break before it. 11949 FormatStyle Style = getLLVMStyleWithColumns(25); 11950 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 11951 EXPECT_EQ("someFunction(\n" 11952 " \"long long long \"\n" 11953 " \"long\",\n" 11954 " a);", 11955 format("someFunction(\"long long long long\", a);", Style)); 11956 } 11957 11958 TEST_F(FormatTest, DontSplitStringLiteralsWithEscapedNewlines) { 11959 EXPECT_EQ( 11960 "aaaaaaaaaaa = \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n" 11961 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n" 11962 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";", 11963 format("aaaaaaaaaaa = \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n" 11964 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n" 11965 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";")); 11966 } 11967 11968 TEST_F(FormatTest, CountsCharactersInMultilineRawStringLiterals) { 11969 EXPECT_EQ("f(g(R\"x(raw literal)x\", a), b);", 11970 format("f(g(R\"x(raw literal)x\", a), b);", getGoogleStyle())); 11971 EXPECT_EQ("fffffffffff(g(R\"x(\n" 11972 "multiline raw string literal xxxxxxxxxxxxxx\n" 11973 ")x\",\n" 11974 " a),\n" 11975 " b);", 11976 format("fffffffffff(g(R\"x(\n" 11977 "multiline raw string literal xxxxxxxxxxxxxx\n" 11978 ")x\", a), b);", 11979 getGoogleStyleWithColumns(20))); 11980 EXPECT_EQ("fffffffffff(\n" 11981 " g(R\"x(qqq\n" 11982 "multiline raw string literal xxxxxxxxxxxxxx\n" 11983 ")x\",\n" 11984 " a),\n" 11985 " b);", 11986 format("fffffffffff(g(R\"x(qqq\n" 11987 "multiline raw string literal xxxxxxxxxxxxxx\n" 11988 ")x\", a), b);", 11989 getGoogleStyleWithColumns(20))); 11990 11991 EXPECT_EQ("fffffffffff(R\"x(\n" 11992 "multiline raw string literal xxxxxxxxxxxxxx\n" 11993 ")x\");", 11994 format("fffffffffff(R\"x(\n" 11995 "multiline raw string literal xxxxxxxxxxxxxx\n" 11996 ")x\");", 11997 getGoogleStyleWithColumns(20))); 11998 EXPECT_EQ("fffffffffff(R\"x(\n" 11999 "multiline raw string literal xxxxxxxxxxxxxx\n" 12000 ")x\" + bbbbbb);", 12001 format("fffffffffff(R\"x(\n" 12002 "multiline raw string literal xxxxxxxxxxxxxx\n" 12003 ")x\" + bbbbbb);", 12004 getGoogleStyleWithColumns(20))); 12005 EXPECT_EQ("fffffffffff(\n" 12006 " R\"x(\n" 12007 "multiline raw string literal xxxxxxxxxxxxxx\n" 12008 ")x\" +\n" 12009 " bbbbbb);", 12010 format("fffffffffff(\n" 12011 " R\"x(\n" 12012 "multiline raw string literal xxxxxxxxxxxxxx\n" 12013 ")x\" + bbbbbb);", 12014 getGoogleStyleWithColumns(20))); 12015 EXPECT_EQ("fffffffffff(R\"(single line raw string)\" + bbbbbb);", 12016 format("fffffffffff(\n" 12017 " R\"(single line raw string)\" + bbbbbb);")); 12018 } 12019 12020 TEST_F(FormatTest, SkipsUnknownStringLiterals) { 12021 verifyFormat("string a = \"unterminated;"); 12022 EXPECT_EQ("function(\"unterminated,\n" 12023 " OtherParameter);", 12024 format("function( \"unterminated,\n" 12025 " OtherParameter);")); 12026 } 12027 12028 TEST_F(FormatTest, DoesNotTryToParseUDLiteralsInPreCpp11Code) { 12029 FormatStyle Style = getLLVMStyle(); 12030 Style.Standard = FormatStyle::LS_Cpp03; 12031 EXPECT_EQ("#define x(_a) printf(\"foo\" _a);", 12032 format("#define x(_a) printf(\"foo\"_a);", Style)); 12033 } 12034 12035 TEST_F(FormatTest, CppLexVersion) { 12036 FormatStyle Style = getLLVMStyle(); 12037 // Formatting of x * y differs if x is a type. 12038 verifyFormat("void foo() { MACRO(a * b); }", Style); 12039 verifyFormat("void foo() { MACRO(int *b); }", Style); 12040 12041 // LLVM style uses latest lexer. 12042 verifyFormat("void foo() { MACRO(char8_t *b); }", Style); 12043 Style.Standard = FormatStyle::LS_Cpp17; 12044 // But in c++17, char8_t isn't a keyword. 12045 verifyFormat("void foo() { MACRO(char8_t * b); }", Style); 12046 } 12047 12048 TEST_F(FormatTest, UnderstandsCpp1y) { verifyFormat("int bi{1'000'000};"); } 12049 12050 TEST_F(FormatTest, BreakStringLiteralsBeforeUnbreakableTokenSequence) { 12051 EXPECT_EQ("someFunction(\"aaabbbcccd\"\n" 12052 " \"ddeeefff\");", 12053 format("someFunction(\"aaabbbcccdddeeefff\");", 12054 getLLVMStyleWithColumns(25))); 12055 EXPECT_EQ("someFunction1234567890(\n" 12056 " \"aaabbbcccdddeeefff\");", 12057 format("someFunction1234567890(\"aaabbbcccdddeeefff\");", 12058 getLLVMStyleWithColumns(26))); 12059 EXPECT_EQ("someFunction1234567890(\n" 12060 " \"aaabbbcccdddeeeff\"\n" 12061 " \"f\");", 12062 format("someFunction1234567890(\"aaabbbcccdddeeefff\");", 12063 getLLVMStyleWithColumns(25))); 12064 EXPECT_EQ("someFunction1234567890(\n" 12065 " \"aaabbbcccdddeeeff\"\n" 12066 " \"f\");", 12067 format("someFunction1234567890(\"aaabbbcccdddeeefff\");", 12068 getLLVMStyleWithColumns(24))); 12069 EXPECT_EQ("someFunction(\n" 12070 " \"aaabbbcc ddde \"\n" 12071 " \"efff\");", 12072 format("someFunction(\"aaabbbcc ddde efff\");", 12073 getLLVMStyleWithColumns(25))); 12074 EXPECT_EQ("someFunction(\"aaabbbccc \"\n" 12075 " \"ddeeefff\");", 12076 format("someFunction(\"aaabbbccc ddeeefff\");", 12077 getLLVMStyleWithColumns(25))); 12078 EXPECT_EQ("someFunction1234567890(\n" 12079 " \"aaabb \"\n" 12080 " \"cccdddeeefff\");", 12081 format("someFunction1234567890(\"aaabb cccdddeeefff\");", 12082 getLLVMStyleWithColumns(25))); 12083 EXPECT_EQ("#define A \\\n" 12084 " string s = \\\n" 12085 " \"123456789\" \\\n" 12086 " \"0\"; \\\n" 12087 " int i;", 12088 format("#define A string s = \"1234567890\"; int i;", 12089 getLLVMStyleWithColumns(20))); 12090 EXPECT_EQ("someFunction(\n" 12091 " \"aaabbbcc \"\n" 12092 " \"dddeeefff\");", 12093 format("someFunction(\"aaabbbcc dddeeefff\");", 12094 getLLVMStyleWithColumns(25))); 12095 } 12096 12097 TEST_F(FormatTest, DoNotBreakStringLiteralsInEscapeSequence) { 12098 EXPECT_EQ("\"\\a\"", format("\"\\a\"", getLLVMStyleWithColumns(3))); 12099 EXPECT_EQ("\"\\\"", format("\"\\\"", getLLVMStyleWithColumns(2))); 12100 EXPECT_EQ("\"test\"\n" 12101 "\"\\n\"", 12102 format("\"test\\n\"", getLLVMStyleWithColumns(7))); 12103 EXPECT_EQ("\"tes\\\\\"\n" 12104 "\"n\"", 12105 format("\"tes\\\\n\"", getLLVMStyleWithColumns(7))); 12106 EXPECT_EQ("\"\\\\\\\\\"\n" 12107 "\"\\n\"", 12108 format("\"\\\\\\\\\\n\"", getLLVMStyleWithColumns(7))); 12109 EXPECT_EQ("\"\\uff01\"", format("\"\\uff01\"", getLLVMStyleWithColumns(7))); 12110 EXPECT_EQ("\"\\uff01\"\n" 12111 "\"test\"", 12112 format("\"\\uff01test\"", getLLVMStyleWithColumns(8))); 12113 EXPECT_EQ("\"\\Uff01ff02\"", 12114 format("\"\\Uff01ff02\"", getLLVMStyleWithColumns(11))); 12115 EXPECT_EQ("\"\\x000000000001\"\n" 12116 "\"next\"", 12117 format("\"\\x000000000001next\"", getLLVMStyleWithColumns(16))); 12118 EXPECT_EQ("\"\\x000000000001next\"", 12119 format("\"\\x000000000001next\"", getLLVMStyleWithColumns(15))); 12120 EXPECT_EQ("\"\\x000000000001\"", 12121 format("\"\\x000000000001\"", getLLVMStyleWithColumns(7))); 12122 EXPECT_EQ("\"test\"\n" 12123 "\"\\000000\"\n" 12124 "\"000001\"", 12125 format("\"test\\000000000001\"", getLLVMStyleWithColumns(9))); 12126 EXPECT_EQ("\"test\\000\"\n" 12127 "\"00000000\"\n" 12128 "\"1\"", 12129 format("\"test\\000000000001\"", getLLVMStyleWithColumns(10))); 12130 } 12131 12132 TEST_F(FormatTest, DoNotCreateUnreasonableUnwrappedLines) { 12133 verifyFormat("void f() {\n" 12134 " return g() {}\n" 12135 " void h() {}"); 12136 verifyFormat("int a[] = {void forgot_closing_brace(){f();\n" 12137 "g();\n" 12138 "}"); 12139 } 12140 12141 TEST_F(FormatTest, DoNotPrematurelyEndUnwrappedLineForReturnStatements) { 12142 verifyFormat( 12143 "void f() { return C{param1, param2}.SomeCall(param1, param2); }"); 12144 } 12145 12146 TEST_F(FormatTest, FormatsClosingBracesInEmptyNestedBlocks) { 12147 verifyFormat("class X {\n" 12148 " void f() {\n" 12149 " }\n" 12150 "};", 12151 getLLVMStyleWithColumns(12)); 12152 } 12153 12154 TEST_F(FormatTest, ConfigurableIndentWidth) { 12155 FormatStyle EightIndent = getLLVMStyleWithColumns(18); 12156 EightIndent.IndentWidth = 8; 12157 EightIndent.ContinuationIndentWidth = 8; 12158 verifyFormat("void f() {\n" 12159 " someFunction();\n" 12160 " if (true) {\n" 12161 " f();\n" 12162 " }\n" 12163 "}", 12164 EightIndent); 12165 verifyFormat("class X {\n" 12166 " void f() {\n" 12167 " }\n" 12168 "};", 12169 EightIndent); 12170 verifyFormat("int x[] = {\n" 12171 " call(),\n" 12172 " call()};", 12173 EightIndent); 12174 } 12175 12176 TEST_F(FormatTest, ConfigurableFunctionDeclarationIndentAfterType) { 12177 verifyFormat("double\n" 12178 "f();", 12179 getLLVMStyleWithColumns(8)); 12180 } 12181 12182 TEST_F(FormatTest, ConfigurableUseOfTab) { 12183 FormatStyle Tab = getLLVMStyleWithColumns(42); 12184 Tab.IndentWidth = 8; 12185 Tab.UseTab = FormatStyle::UT_Always; 12186 Tab.AlignEscapedNewlines = FormatStyle::ENAS_Left; 12187 12188 EXPECT_EQ("if (aaaaaaaa && // q\n" 12189 " bb)\t\t// w\n" 12190 "\t;", 12191 format("if (aaaaaaaa &&// q\n" 12192 "bb)// w\n" 12193 ";", 12194 Tab)); 12195 EXPECT_EQ("if (aaa && bbb) // w\n" 12196 "\t;", 12197 format("if(aaa&&bbb)// w\n" 12198 ";", 12199 Tab)); 12200 12201 verifyFormat("class X {\n" 12202 "\tvoid f() {\n" 12203 "\t\tsomeFunction(parameter1,\n" 12204 "\t\t\t parameter2);\n" 12205 "\t}\n" 12206 "};", 12207 Tab); 12208 verifyFormat("#define A \\\n" 12209 "\tvoid f() { \\\n" 12210 "\t\tsomeFunction( \\\n" 12211 "\t\t parameter1, \\\n" 12212 "\t\t parameter2); \\\n" 12213 "\t}", 12214 Tab); 12215 verifyFormat("int a;\t // x\n" 12216 "int bbbbbbbb; // x\n", 12217 Tab); 12218 12219 Tab.TabWidth = 4; 12220 Tab.IndentWidth = 8; 12221 verifyFormat("class TabWidth4Indent8 {\n" 12222 "\t\tvoid f() {\n" 12223 "\t\t\t\tsomeFunction(parameter1,\n" 12224 "\t\t\t\t\t\t\t parameter2);\n" 12225 "\t\t}\n" 12226 "};", 12227 Tab); 12228 12229 Tab.TabWidth = 4; 12230 Tab.IndentWidth = 4; 12231 verifyFormat("class TabWidth4Indent4 {\n" 12232 "\tvoid f() {\n" 12233 "\t\tsomeFunction(parameter1,\n" 12234 "\t\t\t\t\t parameter2);\n" 12235 "\t}\n" 12236 "};", 12237 Tab); 12238 12239 Tab.TabWidth = 8; 12240 Tab.IndentWidth = 4; 12241 verifyFormat("class TabWidth8Indent4 {\n" 12242 " void f() {\n" 12243 "\tsomeFunction(parameter1,\n" 12244 "\t\t parameter2);\n" 12245 " }\n" 12246 "};", 12247 Tab); 12248 12249 Tab.TabWidth = 8; 12250 Tab.IndentWidth = 8; 12251 EXPECT_EQ("/*\n" 12252 "\t a\t\tcomment\n" 12253 "\t in multiple lines\n" 12254 " */", 12255 format(" /*\t \t \n" 12256 " \t \t a\t\tcomment\t \t\n" 12257 " \t \t in multiple lines\t\n" 12258 " \t */", 12259 Tab)); 12260 12261 Tab.UseTab = FormatStyle::UT_ForIndentation; 12262 verifyFormat("{\n" 12263 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 12264 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 12265 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 12266 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 12267 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 12268 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 12269 "};", 12270 Tab); 12271 verifyFormat("enum AA {\n" 12272 "\ta1, // Force multiple lines\n" 12273 "\ta2,\n" 12274 "\ta3\n" 12275 "};", 12276 Tab); 12277 EXPECT_EQ("if (aaaaaaaa && // q\n" 12278 " bb) // w\n" 12279 "\t;", 12280 format("if (aaaaaaaa &&// q\n" 12281 "bb)// w\n" 12282 ";", 12283 Tab)); 12284 verifyFormat("class X {\n" 12285 "\tvoid f() {\n" 12286 "\t\tsomeFunction(parameter1,\n" 12287 "\t\t parameter2);\n" 12288 "\t}\n" 12289 "};", 12290 Tab); 12291 verifyFormat("{\n" 12292 "\tQ(\n" 12293 "\t {\n" 12294 "\t\t int a;\n" 12295 "\t\t someFunction(aaaaaaaa,\n" 12296 "\t\t bbbbbbb);\n" 12297 "\t },\n" 12298 "\t p);\n" 12299 "}", 12300 Tab); 12301 EXPECT_EQ("{\n" 12302 "\t/* aaaa\n" 12303 "\t bbbb */\n" 12304 "}", 12305 format("{\n" 12306 "/* aaaa\n" 12307 " bbbb */\n" 12308 "}", 12309 Tab)); 12310 EXPECT_EQ("{\n" 12311 "\t/*\n" 12312 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 12313 "\t bbbbbbbbbbbbb\n" 12314 "\t*/\n" 12315 "}", 12316 format("{\n" 12317 "/*\n" 12318 " aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 12319 "*/\n" 12320 "}", 12321 Tab)); 12322 EXPECT_EQ("{\n" 12323 "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 12324 "\t// bbbbbbbbbbbbb\n" 12325 "}", 12326 format("{\n" 12327 "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 12328 "}", 12329 Tab)); 12330 EXPECT_EQ("{\n" 12331 "\t/*\n" 12332 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 12333 "\t bbbbbbbbbbbbb\n" 12334 "\t*/\n" 12335 "}", 12336 format("{\n" 12337 "\t/*\n" 12338 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 12339 "\t*/\n" 12340 "}", 12341 Tab)); 12342 EXPECT_EQ("{\n" 12343 "\t/*\n" 12344 "\n" 12345 "\t*/\n" 12346 "}", 12347 format("{\n" 12348 "\t/*\n" 12349 "\n" 12350 "\t*/\n" 12351 "}", 12352 Tab)); 12353 EXPECT_EQ("{\n" 12354 "\t/*\n" 12355 " asdf\n" 12356 "\t*/\n" 12357 "}", 12358 format("{\n" 12359 "\t/*\n" 12360 " asdf\n" 12361 "\t*/\n" 12362 "}", 12363 Tab)); 12364 12365 Tab.UseTab = FormatStyle::UT_Never; 12366 EXPECT_EQ("/*\n" 12367 " a\t\tcomment\n" 12368 " in multiple lines\n" 12369 " */", 12370 format(" /*\t \t \n" 12371 " \t \t a\t\tcomment\t \t\n" 12372 " \t \t in multiple lines\t\n" 12373 " \t */", 12374 Tab)); 12375 EXPECT_EQ("/* some\n" 12376 " comment */", 12377 format(" \t \t /* some\n" 12378 " \t \t comment */", 12379 Tab)); 12380 EXPECT_EQ("int a; /* some\n" 12381 " comment */", 12382 format(" \t \t int a; /* some\n" 12383 " \t \t comment */", 12384 Tab)); 12385 12386 EXPECT_EQ("int a; /* some\n" 12387 "comment */", 12388 format(" \t \t int\ta; /* some\n" 12389 " \t \t comment */", 12390 Tab)); 12391 EXPECT_EQ("f(\"\t\t\"); /* some\n" 12392 " comment */", 12393 format(" \t \t f(\"\t\t\"); /* some\n" 12394 " \t \t comment */", 12395 Tab)); 12396 EXPECT_EQ("{\n" 12397 " /*\n" 12398 " * Comment\n" 12399 " */\n" 12400 " int i;\n" 12401 "}", 12402 format("{\n" 12403 "\t/*\n" 12404 "\t * Comment\n" 12405 "\t */\n" 12406 "\t int i;\n" 12407 "}", 12408 Tab)); 12409 12410 Tab.UseTab = FormatStyle::UT_ForContinuationAndIndentation; 12411 Tab.TabWidth = 8; 12412 Tab.IndentWidth = 8; 12413 EXPECT_EQ("if (aaaaaaaa && // q\n" 12414 " bb) // w\n" 12415 "\t;", 12416 format("if (aaaaaaaa &&// q\n" 12417 "bb)// w\n" 12418 ";", 12419 Tab)); 12420 EXPECT_EQ("if (aaa && bbb) // w\n" 12421 "\t;", 12422 format("if(aaa&&bbb)// w\n" 12423 ";", 12424 Tab)); 12425 verifyFormat("class X {\n" 12426 "\tvoid f() {\n" 12427 "\t\tsomeFunction(parameter1,\n" 12428 "\t\t\t parameter2);\n" 12429 "\t}\n" 12430 "};", 12431 Tab); 12432 verifyFormat("#define A \\\n" 12433 "\tvoid f() { \\\n" 12434 "\t\tsomeFunction( \\\n" 12435 "\t\t parameter1, \\\n" 12436 "\t\t parameter2); \\\n" 12437 "\t}", 12438 Tab); 12439 Tab.TabWidth = 4; 12440 Tab.IndentWidth = 8; 12441 verifyFormat("class TabWidth4Indent8 {\n" 12442 "\t\tvoid f() {\n" 12443 "\t\t\t\tsomeFunction(parameter1,\n" 12444 "\t\t\t\t\t\t\t parameter2);\n" 12445 "\t\t}\n" 12446 "};", 12447 Tab); 12448 Tab.TabWidth = 4; 12449 Tab.IndentWidth = 4; 12450 verifyFormat("class TabWidth4Indent4 {\n" 12451 "\tvoid f() {\n" 12452 "\t\tsomeFunction(parameter1,\n" 12453 "\t\t\t\t\t parameter2);\n" 12454 "\t}\n" 12455 "};", 12456 Tab); 12457 Tab.TabWidth = 8; 12458 Tab.IndentWidth = 4; 12459 verifyFormat("class TabWidth8Indent4 {\n" 12460 " void f() {\n" 12461 "\tsomeFunction(parameter1,\n" 12462 "\t\t parameter2);\n" 12463 " }\n" 12464 "};", 12465 Tab); 12466 Tab.TabWidth = 8; 12467 Tab.IndentWidth = 8; 12468 EXPECT_EQ("/*\n" 12469 "\t a\t\tcomment\n" 12470 "\t in multiple lines\n" 12471 " */", 12472 format(" /*\t \t \n" 12473 " \t \t a\t\tcomment\t \t\n" 12474 " \t \t in multiple lines\t\n" 12475 " \t */", 12476 Tab)); 12477 verifyFormat("{\n" 12478 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 12479 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 12480 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 12481 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 12482 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 12483 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 12484 "};", 12485 Tab); 12486 verifyFormat("enum AA {\n" 12487 "\ta1, // Force multiple lines\n" 12488 "\ta2,\n" 12489 "\ta3\n" 12490 "};", 12491 Tab); 12492 EXPECT_EQ("if (aaaaaaaa && // q\n" 12493 " bb) // w\n" 12494 "\t;", 12495 format("if (aaaaaaaa &&// q\n" 12496 "bb)// w\n" 12497 ";", 12498 Tab)); 12499 verifyFormat("class X {\n" 12500 "\tvoid f() {\n" 12501 "\t\tsomeFunction(parameter1,\n" 12502 "\t\t\t parameter2);\n" 12503 "\t}\n" 12504 "};", 12505 Tab); 12506 verifyFormat("{\n" 12507 "\tQ(\n" 12508 "\t {\n" 12509 "\t\t int a;\n" 12510 "\t\t someFunction(aaaaaaaa,\n" 12511 "\t\t\t\t bbbbbbb);\n" 12512 "\t },\n" 12513 "\t p);\n" 12514 "}", 12515 Tab); 12516 EXPECT_EQ("{\n" 12517 "\t/* aaaa\n" 12518 "\t bbbb */\n" 12519 "}", 12520 format("{\n" 12521 "/* aaaa\n" 12522 " bbbb */\n" 12523 "}", 12524 Tab)); 12525 EXPECT_EQ("{\n" 12526 "\t/*\n" 12527 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 12528 "\t bbbbbbbbbbbbb\n" 12529 "\t*/\n" 12530 "}", 12531 format("{\n" 12532 "/*\n" 12533 " aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 12534 "*/\n" 12535 "}", 12536 Tab)); 12537 EXPECT_EQ("{\n" 12538 "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 12539 "\t// bbbbbbbbbbbbb\n" 12540 "}", 12541 format("{\n" 12542 "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 12543 "}", 12544 Tab)); 12545 EXPECT_EQ("{\n" 12546 "\t/*\n" 12547 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 12548 "\t bbbbbbbbbbbbb\n" 12549 "\t*/\n" 12550 "}", 12551 format("{\n" 12552 "\t/*\n" 12553 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 12554 "\t*/\n" 12555 "}", 12556 Tab)); 12557 EXPECT_EQ("{\n" 12558 "\t/*\n" 12559 "\n" 12560 "\t*/\n" 12561 "}", 12562 format("{\n" 12563 "\t/*\n" 12564 "\n" 12565 "\t*/\n" 12566 "}", 12567 Tab)); 12568 EXPECT_EQ("{\n" 12569 "\t/*\n" 12570 " asdf\n" 12571 "\t*/\n" 12572 "}", 12573 format("{\n" 12574 "\t/*\n" 12575 " asdf\n" 12576 "\t*/\n" 12577 "}", 12578 Tab)); 12579 EXPECT_EQ("/* some\n" 12580 " comment */", 12581 format(" \t \t /* some\n" 12582 " \t \t comment */", 12583 Tab)); 12584 EXPECT_EQ("int a; /* some\n" 12585 " comment */", 12586 format(" \t \t int a; /* some\n" 12587 " \t \t comment */", 12588 Tab)); 12589 EXPECT_EQ("int a; /* some\n" 12590 "comment */", 12591 format(" \t \t int\ta; /* some\n" 12592 " \t \t comment */", 12593 Tab)); 12594 EXPECT_EQ("f(\"\t\t\"); /* some\n" 12595 " comment */", 12596 format(" \t \t f(\"\t\t\"); /* some\n" 12597 " \t \t comment */", 12598 Tab)); 12599 EXPECT_EQ("{\n" 12600 "\t/*\n" 12601 "\t * Comment\n" 12602 "\t */\n" 12603 "\tint i;\n" 12604 "}", 12605 format("{\n" 12606 "\t/*\n" 12607 "\t * Comment\n" 12608 "\t */\n" 12609 "\t int i;\n" 12610 "}", 12611 Tab)); 12612 Tab.TabWidth = 2; 12613 Tab.IndentWidth = 2; 12614 EXPECT_EQ("{\n" 12615 "\t/* aaaa\n" 12616 "\t\t bbbb */\n" 12617 "}", 12618 format("{\n" 12619 "/* aaaa\n" 12620 "\t bbbb */\n" 12621 "}", 12622 Tab)); 12623 EXPECT_EQ("{\n" 12624 "\t/*\n" 12625 "\t\taaaaaaaaaaaaaaaaaaaaaaaaaa\n" 12626 "\t\tbbbbbbbbbbbbb\n" 12627 "\t*/\n" 12628 "}", 12629 format("{\n" 12630 "/*\n" 12631 "\taaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 12632 "*/\n" 12633 "}", 12634 Tab)); 12635 Tab.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive; 12636 Tab.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 12637 Tab.TabWidth = 4; 12638 Tab.IndentWidth = 4; 12639 verifyFormat("class Assign {\n" 12640 "\tvoid f() {\n" 12641 "\t\tint x = 123;\n" 12642 "\t\tint random = 4;\n" 12643 "\t\tstd::string alphabet =\n" 12644 "\t\t\t\"abcdefghijklmnopqrstuvwxyz\";\n" 12645 "\t}\n" 12646 "};", 12647 Tab); 12648 12649 Tab.UseTab = FormatStyle::UT_AlignWithSpaces; 12650 Tab.TabWidth = 8; 12651 Tab.IndentWidth = 8; 12652 EXPECT_EQ("if (aaaaaaaa && // q\n" 12653 " bb) // w\n" 12654 "\t;", 12655 format("if (aaaaaaaa &&// q\n" 12656 "bb)// w\n" 12657 ";", 12658 Tab)); 12659 EXPECT_EQ("if (aaa && bbb) // w\n" 12660 "\t;", 12661 format("if(aaa&&bbb)// w\n" 12662 ";", 12663 Tab)); 12664 verifyFormat("class X {\n" 12665 "\tvoid f() {\n" 12666 "\t\tsomeFunction(parameter1,\n" 12667 "\t\t parameter2);\n" 12668 "\t}\n" 12669 "};", 12670 Tab); 12671 verifyFormat("#define A \\\n" 12672 "\tvoid f() { \\\n" 12673 "\t\tsomeFunction( \\\n" 12674 "\t\t parameter1, \\\n" 12675 "\t\t parameter2); \\\n" 12676 "\t}", 12677 Tab); 12678 Tab.TabWidth = 4; 12679 Tab.IndentWidth = 8; 12680 verifyFormat("class TabWidth4Indent8 {\n" 12681 "\t\tvoid f() {\n" 12682 "\t\t\t\tsomeFunction(parameter1,\n" 12683 "\t\t\t\t parameter2);\n" 12684 "\t\t}\n" 12685 "};", 12686 Tab); 12687 Tab.TabWidth = 4; 12688 Tab.IndentWidth = 4; 12689 verifyFormat("class TabWidth4Indent4 {\n" 12690 "\tvoid f() {\n" 12691 "\t\tsomeFunction(parameter1,\n" 12692 "\t\t parameter2);\n" 12693 "\t}\n" 12694 "};", 12695 Tab); 12696 Tab.TabWidth = 8; 12697 Tab.IndentWidth = 4; 12698 verifyFormat("class TabWidth8Indent4 {\n" 12699 " void f() {\n" 12700 "\tsomeFunction(parameter1,\n" 12701 "\t parameter2);\n" 12702 " }\n" 12703 "};", 12704 Tab); 12705 Tab.TabWidth = 8; 12706 Tab.IndentWidth = 8; 12707 EXPECT_EQ("/*\n" 12708 " a\t\tcomment\n" 12709 " in multiple lines\n" 12710 " */", 12711 format(" /*\t \t \n" 12712 " \t \t a\t\tcomment\t \t\n" 12713 " \t \t in multiple lines\t\n" 12714 " \t */", 12715 Tab)); 12716 verifyFormat("{\n" 12717 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 12718 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 12719 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 12720 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 12721 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 12722 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 12723 "};", 12724 Tab); 12725 verifyFormat("enum AA {\n" 12726 "\ta1, // Force multiple lines\n" 12727 "\ta2,\n" 12728 "\ta3\n" 12729 "};", 12730 Tab); 12731 EXPECT_EQ("if (aaaaaaaa && // q\n" 12732 " bb) // w\n" 12733 "\t;", 12734 format("if (aaaaaaaa &&// q\n" 12735 "bb)// w\n" 12736 ";", 12737 Tab)); 12738 verifyFormat("class X {\n" 12739 "\tvoid f() {\n" 12740 "\t\tsomeFunction(parameter1,\n" 12741 "\t\t parameter2);\n" 12742 "\t}\n" 12743 "};", 12744 Tab); 12745 verifyFormat("{\n" 12746 "\tQ(\n" 12747 "\t {\n" 12748 "\t\t int a;\n" 12749 "\t\t someFunction(aaaaaaaa,\n" 12750 "\t\t bbbbbbb);\n" 12751 "\t },\n" 12752 "\t p);\n" 12753 "}", 12754 Tab); 12755 EXPECT_EQ("{\n" 12756 "\t/* aaaa\n" 12757 "\t bbbb */\n" 12758 "}", 12759 format("{\n" 12760 "/* aaaa\n" 12761 " bbbb */\n" 12762 "}", 12763 Tab)); 12764 EXPECT_EQ("{\n" 12765 "\t/*\n" 12766 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 12767 "\t bbbbbbbbbbbbb\n" 12768 "\t*/\n" 12769 "}", 12770 format("{\n" 12771 "/*\n" 12772 " aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 12773 "*/\n" 12774 "}", 12775 Tab)); 12776 EXPECT_EQ("{\n" 12777 "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 12778 "\t// bbbbbbbbbbbbb\n" 12779 "}", 12780 format("{\n" 12781 "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 12782 "}", 12783 Tab)); 12784 EXPECT_EQ("{\n" 12785 "\t/*\n" 12786 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 12787 "\t bbbbbbbbbbbbb\n" 12788 "\t*/\n" 12789 "}", 12790 format("{\n" 12791 "\t/*\n" 12792 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 12793 "\t*/\n" 12794 "}", 12795 Tab)); 12796 EXPECT_EQ("{\n" 12797 "\t/*\n" 12798 "\n" 12799 "\t*/\n" 12800 "}", 12801 format("{\n" 12802 "\t/*\n" 12803 "\n" 12804 "\t*/\n" 12805 "}", 12806 Tab)); 12807 EXPECT_EQ("{\n" 12808 "\t/*\n" 12809 " asdf\n" 12810 "\t*/\n" 12811 "}", 12812 format("{\n" 12813 "\t/*\n" 12814 " asdf\n" 12815 "\t*/\n" 12816 "}", 12817 Tab)); 12818 EXPECT_EQ("/* some\n" 12819 " comment */", 12820 format(" \t \t /* some\n" 12821 " \t \t comment */", 12822 Tab)); 12823 EXPECT_EQ("int a; /* some\n" 12824 " comment */", 12825 format(" \t \t int a; /* some\n" 12826 " \t \t comment */", 12827 Tab)); 12828 EXPECT_EQ("int a; /* some\n" 12829 "comment */", 12830 format(" \t \t int\ta; /* some\n" 12831 " \t \t comment */", 12832 Tab)); 12833 EXPECT_EQ("f(\"\t\t\"); /* some\n" 12834 " comment */", 12835 format(" \t \t f(\"\t\t\"); /* some\n" 12836 " \t \t comment */", 12837 Tab)); 12838 EXPECT_EQ("{\n" 12839 "\t/*\n" 12840 "\t * Comment\n" 12841 "\t */\n" 12842 "\tint i;\n" 12843 "}", 12844 format("{\n" 12845 "\t/*\n" 12846 "\t * Comment\n" 12847 "\t */\n" 12848 "\t int i;\n" 12849 "}", 12850 Tab)); 12851 Tab.TabWidth = 2; 12852 Tab.IndentWidth = 2; 12853 EXPECT_EQ("{\n" 12854 "\t/* aaaa\n" 12855 "\t bbbb */\n" 12856 "}", 12857 format("{\n" 12858 "/* aaaa\n" 12859 " bbbb */\n" 12860 "}", 12861 Tab)); 12862 EXPECT_EQ("{\n" 12863 "\t/*\n" 12864 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 12865 "\t bbbbbbbbbbbbb\n" 12866 "\t*/\n" 12867 "}", 12868 format("{\n" 12869 "/*\n" 12870 " aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 12871 "*/\n" 12872 "}", 12873 Tab)); 12874 Tab.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive; 12875 Tab.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 12876 Tab.TabWidth = 4; 12877 Tab.IndentWidth = 4; 12878 verifyFormat("class Assign {\n" 12879 "\tvoid f() {\n" 12880 "\t\tint x = 123;\n" 12881 "\t\tint random = 4;\n" 12882 "\t\tstd::string alphabet =\n" 12883 "\t\t\t\"abcdefghijklmnopqrstuvwxyz\";\n" 12884 "\t}\n" 12885 "};", 12886 Tab); 12887 Tab.AlignOperands = FormatStyle::OAS_Align; 12888 verifyFormat("int aaaaaaaaaa = bbbbbbbbbbbbbbbbbbbb +\n" 12889 " cccccccccccccccccccc;", 12890 Tab); 12891 // no alignment 12892 verifyFormat("int aaaaaaaaaa =\n" 12893 "\tbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;", 12894 Tab); 12895 verifyFormat("return aaaaaaaaaaaaaaaa ? 111111111111111\n" 12896 " : bbbbbbbbbbbbbb ? 222222222222222\n" 12897 " : 333333333333333;", 12898 Tab); 12899 Tab.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 12900 Tab.AlignOperands = FormatStyle::OAS_AlignAfterOperator; 12901 verifyFormat("int aaaaaaaaaa = bbbbbbbbbbbbbbbbbbbb\n" 12902 " + cccccccccccccccccccc;", 12903 Tab); 12904 } 12905 12906 TEST_F(FormatTest, ZeroTabWidth) { 12907 FormatStyle Tab = getLLVMStyleWithColumns(42); 12908 Tab.IndentWidth = 8; 12909 Tab.UseTab = FormatStyle::UT_Never; 12910 Tab.TabWidth = 0; 12911 EXPECT_EQ("void a(){\n" 12912 " // line starts with '\t'\n" 12913 "};", 12914 format("void a(){\n" 12915 "\t// line starts with '\t'\n" 12916 "};", 12917 Tab)); 12918 12919 EXPECT_EQ("void a(){\n" 12920 " // line starts with '\t'\n" 12921 "};", 12922 format("void a(){\n" 12923 "\t\t// line starts with '\t'\n" 12924 "};", 12925 Tab)); 12926 12927 Tab.UseTab = FormatStyle::UT_ForIndentation; 12928 EXPECT_EQ("void a(){\n" 12929 " // line starts with '\t'\n" 12930 "};", 12931 format("void a(){\n" 12932 "\t// line starts with '\t'\n" 12933 "};", 12934 Tab)); 12935 12936 EXPECT_EQ("void a(){\n" 12937 " // line starts with '\t'\n" 12938 "};", 12939 format("void a(){\n" 12940 "\t\t// line starts with '\t'\n" 12941 "};", 12942 Tab)); 12943 12944 Tab.UseTab = FormatStyle::UT_ForContinuationAndIndentation; 12945 EXPECT_EQ("void a(){\n" 12946 " // line starts with '\t'\n" 12947 "};", 12948 format("void a(){\n" 12949 "\t// line starts with '\t'\n" 12950 "};", 12951 Tab)); 12952 12953 EXPECT_EQ("void a(){\n" 12954 " // line starts with '\t'\n" 12955 "};", 12956 format("void a(){\n" 12957 "\t\t// line starts with '\t'\n" 12958 "};", 12959 Tab)); 12960 12961 Tab.UseTab = FormatStyle::UT_AlignWithSpaces; 12962 EXPECT_EQ("void a(){\n" 12963 " // line starts with '\t'\n" 12964 "};", 12965 format("void a(){\n" 12966 "\t// line starts with '\t'\n" 12967 "};", 12968 Tab)); 12969 12970 EXPECT_EQ("void a(){\n" 12971 " // line starts with '\t'\n" 12972 "};", 12973 format("void a(){\n" 12974 "\t\t// line starts with '\t'\n" 12975 "};", 12976 Tab)); 12977 12978 Tab.UseTab = FormatStyle::UT_Always; 12979 EXPECT_EQ("void a(){\n" 12980 "// line starts with '\t'\n" 12981 "};", 12982 format("void a(){\n" 12983 "\t// line starts with '\t'\n" 12984 "};", 12985 Tab)); 12986 12987 EXPECT_EQ("void a(){\n" 12988 "// line starts with '\t'\n" 12989 "};", 12990 format("void a(){\n" 12991 "\t\t// line starts with '\t'\n" 12992 "};", 12993 Tab)); 12994 } 12995 12996 TEST_F(FormatTest, CalculatesOriginalColumn) { 12997 EXPECT_EQ("\"qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n" 12998 "q\"; /* some\n" 12999 " comment */", 13000 format(" \"qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n" 13001 "q\"; /* some\n" 13002 " comment */", 13003 getLLVMStyle())); 13004 EXPECT_EQ("// qqqqqqqqqqqqqqqqqqqqqqqqqq\n" 13005 "/* some\n" 13006 " comment */", 13007 format("// qqqqqqqqqqqqqqqqqqqqqqqqqq\n" 13008 " /* some\n" 13009 " comment */", 13010 getLLVMStyle())); 13011 EXPECT_EQ("// qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n" 13012 "qqq\n" 13013 "/* some\n" 13014 " comment */", 13015 format("// qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n" 13016 "qqq\n" 13017 " /* some\n" 13018 " comment */", 13019 getLLVMStyle())); 13020 EXPECT_EQ("inttt qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\\\n" 13021 "wwww; /* some\n" 13022 " comment */", 13023 format(" inttt qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\\\n" 13024 "wwww; /* some\n" 13025 " comment */", 13026 getLLVMStyle())); 13027 } 13028 13029 TEST_F(FormatTest, ConfigurableSpaceBeforeParens) { 13030 FormatStyle NoSpace = getLLVMStyle(); 13031 NoSpace.SpaceBeforeParens = FormatStyle::SBPO_Never; 13032 13033 verifyFormat("while(true)\n" 13034 " continue;", 13035 NoSpace); 13036 verifyFormat("for(;;)\n" 13037 " continue;", 13038 NoSpace); 13039 verifyFormat("if(true)\n" 13040 " f();\n" 13041 "else if(true)\n" 13042 " f();", 13043 NoSpace); 13044 verifyFormat("do {\n" 13045 " do_something();\n" 13046 "} while(something());", 13047 NoSpace); 13048 verifyFormat("switch(x) {\n" 13049 "default:\n" 13050 " break;\n" 13051 "}", 13052 NoSpace); 13053 verifyFormat("auto i = std::make_unique<int>(5);", NoSpace); 13054 verifyFormat("size_t x = sizeof(x);", NoSpace); 13055 verifyFormat("auto f(int x) -> decltype(x);", NoSpace); 13056 verifyFormat("auto f(int x) -> typeof(x);", NoSpace); 13057 verifyFormat("auto f(int x) -> _Atomic(x);", NoSpace); 13058 verifyFormat("auto f(int x) -> __underlying_type(x);", NoSpace); 13059 verifyFormat("int f(T x) noexcept(x.create());", NoSpace); 13060 verifyFormat("alignas(128) char a[128];", NoSpace); 13061 verifyFormat("size_t x = alignof(MyType);", NoSpace); 13062 verifyFormat("static_assert(sizeof(char) == 1, \"Impossible!\");", NoSpace); 13063 verifyFormat("int f() throw(Deprecated);", NoSpace); 13064 verifyFormat("typedef void (*cb)(int);", NoSpace); 13065 verifyFormat("T A::operator()();", NoSpace); 13066 verifyFormat("X A::operator++(T);", NoSpace); 13067 verifyFormat("auto lambda = []() { return 0; };", NoSpace); 13068 13069 FormatStyle Space = getLLVMStyle(); 13070 Space.SpaceBeforeParens = FormatStyle::SBPO_Always; 13071 13072 verifyFormat("int f ();", Space); 13073 verifyFormat("void f (int a, T b) {\n" 13074 " while (true)\n" 13075 " continue;\n" 13076 "}", 13077 Space); 13078 verifyFormat("if (true)\n" 13079 " f ();\n" 13080 "else if (true)\n" 13081 " f ();", 13082 Space); 13083 verifyFormat("do {\n" 13084 " do_something ();\n" 13085 "} while (something ());", 13086 Space); 13087 verifyFormat("switch (x) {\n" 13088 "default:\n" 13089 " break;\n" 13090 "}", 13091 Space); 13092 verifyFormat("A::A () : a (1) {}", Space); 13093 verifyFormat("void f () __attribute__ ((asdf));", Space); 13094 verifyFormat("*(&a + 1);\n" 13095 "&((&a)[1]);\n" 13096 "a[(b + c) * d];\n" 13097 "(((a + 1) * 2) + 3) * 4;", 13098 Space); 13099 verifyFormat("#define A(x) x", Space); 13100 verifyFormat("#define A (x) x", Space); 13101 verifyFormat("#if defined(x)\n" 13102 "#endif", 13103 Space); 13104 verifyFormat("auto i = std::make_unique<int> (5);", Space); 13105 verifyFormat("size_t x = sizeof (x);", Space); 13106 verifyFormat("auto f (int x) -> decltype (x);", Space); 13107 verifyFormat("auto f (int x) -> typeof (x);", Space); 13108 verifyFormat("auto f (int x) -> _Atomic (x);", Space); 13109 verifyFormat("auto f (int x) -> __underlying_type (x);", Space); 13110 verifyFormat("int f (T x) noexcept (x.create ());", Space); 13111 verifyFormat("alignas (128) char a[128];", Space); 13112 verifyFormat("size_t x = alignof (MyType);", Space); 13113 verifyFormat("static_assert (sizeof (char) == 1, \"Impossible!\");", Space); 13114 verifyFormat("int f () throw (Deprecated);", Space); 13115 verifyFormat("typedef void (*cb) (int);", Space); 13116 verifyFormat("T A::operator() ();", Space); 13117 verifyFormat("X A::operator++ (T);", Space); 13118 verifyFormat("auto lambda = [] () { return 0; };", Space); 13119 verifyFormat("int x = int (y);", Space); 13120 13121 FormatStyle SomeSpace = getLLVMStyle(); 13122 SomeSpace.SpaceBeforeParens = FormatStyle::SBPO_NonEmptyParentheses; 13123 13124 verifyFormat("[]() -> float {}", SomeSpace); 13125 verifyFormat("[] (auto foo) {}", SomeSpace); 13126 verifyFormat("[foo]() -> int {}", SomeSpace); 13127 verifyFormat("int f();", SomeSpace); 13128 verifyFormat("void f (int a, T b) {\n" 13129 " while (true)\n" 13130 " continue;\n" 13131 "}", 13132 SomeSpace); 13133 verifyFormat("if (true)\n" 13134 " f();\n" 13135 "else if (true)\n" 13136 " f();", 13137 SomeSpace); 13138 verifyFormat("do {\n" 13139 " do_something();\n" 13140 "} while (something());", 13141 SomeSpace); 13142 verifyFormat("switch (x) {\n" 13143 "default:\n" 13144 " break;\n" 13145 "}", 13146 SomeSpace); 13147 verifyFormat("A::A() : a (1) {}", SomeSpace); 13148 verifyFormat("void f() __attribute__ ((asdf));", SomeSpace); 13149 verifyFormat("*(&a + 1);\n" 13150 "&((&a)[1]);\n" 13151 "a[(b + c) * d];\n" 13152 "(((a + 1) * 2) + 3) * 4;", 13153 SomeSpace); 13154 verifyFormat("#define A(x) x", SomeSpace); 13155 verifyFormat("#define A (x) x", SomeSpace); 13156 verifyFormat("#if defined(x)\n" 13157 "#endif", 13158 SomeSpace); 13159 verifyFormat("auto i = std::make_unique<int> (5);", SomeSpace); 13160 verifyFormat("size_t x = sizeof (x);", SomeSpace); 13161 verifyFormat("auto f (int x) -> decltype (x);", SomeSpace); 13162 verifyFormat("auto f (int x) -> typeof (x);", SomeSpace); 13163 verifyFormat("auto f (int x) -> _Atomic (x);", SomeSpace); 13164 verifyFormat("auto f (int x) -> __underlying_type (x);", SomeSpace); 13165 verifyFormat("int f (T x) noexcept (x.create());", SomeSpace); 13166 verifyFormat("alignas (128) char a[128];", SomeSpace); 13167 verifyFormat("size_t x = alignof (MyType);", SomeSpace); 13168 verifyFormat("static_assert (sizeof (char) == 1, \"Impossible!\");", 13169 SomeSpace); 13170 verifyFormat("int f() throw (Deprecated);", SomeSpace); 13171 verifyFormat("typedef void (*cb) (int);", SomeSpace); 13172 verifyFormat("T A::operator()();", SomeSpace); 13173 verifyFormat("X A::operator++ (T);", SomeSpace); 13174 verifyFormat("int x = int (y);", SomeSpace); 13175 verifyFormat("auto lambda = []() { return 0; };", SomeSpace); 13176 } 13177 13178 TEST_F(FormatTest, SpaceAfterLogicalNot) { 13179 FormatStyle Spaces = getLLVMStyle(); 13180 Spaces.SpaceAfterLogicalNot = true; 13181 13182 verifyFormat("bool x = ! y", Spaces); 13183 verifyFormat("if (! isFailure())", Spaces); 13184 verifyFormat("if (! (a && b))", Spaces); 13185 verifyFormat("\"Error!\"", Spaces); 13186 verifyFormat("! ! x", Spaces); 13187 } 13188 13189 TEST_F(FormatTest, ConfigurableSpacesInParentheses) { 13190 FormatStyle Spaces = getLLVMStyle(); 13191 13192 Spaces.SpacesInParentheses = true; 13193 verifyFormat("do_something( ::globalVar );", Spaces); 13194 verifyFormat("call( x, y, z );", Spaces); 13195 verifyFormat("call();", Spaces); 13196 verifyFormat("std::function<void( int, int )> callback;", Spaces); 13197 verifyFormat("void inFunction() { std::function<void( int, int )> fct; }", 13198 Spaces); 13199 verifyFormat("while ( (bool)1 )\n" 13200 " continue;", 13201 Spaces); 13202 verifyFormat("for ( ;; )\n" 13203 " continue;", 13204 Spaces); 13205 verifyFormat("if ( true )\n" 13206 " f();\n" 13207 "else if ( true )\n" 13208 " f();", 13209 Spaces); 13210 verifyFormat("do {\n" 13211 " do_something( (int)i );\n" 13212 "} while ( something() );", 13213 Spaces); 13214 verifyFormat("switch ( x ) {\n" 13215 "default:\n" 13216 " break;\n" 13217 "}", 13218 Spaces); 13219 13220 Spaces.SpacesInParentheses = false; 13221 Spaces.SpacesInCStyleCastParentheses = true; 13222 verifyFormat("Type *A = ( Type * )P;", Spaces); 13223 verifyFormat("Type *A = ( vector<Type *, int *> )P;", Spaces); 13224 verifyFormat("x = ( int32 )y;", Spaces); 13225 verifyFormat("int a = ( int )(2.0f);", Spaces); 13226 verifyFormat("#define AA(X) sizeof((( X * )NULL)->a)", Spaces); 13227 verifyFormat("my_int a = ( my_int )sizeof(int);", Spaces); 13228 verifyFormat("#define x (( int )-1)", Spaces); 13229 13230 // Run the first set of tests again with: 13231 Spaces.SpacesInParentheses = false; 13232 Spaces.SpaceInEmptyParentheses = true; 13233 Spaces.SpacesInCStyleCastParentheses = true; 13234 verifyFormat("call(x, y, z);", Spaces); 13235 verifyFormat("call( );", Spaces); 13236 verifyFormat("std::function<void(int, int)> callback;", Spaces); 13237 verifyFormat("while (( bool )1)\n" 13238 " continue;", 13239 Spaces); 13240 verifyFormat("for (;;)\n" 13241 " continue;", 13242 Spaces); 13243 verifyFormat("if (true)\n" 13244 " f( );\n" 13245 "else if (true)\n" 13246 " f( );", 13247 Spaces); 13248 verifyFormat("do {\n" 13249 " do_something(( int )i);\n" 13250 "} while (something( ));", 13251 Spaces); 13252 verifyFormat("switch (x) {\n" 13253 "default:\n" 13254 " break;\n" 13255 "}", 13256 Spaces); 13257 13258 // Run the first set of tests again with: 13259 Spaces.SpaceAfterCStyleCast = true; 13260 verifyFormat("call(x, y, z);", Spaces); 13261 verifyFormat("call( );", Spaces); 13262 verifyFormat("std::function<void(int, int)> callback;", Spaces); 13263 verifyFormat("while (( bool ) 1)\n" 13264 " continue;", 13265 Spaces); 13266 verifyFormat("for (;;)\n" 13267 " continue;", 13268 Spaces); 13269 verifyFormat("if (true)\n" 13270 " f( );\n" 13271 "else if (true)\n" 13272 " f( );", 13273 Spaces); 13274 verifyFormat("do {\n" 13275 " do_something(( int ) i);\n" 13276 "} while (something( ));", 13277 Spaces); 13278 verifyFormat("switch (x) {\n" 13279 "default:\n" 13280 " break;\n" 13281 "}", 13282 Spaces); 13283 13284 // Run subset of tests again with: 13285 Spaces.SpacesInCStyleCastParentheses = false; 13286 Spaces.SpaceAfterCStyleCast = true; 13287 verifyFormat("while ((bool) 1)\n" 13288 " continue;", 13289 Spaces); 13290 verifyFormat("do {\n" 13291 " do_something((int) i);\n" 13292 "} while (something( ));", 13293 Spaces); 13294 13295 verifyFormat("size_t idx = (size_t) (ptr - ((char *) file));", Spaces); 13296 verifyFormat("size_t idx = (size_t) a;", Spaces); 13297 verifyFormat("size_t idx = (size_t) (a - 1);", Spaces); 13298 verifyFormat("size_t idx = (a->*foo)(a - 1);", Spaces); 13299 verifyFormat("size_t idx = (a->foo)(a - 1);", Spaces); 13300 verifyFormat("size_t idx = (*foo)(a - 1);", Spaces); 13301 Spaces.SpaceAfterCStyleCast = false; 13302 verifyFormat("size_t idx = (size_t)(ptr - ((char *)file));", Spaces); 13303 verifyFormat("size_t idx = (size_t)a;", Spaces); 13304 verifyFormat("size_t idx = (size_t)(a - 1);", Spaces); 13305 verifyFormat("size_t idx = (a->*foo)(a - 1);", Spaces); 13306 verifyFormat("size_t idx = (a->foo)(a - 1);", Spaces); 13307 verifyFormat("size_t idx = (*foo)(a - 1);", Spaces); 13308 } 13309 13310 TEST_F(FormatTest, ConfigurableSpacesInSquareBrackets) { 13311 verifyFormat("int a[5];"); 13312 verifyFormat("a[3] += 42;"); 13313 13314 FormatStyle Spaces = getLLVMStyle(); 13315 Spaces.SpacesInSquareBrackets = true; 13316 // Not lambdas. 13317 verifyFormat("int a[ 5 ];", Spaces); 13318 verifyFormat("a[ 3 ] += 42;", Spaces); 13319 verifyFormat("constexpr char hello[]{\"hello\"};", Spaces); 13320 verifyFormat("double &operator[](int i) { return 0; }\n" 13321 "int i;", 13322 Spaces); 13323 verifyFormat("std::unique_ptr<int[]> foo() {}", Spaces); 13324 verifyFormat("int i = a[ a ][ a ]->f();", Spaces); 13325 verifyFormat("int i = (*b)[ a ]->f();", Spaces); 13326 // Lambdas. 13327 verifyFormat("int c = []() -> int { return 2; }();\n", Spaces); 13328 verifyFormat("return [ i, args... ] {};", Spaces); 13329 verifyFormat("int foo = [ &bar ]() {};", Spaces); 13330 verifyFormat("int foo = [ = ]() {};", Spaces); 13331 verifyFormat("int foo = [ & ]() {};", Spaces); 13332 verifyFormat("int foo = [ =, &bar ]() {};", Spaces); 13333 verifyFormat("int foo = [ &bar, = ]() {};", Spaces); 13334 } 13335 13336 TEST_F(FormatTest, ConfigurableSpaceBeforeBrackets) { 13337 FormatStyle NoSpaceStyle = getLLVMStyle(); 13338 verifyFormat("int a[5];", NoSpaceStyle); 13339 verifyFormat("a[3] += 42;", NoSpaceStyle); 13340 13341 verifyFormat("int a[1];", NoSpaceStyle); 13342 verifyFormat("int 1 [a];", NoSpaceStyle); 13343 verifyFormat("int a[1][2];", NoSpaceStyle); 13344 verifyFormat("a[7] = 5;", NoSpaceStyle); 13345 verifyFormat("int a = (f())[23];", NoSpaceStyle); 13346 verifyFormat("f([] {})", NoSpaceStyle); 13347 13348 FormatStyle Space = getLLVMStyle(); 13349 Space.SpaceBeforeSquareBrackets = true; 13350 verifyFormat("int c = []() -> int { return 2; }();\n", Space); 13351 verifyFormat("return [i, args...] {};", Space); 13352 13353 verifyFormat("int a [5];", Space); 13354 verifyFormat("a [3] += 42;", Space); 13355 verifyFormat("constexpr char hello []{\"hello\"};", Space); 13356 verifyFormat("double &operator[](int i) { return 0; }\n" 13357 "int i;", 13358 Space); 13359 verifyFormat("std::unique_ptr<int []> foo() {}", Space); 13360 verifyFormat("int i = a [a][a]->f();", Space); 13361 verifyFormat("int i = (*b) [a]->f();", Space); 13362 13363 verifyFormat("int a [1];", Space); 13364 verifyFormat("int 1 [a];", Space); 13365 verifyFormat("int a [1][2];", Space); 13366 verifyFormat("a [7] = 5;", Space); 13367 verifyFormat("int a = (f()) [23];", Space); 13368 verifyFormat("f([] {})", Space); 13369 } 13370 13371 TEST_F(FormatTest, ConfigurableSpaceBeforeAssignmentOperators) { 13372 verifyFormat("int a = 5;"); 13373 verifyFormat("a += 42;"); 13374 verifyFormat("a or_eq 8;"); 13375 13376 FormatStyle Spaces = getLLVMStyle(); 13377 Spaces.SpaceBeforeAssignmentOperators = false; 13378 verifyFormat("int a= 5;", Spaces); 13379 verifyFormat("a+= 42;", Spaces); 13380 verifyFormat("a or_eq 8;", Spaces); 13381 } 13382 13383 TEST_F(FormatTest, ConfigurableSpaceBeforeColon) { 13384 verifyFormat("class Foo : public Bar {};"); 13385 verifyFormat("Foo::Foo() : foo(1) {}"); 13386 verifyFormat("for (auto a : b) {\n}"); 13387 verifyFormat("int x = a ? b : c;"); 13388 verifyFormat("{\n" 13389 "label0:\n" 13390 " int x = 0;\n" 13391 "}"); 13392 verifyFormat("switch (x) {\n" 13393 "case 1:\n" 13394 "default:\n" 13395 "}"); 13396 verifyFormat("switch (allBraces) {\n" 13397 "case 1: {\n" 13398 " break;\n" 13399 "}\n" 13400 "case 2: {\n" 13401 " [[fallthrough]];\n" 13402 "}\n" 13403 "default: {\n" 13404 " break;\n" 13405 "}\n" 13406 "}"); 13407 13408 FormatStyle CtorInitializerStyle = getLLVMStyleWithColumns(30); 13409 CtorInitializerStyle.SpaceBeforeCtorInitializerColon = false; 13410 verifyFormat("class Foo : public Bar {};", CtorInitializerStyle); 13411 verifyFormat("Foo::Foo(): foo(1) {}", CtorInitializerStyle); 13412 verifyFormat("for (auto a : b) {\n}", CtorInitializerStyle); 13413 verifyFormat("int x = a ? b : c;", CtorInitializerStyle); 13414 verifyFormat("{\n" 13415 "label1:\n" 13416 " int x = 0;\n" 13417 "}", 13418 CtorInitializerStyle); 13419 verifyFormat("switch (x) {\n" 13420 "case 1:\n" 13421 "default:\n" 13422 "}", 13423 CtorInitializerStyle); 13424 verifyFormat("switch (allBraces) {\n" 13425 "case 1: {\n" 13426 " break;\n" 13427 "}\n" 13428 "case 2: {\n" 13429 " [[fallthrough]];\n" 13430 "}\n" 13431 "default: {\n" 13432 " break;\n" 13433 "}\n" 13434 "}", 13435 CtorInitializerStyle); 13436 CtorInitializerStyle.BreakConstructorInitializers = 13437 FormatStyle::BCIS_AfterColon; 13438 verifyFormat("Fooooooooooo::Fooooooooooo():\n" 13439 " aaaaaaaaaaaaaaaa(1),\n" 13440 " bbbbbbbbbbbbbbbb(2) {}", 13441 CtorInitializerStyle); 13442 CtorInitializerStyle.BreakConstructorInitializers = 13443 FormatStyle::BCIS_BeforeComma; 13444 verifyFormat("Fooooooooooo::Fooooooooooo()\n" 13445 " : aaaaaaaaaaaaaaaa(1)\n" 13446 " , bbbbbbbbbbbbbbbb(2) {}", 13447 CtorInitializerStyle); 13448 CtorInitializerStyle.BreakConstructorInitializers = 13449 FormatStyle::BCIS_BeforeColon; 13450 verifyFormat("Fooooooooooo::Fooooooooooo()\n" 13451 " : aaaaaaaaaaaaaaaa(1),\n" 13452 " bbbbbbbbbbbbbbbb(2) {}", 13453 CtorInitializerStyle); 13454 CtorInitializerStyle.ConstructorInitializerIndentWidth = 0; 13455 verifyFormat("Fooooooooooo::Fooooooooooo()\n" 13456 ": aaaaaaaaaaaaaaaa(1),\n" 13457 " bbbbbbbbbbbbbbbb(2) {}", 13458 CtorInitializerStyle); 13459 13460 FormatStyle InheritanceStyle = getLLVMStyleWithColumns(30); 13461 InheritanceStyle.SpaceBeforeInheritanceColon = false; 13462 verifyFormat("class Foo: public Bar {};", InheritanceStyle); 13463 verifyFormat("Foo::Foo() : foo(1) {}", InheritanceStyle); 13464 verifyFormat("for (auto a : b) {\n}", InheritanceStyle); 13465 verifyFormat("int x = a ? b : c;", InheritanceStyle); 13466 verifyFormat("{\n" 13467 "label2:\n" 13468 " int x = 0;\n" 13469 "}", 13470 InheritanceStyle); 13471 verifyFormat("switch (x) {\n" 13472 "case 1:\n" 13473 "default:\n" 13474 "}", 13475 InheritanceStyle); 13476 verifyFormat("switch (allBraces) {\n" 13477 "case 1: {\n" 13478 " break;\n" 13479 "}\n" 13480 "case 2: {\n" 13481 " [[fallthrough]];\n" 13482 "}\n" 13483 "default: {\n" 13484 " break;\n" 13485 "}\n" 13486 "}", 13487 InheritanceStyle); 13488 InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_AfterColon; 13489 verifyFormat("class Foooooooooooooooooooooo:\n" 13490 " public aaaaaaaaaaaaaaaaaa,\n" 13491 " public bbbbbbbbbbbbbbbbbb {\n" 13492 "}", 13493 InheritanceStyle); 13494 InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_BeforeComma; 13495 verifyFormat("class Foooooooooooooooooooooo\n" 13496 " : public aaaaaaaaaaaaaaaaaa\n" 13497 " , public bbbbbbbbbbbbbbbbbb {\n" 13498 "}", 13499 InheritanceStyle); 13500 InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_BeforeColon; 13501 verifyFormat("class Foooooooooooooooooooooo\n" 13502 " : public aaaaaaaaaaaaaaaaaa,\n" 13503 " public bbbbbbbbbbbbbbbbbb {\n" 13504 "}", 13505 InheritanceStyle); 13506 InheritanceStyle.ConstructorInitializerIndentWidth = 0; 13507 verifyFormat("class Foooooooooooooooooooooo\n" 13508 ": public aaaaaaaaaaaaaaaaaa,\n" 13509 " public bbbbbbbbbbbbbbbbbb {}", 13510 InheritanceStyle); 13511 13512 FormatStyle ForLoopStyle = getLLVMStyle(); 13513 ForLoopStyle.SpaceBeforeRangeBasedForLoopColon = false; 13514 verifyFormat("class Foo : public Bar {};", ForLoopStyle); 13515 verifyFormat("Foo::Foo() : foo(1) {}", ForLoopStyle); 13516 verifyFormat("for (auto a: b) {\n}", ForLoopStyle); 13517 verifyFormat("int x = a ? b : c;", ForLoopStyle); 13518 verifyFormat("{\n" 13519 "label2:\n" 13520 " int x = 0;\n" 13521 "}", 13522 ForLoopStyle); 13523 verifyFormat("switch (x) {\n" 13524 "case 1:\n" 13525 "default:\n" 13526 "}", 13527 ForLoopStyle); 13528 verifyFormat("switch (allBraces) {\n" 13529 "case 1: {\n" 13530 " break;\n" 13531 "}\n" 13532 "case 2: {\n" 13533 " [[fallthrough]];\n" 13534 "}\n" 13535 "default: {\n" 13536 " break;\n" 13537 "}\n" 13538 "}", 13539 ForLoopStyle); 13540 13541 FormatStyle CaseStyle = getLLVMStyle(); 13542 CaseStyle.SpaceBeforeCaseColon = true; 13543 verifyFormat("class Foo : public Bar {};", CaseStyle); 13544 verifyFormat("Foo::Foo() : foo(1) {}", CaseStyle); 13545 verifyFormat("for (auto a : b) {\n}", CaseStyle); 13546 verifyFormat("int x = a ? b : c;", CaseStyle); 13547 verifyFormat("switch (x) {\n" 13548 "case 1 :\n" 13549 "default :\n" 13550 "}", 13551 CaseStyle); 13552 verifyFormat("switch (allBraces) {\n" 13553 "case 1 : {\n" 13554 " break;\n" 13555 "}\n" 13556 "case 2 : {\n" 13557 " [[fallthrough]];\n" 13558 "}\n" 13559 "default : {\n" 13560 " break;\n" 13561 "}\n" 13562 "}", 13563 CaseStyle); 13564 13565 FormatStyle NoSpaceStyle = getLLVMStyle(); 13566 EXPECT_EQ(NoSpaceStyle.SpaceBeforeCaseColon, false); 13567 NoSpaceStyle.SpaceBeforeCtorInitializerColon = false; 13568 NoSpaceStyle.SpaceBeforeInheritanceColon = false; 13569 NoSpaceStyle.SpaceBeforeRangeBasedForLoopColon = false; 13570 verifyFormat("class Foo: public Bar {};", NoSpaceStyle); 13571 verifyFormat("Foo::Foo(): foo(1) {}", NoSpaceStyle); 13572 verifyFormat("for (auto a: b) {\n}", NoSpaceStyle); 13573 verifyFormat("int x = a ? b : c;", NoSpaceStyle); 13574 verifyFormat("{\n" 13575 "label3:\n" 13576 " int x = 0;\n" 13577 "}", 13578 NoSpaceStyle); 13579 verifyFormat("switch (x) {\n" 13580 "case 1:\n" 13581 "default:\n" 13582 "}", 13583 NoSpaceStyle); 13584 verifyFormat("switch (allBraces) {\n" 13585 "case 1: {\n" 13586 " break;\n" 13587 "}\n" 13588 "case 2: {\n" 13589 " [[fallthrough]];\n" 13590 "}\n" 13591 "default: {\n" 13592 " break;\n" 13593 "}\n" 13594 "}", 13595 NoSpaceStyle); 13596 13597 FormatStyle InvertedSpaceStyle = getLLVMStyle(); 13598 InvertedSpaceStyle.SpaceBeforeCaseColon = true; 13599 InvertedSpaceStyle.SpaceBeforeCtorInitializerColon = false; 13600 InvertedSpaceStyle.SpaceBeforeInheritanceColon = false; 13601 InvertedSpaceStyle.SpaceBeforeRangeBasedForLoopColon = false; 13602 verifyFormat("class Foo: public Bar {};", InvertedSpaceStyle); 13603 verifyFormat("Foo::Foo(): foo(1) {}", InvertedSpaceStyle); 13604 verifyFormat("for (auto a: b) {\n}", InvertedSpaceStyle); 13605 verifyFormat("int x = a ? b : c;", InvertedSpaceStyle); 13606 verifyFormat("{\n" 13607 "label3:\n" 13608 " int x = 0;\n" 13609 "}", 13610 InvertedSpaceStyle); 13611 verifyFormat("switch (x) {\n" 13612 "case 1 :\n" 13613 "case 2 : {\n" 13614 " break;\n" 13615 "}\n" 13616 "default :\n" 13617 " break;\n" 13618 "}", 13619 InvertedSpaceStyle); 13620 verifyFormat("switch (allBraces) {\n" 13621 "case 1 : {\n" 13622 " break;\n" 13623 "}\n" 13624 "case 2 : {\n" 13625 " [[fallthrough]];\n" 13626 "}\n" 13627 "default : {\n" 13628 " break;\n" 13629 "}\n" 13630 "}", 13631 InvertedSpaceStyle); 13632 } 13633 13634 TEST_F(FormatTest, ConfigurableSpaceAroundPointerQualifiers) { 13635 FormatStyle Style = getLLVMStyle(); 13636 13637 Style.PointerAlignment = FormatStyle::PAS_Left; 13638 Style.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Default; 13639 verifyFormat("void* const* x = NULL;", Style); 13640 13641 #define verifyQualifierSpaces(Code, Pointers, Qualifiers) \ 13642 do { \ 13643 Style.PointerAlignment = FormatStyle::Pointers; \ 13644 Style.SpaceAroundPointerQualifiers = FormatStyle::Qualifiers; \ 13645 verifyFormat(Code, Style); \ 13646 } while (false) 13647 13648 verifyQualifierSpaces("void* const* x = NULL;", PAS_Left, SAPQ_Default); 13649 verifyQualifierSpaces("void *const *x = NULL;", PAS_Right, SAPQ_Default); 13650 verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_Default); 13651 13652 verifyQualifierSpaces("void* const* x = NULL;", PAS_Left, SAPQ_Before); 13653 verifyQualifierSpaces("void * const *x = NULL;", PAS_Right, SAPQ_Before); 13654 verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_Before); 13655 13656 verifyQualifierSpaces("void* const * x = NULL;", PAS_Left, SAPQ_After); 13657 verifyQualifierSpaces("void *const *x = NULL;", PAS_Right, SAPQ_After); 13658 verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_After); 13659 13660 verifyQualifierSpaces("void* const * x = NULL;", PAS_Left, SAPQ_Both); 13661 verifyQualifierSpaces("void * const *x = NULL;", PAS_Right, SAPQ_Both); 13662 verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_Both); 13663 13664 verifyQualifierSpaces("Foo::operator void const*();", PAS_Left, SAPQ_Default); 13665 verifyQualifierSpaces("Foo::operator void const *();", PAS_Right, 13666 SAPQ_Default); 13667 verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle, 13668 SAPQ_Default); 13669 13670 verifyQualifierSpaces("Foo::operator void const*();", PAS_Left, SAPQ_Before); 13671 verifyQualifierSpaces("Foo::operator void const *();", PAS_Right, 13672 SAPQ_Before); 13673 verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle, 13674 SAPQ_Before); 13675 13676 verifyQualifierSpaces("Foo::operator void const *();", PAS_Left, SAPQ_After); 13677 verifyQualifierSpaces("Foo::operator void const *();", PAS_Right, SAPQ_After); 13678 verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle, 13679 SAPQ_After); 13680 13681 verifyQualifierSpaces("Foo::operator void const *();", PAS_Left, SAPQ_Both); 13682 verifyQualifierSpaces("Foo::operator void const *();", PAS_Right, SAPQ_Both); 13683 verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle, SAPQ_Both); 13684 13685 #undef verifyQualifierSpaces 13686 13687 FormatStyle Spaces = getLLVMStyle(); 13688 Spaces.AttributeMacros.push_back("qualified"); 13689 Spaces.PointerAlignment = FormatStyle::PAS_Right; 13690 Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Default; 13691 verifyFormat("SomeType *volatile *a = NULL;", Spaces); 13692 verifyFormat("SomeType *__attribute__((attr)) *a = NULL;", Spaces); 13693 verifyFormat("std::vector<SomeType *const *> x;", Spaces); 13694 verifyFormat("std::vector<SomeType *qualified *> x;", Spaces); 13695 verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces); 13696 Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Before; 13697 verifyFormat("SomeType * volatile *a = NULL;", Spaces); 13698 verifyFormat("SomeType * __attribute__((attr)) *a = NULL;", Spaces); 13699 verifyFormat("std::vector<SomeType * const *> x;", Spaces); 13700 verifyFormat("std::vector<SomeType * qualified *> x;", Spaces); 13701 verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces); 13702 13703 // Check that SAPQ_Before doesn't result in extra spaces for PAS_Left. 13704 Spaces.PointerAlignment = FormatStyle::PAS_Left; 13705 Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Before; 13706 verifyFormat("SomeType* volatile* a = NULL;", Spaces); 13707 verifyFormat("SomeType* __attribute__((attr))* a = NULL;", Spaces); 13708 verifyFormat("std::vector<SomeType* const*> x;", Spaces); 13709 verifyFormat("std::vector<SomeType* qualified*> x;", Spaces); 13710 verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces); 13711 // However, setting it to SAPQ_After should add spaces after __attribute, etc. 13712 Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_After; 13713 verifyFormat("SomeType* volatile * a = NULL;", Spaces); 13714 verifyFormat("SomeType* __attribute__((attr)) * a = NULL;", Spaces); 13715 verifyFormat("std::vector<SomeType* const *> x;", Spaces); 13716 verifyFormat("std::vector<SomeType* qualified *> x;", Spaces); 13717 verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces); 13718 13719 // PAS_Middle should not have any noticeable changes even for SAPQ_Both 13720 Spaces.PointerAlignment = FormatStyle::PAS_Middle; 13721 Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_After; 13722 verifyFormat("SomeType * volatile * a = NULL;", Spaces); 13723 verifyFormat("SomeType * __attribute__((attr)) * a = NULL;", Spaces); 13724 verifyFormat("std::vector<SomeType * const *> x;", Spaces); 13725 verifyFormat("std::vector<SomeType * qualified *> x;", Spaces); 13726 verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces); 13727 } 13728 13729 TEST_F(FormatTest, AlignConsecutiveMacros) { 13730 FormatStyle Style = getLLVMStyle(); 13731 Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive; 13732 Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 13733 Style.AlignConsecutiveMacros = FormatStyle::ACS_None; 13734 13735 verifyFormat("#define a 3\n" 13736 "#define bbbb 4\n" 13737 "#define ccc (5)", 13738 Style); 13739 13740 verifyFormat("#define f(x) (x * x)\n" 13741 "#define fff(x, y, z) (x * y + z)\n" 13742 "#define ffff(x, y) (x - y)", 13743 Style); 13744 13745 verifyFormat("#define foo(x, y) (x + y)\n" 13746 "#define bar (5, 6)(2 + 2)", 13747 Style); 13748 13749 verifyFormat("#define a 3\n" 13750 "#define bbbb 4\n" 13751 "#define ccc (5)\n" 13752 "#define f(x) (x * x)\n" 13753 "#define fff(x, y, z) (x * y + z)\n" 13754 "#define ffff(x, y) (x - y)", 13755 Style); 13756 13757 Style.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive; 13758 verifyFormat("#define a 3\n" 13759 "#define bbbb 4\n" 13760 "#define ccc (5)", 13761 Style); 13762 13763 verifyFormat("#define f(x) (x * x)\n" 13764 "#define fff(x, y, z) (x * y + z)\n" 13765 "#define ffff(x, y) (x - y)", 13766 Style); 13767 13768 verifyFormat("#define foo(x, y) (x + y)\n" 13769 "#define bar (5, 6)(2 + 2)", 13770 Style); 13771 13772 verifyFormat("#define a 3\n" 13773 "#define bbbb 4\n" 13774 "#define ccc (5)\n" 13775 "#define f(x) (x * x)\n" 13776 "#define fff(x, y, z) (x * y + z)\n" 13777 "#define ffff(x, y) (x - y)", 13778 Style); 13779 13780 verifyFormat("#define a 5\n" 13781 "#define foo(x, y) (x + y)\n" 13782 "#define CCC (6)\n" 13783 "auto lambda = []() {\n" 13784 " auto ii = 0;\n" 13785 " float j = 0;\n" 13786 " return 0;\n" 13787 "};\n" 13788 "int i = 0;\n" 13789 "float i2 = 0;\n" 13790 "auto v = type{\n" 13791 " i = 1, //\n" 13792 " (i = 2), //\n" 13793 " i = 3 //\n" 13794 "};", 13795 Style); 13796 13797 Style.AlignConsecutiveMacros = FormatStyle::ACS_None; 13798 Style.ColumnLimit = 20; 13799 13800 verifyFormat("#define a \\\n" 13801 " \"aabbbbbbbbbbbb\"\n" 13802 "#define D \\\n" 13803 " \"aabbbbbbbbbbbb\" \\\n" 13804 " \"ccddeeeeeeeee\"\n" 13805 "#define B \\\n" 13806 " \"QQQQQQQQQQQQQ\" \\\n" 13807 " \"FFFFFFFFFFFFF\" \\\n" 13808 " \"LLLLLLLL\"\n", 13809 Style); 13810 13811 Style.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive; 13812 verifyFormat("#define a \\\n" 13813 " \"aabbbbbbbbbbbb\"\n" 13814 "#define D \\\n" 13815 " \"aabbbbbbbbbbbb\" \\\n" 13816 " \"ccddeeeeeeeee\"\n" 13817 "#define B \\\n" 13818 " \"QQQQQQQQQQQQQ\" \\\n" 13819 " \"FFFFFFFFFFFFF\" \\\n" 13820 " \"LLLLLLLL\"\n", 13821 Style); 13822 13823 // Test across comments 13824 Style.MaxEmptyLinesToKeep = 10; 13825 Style.ReflowComments = false; 13826 Style.AlignConsecutiveMacros = FormatStyle::ACS_AcrossComments; 13827 EXPECT_EQ("#define a 3\n" 13828 "// line comment\n" 13829 "#define bbbb 4\n" 13830 "#define ccc (5)", 13831 format("#define a 3\n" 13832 "// line comment\n" 13833 "#define bbbb 4\n" 13834 "#define ccc (5)", 13835 Style)); 13836 13837 EXPECT_EQ("#define a 3\n" 13838 "/* block comment */\n" 13839 "#define bbbb 4\n" 13840 "#define ccc (5)", 13841 format("#define a 3\n" 13842 "/* block comment */\n" 13843 "#define bbbb 4\n" 13844 "#define ccc (5)", 13845 Style)); 13846 13847 EXPECT_EQ("#define a 3\n" 13848 "/* multi-line *\n" 13849 " * block comment */\n" 13850 "#define bbbb 4\n" 13851 "#define ccc (5)", 13852 format("#define a 3\n" 13853 "/* multi-line *\n" 13854 " * block comment */\n" 13855 "#define bbbb 4\n" 13856 "#define ccc (5)", 13857 Style)); 13858 13859 EXPECT_EQ("#define a 3\n" 13860 "// multi-line line comment\n" 13861 "//\n" 13862 "#define bbbb 4\n" 13863 "#define ccc (5)", 13864 format("#define a 3\n" 13865 "// multi-line line comment\n" 13866 "//\n" 13867 "#define bbbb 4\n" 13868 "#define ccc (5)", 13869 Style)); 13870 13871 EXPECT_EQ("#define a 3\n" 13872 "// empty lines still break.\n" 13873 "\n" 13874 "#define bbbb 4\n" 13875 "#define ccc (5)", 13876 format("#define a 3\n" 13877 "// empty lines still break.\n" 13878 "\n" 13879 "#define bbbb 4\n" 13880 "#define ccc (5)", 13881 Style)); 13882 13883 // Test across empty lines 13884 Style.AlignConsecutiveMacros = FormatStyle::ACS_AcrossEmptyLines; 13885 EXPECT_EQ("#define a 3\n" 13886 "\n" 13887 "#define bbbb 4\n" 13888 "#define ccc (5)", 13889 format("#define a 3\n" 13890 "\n" 13891 "#define bbbb 4\n" 13892 "#define ccc (5)", 13893 Style)); 13894 13895 EXPECT_EQ("#define a 3\n" 13896 "\n" 13897 "\n" 13898 "\n" 13899 "#define bbbb 4\n" 13900 "#define ccc (5)", 13901 format("#define a 3\n" 13902 "\n" 13903 "\n" 13904 "\n" 13905 "#define bbbb 4\n" 13906 "#define ccc (5)", 13907 Style)); 13908 13909 EXPECT_EQ("#define a 3\n" 13910 "// comments should break alignment\n" 13911 "//\n" 13912 "#define bbbb 4\n" 13913 "#define ccc (5)", 13914 format("#define a 3\n" 13915 "// comments should break alignment\n" 13916 "//\n" 13917 "#define bbbb 4\n" 13918 "#define ccc (5)", 13919 Style)); 13920 13921 // Test across empty lines and comments 13922 Style.AlignConsecutiveMacros = FormatStyle::ACS_AcrossEmptyLinesAndComments; 13923 verifyFormat("#define a 3\n" 13924 "\n" 13925 "// line comment\n" 13926 "#define bbbb 4\n" 13927 "#define ccc (5)", 13928 Style); 13929 13930 EXPECT_EQ("#define a 3\n" 13931 "\n" 13932 "\n" 13933 "/* multi-line *\n" 13934 " * block comment */\n" 13935 "\n" 13936 "\n" 13937 "#define bbbb 4\n" 13938 "#define ccc (5)", 13939 format("#define a 3\n" 13940 "\n" 13941 "\n" 13942 "/* multi-line *\n" 13943 " * block comment */\n" 13944 "\n" 13945 "\n" 13946 "#define bbbb 4\n" 13947 "#define ccc (5)", 13948 Style)); 13949 13950 EXPECT_EQ("#define a 3\n" 13951 "\n" 13952 "\n" 13953 "/* multi-line *\n" 13954 " * block comment */\n" 13955 "\n" 13956 "\n" 13957 "#define bbbb 4\n" 13958 "#define ccc (5)", 13959 format("#define a 3\n" 13960 "\n" 13961 "\n" 13962 "/* multi-line *\n" 13963 " * block comment */\n" 13964 "\n" 13965 "\n" 13966 "#define bbbb 4\n" 13967 "#define ccc (5)", 13968 Style)); 13969 } 13970 13971 TEST_F(FormatTest, AlignConsecutiveAssignmentsAcrossEmptyLines) { 13972 FormatStyle Alignment = getLLVMStyle(); 13973 Alignment.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive; 13974 Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_AcrossEmptyLines; 13975 13976 Alignment.MaxEmptyLinesToKeep = 10; 13977 /* Test alignment across empty lines */ 13978 EXPECT_EQ("int a = 5;\n" 13979 "\n" 13980 "int oneTwoThree = 123;", 13981 format("int a = 5;\n" 13982 "\n" 13983 "int oneTwoThree= 123;", 13984 Alignment)); 13985 EXPECT_EQ("int a = 5;\n" 13986 "int one = 1;\n" 13987 "\n" 13988 "int oneTwoThree = 123;", 13989 format("int a = 5;\n" 13990 "int one = 1;\n" 13991 "\n" 13992 "int oneTwoThree = 123;", 13993 Alignment)); 13994 EXPECT_EQ("int a = 5;\n" 13995 "int one = 1;\n" 13996 "\n" 13997 "int oneTwoThree = 123;\n" 13998 "int oneTwo = 12;", 13999 format("int a = 5;\n" 14000 "int one = 1;\n" 14001 "\n" 14002 "int oneTwoThree = 123;\n" 14003 "int oneTwo = 12;", 14004 Alignment)); 14005 14006 /* Test across comments */ 14007 EXPECT_EQ("int a = 5;\n" 14008 "/* block comment */\n" 14009 "int oneTwoThree = 123;", 14010 format("int a = 5;\n" 14011 "/* block comment */\n" 14012 "int oneTwoThree=123;", 14013 Alignment)); 14014 14015 EXPECT_EQ("int a = 5;\n" 14016 "// line comment\n" 14017 "int oneTwoThree = 123;", 14018 format("int a = 5;\n" 14019 "// line comment\n" 14020 "int oneTwoThree=123;", 14021 Alignment)); 14022 14023 /* Test across comments and newlines */ 14024 EXPECT_EQ("int a = 5;\n" 14025 "\n" 14026 "/* block comment */\n" 14027 "int oneTwoThree = 123;", 14028 format("int a = 5;\n" 14029 "\n" 14030 "/* block comment */\n" 14031 "int oneTwoThree=123;", 14032 Alignment)); 14033 14034 EXPECT_EQ("int a = 5;\n" 14035 "\n" 14036 "// line comment\n" 14037 "int oneTwoThree = 123;", 14038 format("int a = 5;\n" 14039 "\n" 14040 "// line comment\n" 14041 "int oneTwoThree=123;", 14042 Alignment)); 14043 } 14044 14045 TEST_F(FormatTest, AlignConsecutiveDeclarationsAcrossEmptyLinesAndComments) { 14046 FormatStyle Alignment = getLLVMStyle(); 14047 Alignment.AlignConsecutiveDeclarations = 14048 FormatStyle::ACS_AcrossEmptyLinesAndComments; 14049 Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_None; 14050 14051 Alignment.MaxEmptyLinesToKeep = 10; 14052 /* Test alignment across empty lines */ 14053 EXPECT_EQ("int a = 5;\n" 14054 "\n" 14055 "float const oneTwoThree = 123;", 14056 format("int a = 5;\n" 14057 "\n" 14058 "float const oneTwoThree = 123;", 14059 Alignment)); 14060 EXPECT_EQ("int a = 5;\n" 14061 "float const one = 1;\n" 14062 "\n" 14063 "int oneTwoThree = 123;", 14064 format("int a = 5;\n" 14065 "float const one = 1;\n" 14066 "\n" 14067 "int oneTwoThree = 123;", 14068 Alignment)); 14069 14070 /* Test across comments */ 14071 EXPECT_EQ("float const a = 5;\n" 14072 "/* block comment */\n" 14073 "int oneTwoThree = 123;", 14074 format("float const a = 5;\n" 14075 "/* block comment */\n" 14076 "int oneTwoThree=123;", 14077 Alignment)); 14078 14079 EXPECT_EQ("float const a = 5;\n" 14080 "// line comment\n" 14081 "int oneTwoThree = 123;", 14082 format("float const a = 5;\n" 14083 "// line comment\n" 14084 "int oneTwoThree=123;", 14085 Alignment)); 14086 14087 /* Test across comments and newlines */ 14088 EXPECT_EQ("float const a = 5;\n" 14089 "\n" 14090 "/* block comment */\n" 14091 "int oneTwoThree = 123;", 14092 format("float const a = 5;\n" 14093 "\n" 14094 "/* block comment */\n" 14095 "int oneTwoThree=123;", 14096 Alignment)); 14097 14098 EXPECT_EQ("float const a = 5;\n" 14099 "\n" 14100 "// line comment\n" 14101 "int oneTwoThree = 123;", 14102 format("float const a = 5;\n" 14103 "\n" 14104 "// line comment\n" 14105 "int oneTwoThree=123;", 14106 Alignment)); 14107 } 14108 14109 TEST_F(FormatTest, AlignConsecutiveBitFieldsAcrossEmptyLinesAndComments) { 14110 FormatStyle Alignment = getLLVMStyle(); 14111 Alignment.AlignConsecutiveBitFields = 14112 FormatStyle::ACS_AcrossEmptyLinesAndComments; 14113 14114 Alignment.MaxEmptyLinesToKeep = 10; 14115 /* Test alignment across empty lines */ 14116 EXPECT_EQ("int a : 5;\n" 14117 "\n" 14118 "int longbitfield : 6;", 14119 format("int a : 5;\n" 14120 "\n" 14121 "int longbitfield : 6;", 14122 Alignment)); 14123 EXPECT_EQ("int a : 5;\n" 14124 "int one : 1;\n" 14125 "\n" 14126 "int longbitfield : 6;", 14127 format("int a : 5;\n" 14128 "int one : 1;\n" 14129 "\n" 14130 "int longbitfield : 6;", 14131 Alignment)); 14132 14133 /* Test across comments */ 14134 EXPECT_EQ("int a : 5;\n" 14135 "/* block comment */\n" 14136 "int longbitfield : 6;", 14137 format("int a : 5;\n" 14138 "/* block comment */\n" 14139 "int longbitfield : 6;", 14140 Alignment)); 14141 EXPECT_EQ("int a : 5;\n" 14142 "int one : 1;\n" 14143 "// line comment\n" 14144 "int longbitfield : 6;", 14145 format("int a : 5;\n" 14146 "int one : 1;\n" 14147 "// line comment\n" 14148 "int longbitfield : 6;", 14149 Alignment)); 14150 14151 /* Test across comments and newlines */ 14152 EXPECT_EQ("int a : 5;\n" 14153 "/* block comment */\n" 14154 "\n" 14155 "int longbitfield : 6;", 14156 format("int a : 5;\n" 14157 "/* block comment */\n" 14158 "\n" 14159 "int longbitfield : 6;", 14160 Alignment)); 14161 EXPECT_EQ("int a : 5;\n" 14162 "int one : 1;\n" 14163 "\n" 14164 "// line comment\n" 14165 "\n" 14166 "int longbitfield : 6;", 14167 format("int a : 5;\n" 14168 "int one : 1;\n" 14169 "\n" 14170 "// line comment \n" 14171 "\n" 14172 "int longbitfield : 6;", 14173 Alignment)); 14174 } 14175 14176 TEST_F(FormatTest, AlignConsecutiveAssignmentsAcrossComments) { 14177 FormatStyle Alignment = getLLVMStyle(); 14178 Alignment.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive; 14179 Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_AcrossComments; 14180 14181 Alignment.MaxEmptyLinesToKeep = 10; 14182 /* Test alignment across empty lines */ 14183 EXPECT_EQ("int a = 5;\n" 14184 "\n" 14185 "int oneTwoThree = 123;", 14186 format("int a = 5;\n" 14187 "\n" 14188 "int oneTwoThree= 123;", 14189 Alignment)); 14190 EXPECT_EQ("int a = 5;\n" 14191 "int one = 1;\n" 14192 "\n" 14193 "int oneTwoThree = 123;", 14194 format("int a = 5;\n" 14195 "int one = 1;\n" 14196 "\n" 14197 "int oneTwoThree = 123;", 14198 Alignment)); 14199 14200 /* Test across comments */ 14201 EXPECT_EQ("int a = 5;\n" 14202 "/* block comment */\n" 14203 "int oneTwoThree = 123;", 14204 format("int a = 5;\n" 14205 "/* block comment */\n" 14206 "int oneTwoThree=123;", 14207 Alignment)); 14208 14209 EXPECT_EQ("int a = 5;\n" 14210 "// line comment\n" 14211 "int oneTwoThree = 123;", 14212 format("int a = 5;\n" 14213 "// line comment\n" 14214 "int oneTwoThree=123;", 14215 Alignment)); 14216 14217 EXPECT_EQ("int a = 5;\n" 14218 "/*\n" 14219 " * multi-line block comment\n" 14220 " */\n" 14221 "int oneTwoThree = 123;", 14222 format("int a = 5;\n" 14223 "/*\n" 14224 " * multi-line block comment\n" 14225 " */\n" 14226 "int oneTwoThree=123;", 14227 Alignment)); 14228 14229 EXPECT_EQ("int a = 5;\n" 14230 "//\n" 14231 "// multi-line line comment\n" 14232 "//\n" 14233 "int oneTwoThree = 123;", 14234 format("int a = 5;\n" 14235 "//\n" 14236 "// multi-line line comment\n" 14237 "//\n" 14238 "int oneTwoThree=123;", 14239 Alignment)); 14240 14241 /* Test across comments and newlines */ 14242 EXPECT_EQ("int a = 5;\n" 14243 "\n" 14244 "/* block comment */\n" 14245 "int oneTwoThree = 123;", 14246 format("int a = 5;\n" 14247 "\n" 14248 "/* block comment */\n" 14249 "int oneTwoThree=123;", 14250 Alignment)); 14251 14252 EXPECT_EQ("int a = 5;\n" 14253 "\n" 14254 "// line comment\n" 14255 "int oneTwoThree = 123;", 14256 format("int a = 5;\n" 14257 "\n" 14258 "// line comment\n" 14259 "int oneTwoThree=123;", 14260 Alignment)); 14261 } 14262 14263 TEST_F(FormatTest, AlignConsecutiveAssignmentsAcrossEmptyLinesAndComments) { 14264 FormatStyle Alignment = getLLVMStyle(); 14265 Alignment.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive; 14266 Alignment.AlignConsecutiveAssignments = 14267 FormatStyle::ACS_AcrossEmptyLinesAndComments; 14268 verifyFormat("int a = 5;\n" 14269 "int oneTwoThree = 123;", 14270 Alignment); 14271 verifyFormat("int a = method();\n" 14272 "int oneTwoThree = 133;", 14273 Alignment); 14274 verifyFormat("a &= 5;\n" 14275 "bcd *= 5;\n" 14276 "ghtyf += 5;\n" 14277 "dvfvdb -= 5;\n" 14278 "a /= 5;\n" 14279 "vdsvsv %= 5;\n" 14280 "sfdbddfbdfbb ^= 5;\n" 14281 "dvsdsv |= 5;\n" 14282 "int dsvvdvsdvvv = 123;", 14283 Alignment); 14284 verifyFormat("int i = 1, j = 10;\n" 14285 "something = 2000;", 14286 Alignment); 14287 verifyFormat("something = 2000;\n" 14288 "int i = 1, j = 10;\n", 14289 Alignment); 14290 verifyFormat("something = 2000;\n" 14291 "another = 911;\n" 14292 "int i = 1, j = 10;\n" 14293 "oneMore = 1;\n" 14294 "i = 2;", 14295 Alignment); 14296 verifyFormat("int a = 5;\n" 14297 "int one = 1;\n" 14298 "method();\n" 14299 "int oneTwoThree = 123;\n" 14300 "int oneTwo = 12;", 14301 Alignment); 14302 verifyFormat("int oneTwoThree = 123;\n" 14303 "int oneTwo = 12;\n" 14304 "method();\n", 14305 Alignment); 14306 verifyFormat("int oneTwoThree = 123; // comment\n" 14307 "int oneTwo = 12; // comment", 14308 Alignment); 14309 14310 // Bug 25167 14311 /* Uncomment when fixed 14312 verifyFormat("#if A\n" 14313 "#else\n" 14314 "int aaaaaaaa = 12;\n" 14315 "#endif\n" 14316 "#if B\n" 14317 "#else\n" 14318 "int a = 12;\n" 14319 "#endif\n", 14320 Alignment); 14321 verifyFormat("enum foo {\n" 14322 "#if A\n" 14323 "#else\n" 14324 " aaaaaaaa = 12;\n" 14325 "#endif\n" 14326 "#if B\n" 14327 "#else\n" 14328 " a = 12;\n" 14329 "#endif\n" 14330 "};\n", 14331 Alignment); 14332 */ 14333 14334 Alignment.MaxEmptyLinesToKeep = 10; 14335 /* Test alignment across empty lines */ 14336 EXPECT_EQ("int a = 5;\n" 14337 "\n" 14338 "int oneTwoThree = 123;", 14339 format("int a = 5;\n" 14340 "\n" 14341 "int oneTwoThree= 123;", 14342 Alignment)); 14343 EXPECT_EQ("int a = 5;\n" 14344 "int one = 1;\n" 14345 "\n" 14346 "int oneTwoThree = 123;", 14347 format("int a = 5;\n" 14348 "int one = 1;\n" 14349 "\n" 14350 "int oneTwoThree = 123;", 14351 Alignment)); 14352 EXPECT_EQ("int a = 5;\n" 14353 "int one = 1;\n" 14354 "\n" 14355 "int oneTwoThree = 123;\n" 14356 "int oneTwo = 12;", 14357 format("int a = 5;\n" 14358 "int one = 1;\n" 14359 "\n" 14360 "int oneTwoThree = 123;\n" 14361 "int oneTwo = 12;", 14362 Alignment)); 14363 14364 /* Test across comments */ 14365 EXPECT_EQ("int a = 5;\n" 14366 "/* block comment */\n" 14367 "int oneTwoThree = 123;", 14368 format("int a = 5;\n" 14369 "/* block comment */\n" 14370 "int oneTwoThree=123;", 14371 Alignment)); 14372 14373 EXPECT_EQ("int a = 5;\n" 14374 "// line comment\n" 14375 "int oneTwoThree = 123;", 14376 format("int a = 5;\n" 14377 "// line comment\n" 14378 "int oneTwoThree=123;", 14379 Alignment)); 14380 14381 /* Test across comments and newlines */ 14382 EXPECT_EQ("int a = 5;\n" 14383 "\n" 14384 "/* block comment */\n" 14385 "int oneTwoThree = 123;", 14386 format("int a = 5;\n" 14387 "\n" 14388 "/* block comment */\n" 14389 "int oneTwoThree=123;", 14390 Alignment)); 14391 14392 EXPECT_EQ("int a = 5;\n" 14393 "\n" 14394 "// line comment\n" 14395 "int oneTwoThree = 123;", 14396 format("int a = 5;\n" 14397 "\n" 14398 "// line comment\n" 14399 "int oneTwoThree=123;", 14400 Alignment)); 14401 14402 EXPECT_EQ("int a = 5;\n" 14403 "//\n" 14404 "// multi-line line comment\n" 14405 "//\n" 14406 "int oneTwoThree = 123;", 14407 format("int a = 5;\n" 14408 "//\n" 14409 "// multi-line line comment\n" 14410 "//\n" 14411 "int oneTwoThree=123;", 14412 Alignment)); 14413 14414 EXPECT_EQ("int a = 5;\n" 14415 "/*\n" 14416 " * multi-line block comment\n" 14417 " */\n" 14418 "int oneTwoThree = 123;", 14419 format("int a = 5;\n" 14420 "/*\n" 14421 " * multi-line block comment\n" 14422 " */\n" 14423 "int oneTwoThree=123;", 14424 Alignment)); 14425 14426 EXPECT_EQ("int a = 5;\n" 14427 "\n" 14428 "/* block comment */\n" 14429 "\n" 14430 "\n" 14431 "\n" 14432 "int oneTwoThree = 123;", 14433 format("int a = 5;\n" 14434 "\n" 14435 "/* block comment */\n" 14436 "\n" 14437 "\n" 14438 "\n" 14439 "int oneTwoThree=123;", 14440 Alignment)); 14441 14442 EXPECT_EQ("int a = 5;\n" 14443 "\n" 14444 "// line comment\n" 14445 "\n" 14446 "\n" 14447 "\n" 14448 "int oneTwoThree = 123;", 14449 format("int a = 5;\n" 14450 "\n" 14451 "// line comment\n" 14452 "\n" 14453 "\n" 14454 "\n" 14455 "int oneTwoThree=123;", 14456 Alignment)); 14457 14458 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign; 14459 verifyFormat("#define A \\\n" 14460 " int aaaa = 12; \\\n" 14461 " int b = 23; \\\n" 14462 " int ccc = 234; \\\n" 14463 " int dddddddddd = 2345;", 14464 Alignment); 14465 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Left; 14466 verifyFormat("#define A \\\n" 14467 " int aaaa = 12; \\\n" 14468 " int b = 23; \\\n" 14469 " int ccc = 234; \\\n" 14470 " int dddddddddd = 2345;", 14471 Alignment); 14472 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Right; 14473 verifyFormat("#define A " 14474 " \\\n" 14475 " int aaaa = 12; " 14476 " \\\n" 14477 " int b = 23; " 14478 " \\\n" 14479 " int ccc = 234; " 14480 " \\\n" 14481 " int dddddddddd = 2345;", 14482 Alignment); 14483 verifyFormat("void SomeFunction(int parameter = 1, int i = 2, int j = 3, int " 14484 "k = 4, int l = 5,\n" 14485 " int m = 6) {\n" 14486 " int j = 10;\n" 14487 " otherThing = 1;\n" 14488 "}", 14489 Alignment); 14490 verifyFormat("void SomeFunction(int parameter = 0) {\n" 14491 " int i = 1;\n" 14492 " int j = 2;\n" 14493 " int big = 10000;\n" 14494 "}", 14495 Alignment); 14496 verifyFormat("class C {\n" 14497 "public:\n" 14498 " int i = 1;\n" 14499 " virtual void f() = 0;\n" 14500 "};", 14501 Alignment); 14502 verifyFormat("int i = 1;\n" 14503 "if (SomeType t = getSomething()) {\n" 14504 "}\n" 14505 "int j = 2;\n" 14506 "int big = 10000;", 14507 Alignment); 14508 verifyFormat("int j = 7;\n" 14509 "for (int k = 0; k < N; ++k) {\n" 14510 "}\n" 14511 "int j = 2;\n" 14512 "int big = 10000;\n" 14513 "}", 14514 Alignment); 14515 Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 14516 verifyFormat("int i = 1;\n" 14517 "LooooooooooongType loooooooooooooooooooooongVariable\n" 14518 " = someLooooooooooooooooongFunction();\n" 14519 "int j = 2;", 14520 Alignment); 14521 Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_None; 14522 verifyFormat("int i = 1;\n" 14523 "LooooooooooongType loooooooooooooooooooooongVariable =\n" 14524 " someLooooooooooooooooongFunction();\n" 14525 "int j = 2;", 14526 Alignment); 14527 14528 verifyFormat("auto lambda = []() {\n" 14529 " auto i = 0;\n" 14530 " return 0;\n" 14531 "};\n" 14532 "int i = 0;\n" 14533 "auto v = type{\n" 14534 " i = 1, //\n" 14535 " (i = 2), //\n" 14536 " i = 3 //\n" 14537 "};", 14538 Alignment); 14539 14540 verifyFormat( 14541 "int i = 1;\n" 14542 "SomeType a = SomeFunction(looooooooooooooooooooooongParameterA,\n" 14543 " loooooooooooooooooooooongParameterB);\n" 14544 "int j = 2;", 14545 Alignment); 14546 14547 verifyFormat("template <typename T, typename T_0 = very_long_type_name_0,\n" 14548 " typename B = very_long_type_name_1,\n" 14549 " typename T_2 = very_long_type_name_2>\n" 14550 "auto foo() {}\n", 14551 Alignment); 14552 verifyFormat("int a, b = 1;\n" 14553 "int c = 2;\n" 14554 "int dd = 3;\n", 14555 Alignment); 14556 verifyFormat("int aa = ((1 > 2) ? 3 : 4);\n" 14557 "float b[1][] = {{3.f}};\n", 14558 Alignment); 14559 verifyFormat("for (int i = 0; i < 1; i++)\n" 14560 " int x = 1;\n", 14561 Alignment); 14562 verifyFormat("for (i = 0; i < 1; i++)\n" 14563 " x = 1;\n" 14564 "y = 1;\n", 14565 Alignment); 14566 14567 Alignment.ReflowComments = true; 14568 Alignment.ColumnLimit = 50; 14569 EXPECT_EQ("int x = 0;\n" 14570 "int yy = 1; /// specificlennospace\n" 14571 "int zzz = 2;\n", 14572 format("int x = 0;\n" 14573 "int yy = 1; ///specificlennospace\n" 14574 "int zzz = 2;\n", 14575 Alignment)); 14576 } 14577 14578 TEST_F(FormatTest, AlignConsecutiveAssignments) { 14579 FormatStyle Alignment = getLLVMStyle(); 14580 Alignment.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive; 14581 Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_None; 14582 verifyFormat("int a = 5;\n" 14583 "int oneTwoThree = 123;", 14584 Alignment); 14585 verifyFormat("int a = 5;\n" 14586 "int oneTwoThree = 123;", 14587 Alignment); 14588 14589 Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive; 14590 verifyFormat("int a = 5;\n" 14591 "int oneTwoThree = 123;", 14592 Alignment); 14593 verifyFormat("int a = method();\n" 14594 "int oneTwoThree = 133;", 14595 Alignment); 14596 verifyFormat("a &= 5;\n" 14597 "bcd *= 5;\n" 14598 "ghtyf += 5;\n" 14599 "dvfvdb -= 5;\n" 14600 "a /= 5;\n" 14601 "vdsvsv %= 5;\n" 14602 "sfdbddfbdfbb ^= 5;\n" 14603 "dvsdsv |= 5;\n" 14604 "int dsvvdvsdvvv = 123;", 14605 Alignment); 14606 verifyFormat("int i = 1, j = 10;\n" 14607 "something = 2000;", 14608 Alignment); 14609 verifyFormat("something = 2000;\n" 14610 "int i = 1, j = 10;\n", 14611 Alignment); 14612 verifyFormat("something = 2000;\n" 14613 "another = 911;\n" 14614 "int i = 1, j = 10;\n" 14615 "oneMore = 1;\n" 14616 "i = 2;", 14617 Alignment); 14618 verifyFormat("int a = 5;\n" 14619 "int one = 1;\n" 14620 "method();\n" 14621 "int oneTwoThree = 123;\n" 14622 "int oneTwo = 12;", 14623 Alignment); 14624 verifyFormat("int oneTwoThree = 123;\n" 14625 "int oneTwo = 12;\n" 14626 "method();\n", 14627 Alignment); 14628 verifyFormat("int oneTwoThree = 123; // comment\n" 14629 "int oneTwo = 12; // comment", 14630 Alignment); 14631 14632 // Bug 25167 14633 /* Uncomment when fixed 14634 verifyFormat("#if A\n" 14635 "#else\n" 14636 "int aaaaaaaa = 12;\n" 14637 "#endif\n" 14638 "#if B\n" 14639 "#else\n" 14640 "int a = 12;\n" 14641 "#endif\n", 14642 Alignment); 14643 verifyFormat("enum foo {\n" 14644 "#if A\n" 14645 "#else\n" 14646 " aaaaaaaa = 12;\n" 14647 "#endif\n" 14648 "#if B\n" 14649 "#else\n" 14650 " a = 12;\n" 14651 "#endif\n" 14652 "};\n", 14653 Alignment); 14654 */ 14655 14656 EXPECT_EQ("int a = 5;\n" 14657 "\n" 14658 "int oneTwoThree = 123;", 14659 format("int a = 5;\n" 14660 "\n" 14661 "int oneTwoThree= 123;", 14662 Alignment)); 14663 EXPECT_EQ("int a = 5;\n" 14664 "int one = 1;\n" 14665 "\n" 14666 "int oneTwoThree = 123;", 14667 format("int a = 5;\n" 14668 "int one = 1;\n" 14669 "\n" 14670 "int oneTwoThree = 123;", 14671 Alignment)); 14672 EXPECT_EQ("int a = 5;\n" 14673 "int one = 1;\n" 14674 "\n" 14675 "int oneTwoThree = 123;\n" 14676 "int oneTwo = 12;", 14677 format("int a = 5;\n" 14678 "int one = 1;\n" 14679 "\n" 14680 "int oneTwoThree = 123;\n" 14681 "int oneTwo = 12;", 14682 Alignment)); 14683 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign; 14684 verifyFormat("#define A \\\n" 14685 " int aaaa = 12; \\\n" 14686 " int b = 23; \\\n" 14687 " int ccc = 234; \\\n" 14688 " int dddddddddd = 2345;", 14689 Alignment); 14690 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Left; 14691 verifyFormat("#define A \\\n" 14692 " int aaaa = 12; \\\n" 14693 " int b = 23; \\\n" 14694 " int ccc = 234; \\\n" 14695 " int dddddddddd = 2345;", 14696 Alignment); 14697 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Right; 14698 verifyFormat("#define A " 14699 " \\\n" 14700 " int aaaa = 12; " 14701 " \\\n" 14702 " int b = 23; " 14703 " \\\n" 14704 " int ccc = 234; " 14705 " \\\n" 14706 " int dddddddddd = 2345;", 14707 Alignment); 14708 verifyFormat("void SomeFunction(int parameter = 1, int i = 2, int j = 3, int " 14709 "k = 4, int l = 5,\n" 14710 " int m = 6) {\n" 14711 " int j = 10;\n" 14712 " otherThing = 1;\n" 14713 "}", 14714 Alignment); 14715 verifyFormat("void SomeFunction(int parameter = 0) {\n" 14716 " int i = 1;\n" 14717 " int j = 2;\n" 14718 " int big = 10000;\n" 14719 "}", 14720 Alignment); 14721 verifyFormat("class C {\n" 14722 "public:\n" 14723 " int i = 1;\n" 14724 " virtual void f() = 0;\n" 14725 "};", 14726 Alignment); 14727 verifyFormat("int i = 1;\n" 14728 "if (SomeType t = getSomething()) {\n" 14729 "}\n" 14730 "int j = 2;\n" 14731 "int big = 10000;", 14732 Alignment); 14733 verifyFormat("int j = 7;\n" 14734 "for (int k = 0; k < N; ++k) {\n" 14735 "}\n" 14736 "int j = 2;\n" 14737 "int big = 10000;\n" 14738 "}", 14739 Alignment); 14740 Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 14741 verifyFormat("int i = 1;\n" 14742 "LooooooooooongType loooooooooooooooooooooongVariable\n" 14743 " = someLooooooooooooooooongFunction();\n" 14744 "int j = 2;", 14745 Alignment); 14746 Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_None; 14747 verifyFormat("int i = 1;\n" 14748 "LooooooooooongType loooooooooooooooooooooongVariable =\n" 14749 " someLooooooooooooooooongFunction();\n" 14750 "int j = 2;", 14751 Alignment); 14752 14753 verifyFormat("auto lambda = []() {\n" 14754 " auto i = 0;\n" 14755 " return 0;\n" 14756 "};\n" 14757 "int i = 0;\n" 14758 "auto v = type{\n" 14759 " i = 1, //\n" 14760 " (i = 2), //\n" 14761 " i = 3 //\n" 14762 "};", 14763 Alignment); 14764 14765 verifyFormat( 14766 "int i = 1;\n" 14767 "SomeType a = SomeFunction(looooooooooooooooooooooongParameterA,\n" 14768 " loooooooooooooooooooooongParameterB);\n" 14769 "int j = 2;", 14770 Alignment); 14771 14772 verifyFormat("template <typename T, typename T_0 = very_long_type_name_0,\n" 14773 " typename B = very_long_type_name_1,\n" 14774 " typename T_2 = very_long_type_name_2>\n" 14775 "auto foo() {}\n", 14776 Alignment); 14777 verifyFormat("int a, b = 1;\n" 14778 "int c = 2;\n" 14779 "int dd = 3;\n", 14780 Alignment); 14781 verifyFormat("int aa = ((1 > 2) ? 3 : 4);\n" 14782 "float b[1][] = {{3.f}};\n", 14783 Alignment); 14784 verifyFormat("for (int i = 0; i < 1; i++)\n" 14785 " int x = 1;\n", 14786 Alignment); 14787 verifyFormat("for (i = 0; i < 1; i++)\n" 14788 " x = 1;\n" 14789 "y = 1;\n", 14790 Alignment); 14791 14792 Alignment.ReflowComments = true; 14793 Alignment.ColumnLimit = 50; 14794 EXPECT_EQ("int x = 0;\n" 14795 "int yy = 1; /// specificlennospace\n" 14796 "int zzz = 2;\n", 14797 format("int x = 0;\n" 14798 "int yy = 1; ///specificlennospace\n" 14799 "int zzz = 2;\n", 14800 Alignment)); 14801 } 14802 14803 TEST_F(FormatTest, AlignConsecutiveBitFields) { 14804 FormatStyle Alignment = getLLVMStyle(); 14805 Alignment.AlignConsecutiveBitFields = FormatStyle::ACS_Consecutive; 14806 verifyFormat("int const a : 5;\n" 14807 "int oneTwoThree : 23;", 14808 Alignment); 14809 14810 // Initializers are allowed starting with c++2a 14811 verifyFormat("int const a : 5 = 1;\n" 14812 "int oneTwoThree : 23 = 0;", 14813 Alignment); 14814 14815 Alignment.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 14816 verifyFormat("int const a : 5;\n" 14817 "int oneTwoThree : 23;", 14818 Alignment); 14819 14820 verifyFormat("int const a : 5; // comment\n" 14821 "int oneTwoThree : 23; // comment", 14822 Alignment); 14823 14824 verifyFormat("int const a : 5 = 1;\n" 14825 "int oneTwoThree : 23 = 0;", 14826 Alignment); 14827 14828 Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive; 14829 verifyFormat("int const a : 5 = 1;\n" 14830 "int oneTwoThree : 23 = 0;", 14831 Alignment); 14832 verifyFormat("int const a : 5 = {1};\n" 14833 "int oneTwoThree : 23 = 0;", 14834 Alignment); 14835 14836 Alignment.BitFieldColonSpacing = FormatStyle::BFCS_None; 14837 verifyFormat("int const a :5;\n" 14838 "int oneTwoThree:23;", 14839 Alignment); 14840 14841 Alignment.BitFieldColonSpacing = FormatStyle::BFCS_Before; 14842 verifyFormat("int const a :5;\n" 14843 "int oneTwoThree :23;", 14844 Alignment); 14845 14846 Alignment.BitFieldColonSpacing = FormatStyle::BFCS_After; 14847 verifyFormat("int const a : 5;\n" 14848 "int oneTwoThree: 23;", 14849 Alignment); 14850 14851 // Known limitations: ':' is only recognized as a bitfield colon when 14852 // followed by a number. 14853 /* 14854 verifyFormat("int oneTwoThree : SOME_CONSTANT;\n" 14855 "int a : 5;", 14856 Alignment); 14857 */ 14858 } 14859 14860 TEST_F(FormatTest, AlignConsecutiveDeclarations) { 14861 FormatStyle Alignment = getLLVMStyle(); 14862 Alignment.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive; 14863 Alignment.AlignConsecutiveDeclarations = FormatStyle::ACS_None; 14864 verifyFormat("float const a = 5;\n" 14865 "int oneTwoThree = 123;", 14866 Alignment); 14867 verifyFormat("int a = 5;\n" 14868 "float const oneTwoThree = 123;", 14869 Alignment); 14870 14871 Alignment.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 14872 verifyFormat("float const a = 5;\n" 14873 "int oneTwoThree = 123;", 14874 Alignment); 14875 verifyFormat("int a = method();\n" 14876 "float const oneTwoThree = 133;", 14877 Alignment); 14878 verifyFormat("int i = 1, j = 10;\n" 14879 "something = 2000;", 14880 Alignment); 14881 verifyFormat("something = 2000;\n" 14882 "int i = 1, j = 10;\n", 14883 Alignment); 14884 verifyFormat("float something = 2000;\n" 14885 "double another = 911;\n" 14886 "int i = 1, j = 10;\n" 14887 "const int *oneMore = 1;\n" 14888 "unsigned i = 2;", 14889 Alignment); 14890 verifyFormat("float a = 5;\n" 14891 "int one = 1;\n" 14892 "method();\n" 14893 "const double oneTwoThree = 123;\n" 14894 "const unsigned int oneTwo = 12;", 14895 Alignment); 14896 verifyFormat("int oneTwoThree{0}; // comment\n" 14897 "unsigned oneTwo; // comment", 14898 Alignment); 14899 verifyFormat("unsigned int * a;\n" 14900 "int * b;\n" 14901 "unsigned int Const *c;\n" 14902 "unsigned int const *d;\n" 14903 "unsigned int Const &e;\n" 14904 "unsigned int const &f;", 14905 Alignment); 14906 verifyFormat("Const unsigned int *c;\n" 14907 "const unsigned int *d;\n" 14908 "Const unsigned int &e;\n" 14909 "const unsigned int &f;\n" 14910 "const unsigned g;\n" 14911 "Const unsigned h;", 14912 Alignment); 14913 EXPECT_EQ("float const a = 5;\n" 14914 "\n" 14915 "int oneTwoThree = 123;", 14916 format("float const a = 5;\n" 14917 "\n" 14918 "int oneTwoThree= 123;", 14919 Alignment)); 14920 EXPECT_EQ("float a = 5;\n" 14921 "int one = 1;\n" 14922 "\n" 14923 "unsigned oneTwoThree = 123;", 14924 format("float a = 5;\n" 14925 "int one = 1;\n" 14926 "\n" 14927 "unsigned oneTwoThree = 123;", 14928 Alignment)); 14929 EXPECT_EQ("float a = 5;\n" 14930 "int one = 1;\n" 14931 "\n" 14932 "unsigned oneTwoThree = 123;\n" 14933 "int oneTwo = 12;", 14934 format("float a = 5;\n" 14935 "int one = 1;\n" 14936 "\n" 14937 "unsigned oneTwoThree = 123;\n" 14938 "int oneTwo = 12;", 14939 Alignment)); 14940 // Function prototype alignment 14941 verifyFormat("int a();\n" 14942 "double b();", 14943 Alignment); 14944 verifyFormat("int a(int x);\n" 14945 "double b();", 14946 Alignment); 14947 unsigned OldColumnLimit = Alignment.ColumnLimit; 14948 // We need to set ColumnLimit to zero, in order to stress nested alignments, 14949 // otherwise the function parameters will be re-flowed onto a single line. 14950 Alignment.ColumnLimit = 0; 14951 EXPECT_EQ("int a(int x,\n" 14952 " float y);\n" 14953 "double b(int x,\n" 14954 " double y);", 14955 format("int a(int x,\n" 14956 " float y);\n" 14957 "double b(int x,\n" 14958 " double y);", 14959 Alignment)); 14960 // This ensures that function parameters of function declarations are 14961 // correctly indented when their owning functions are indented. 14962 // The failure case here is for 'double y' to not be indented enough. 14963 EXPECT_EQ("double a(int x);\n" 14964 "int b(int y,\n" 14965 " double z);", 14966 format("double a(int x);\n" 14967 "int b(int y,\n" 14968 " double z);", 14969 Alignment)); 14970 // Set ColumnLimit low so that we induce wrapping immediately after 14971 // the function name and opening paren. 14972 Alignment.ColumnLimit = 13; 14973 verifyFormat("int function(\n" 14974 " int x,\n" 14975 " bool y);", 14976 Alignment); 14977 Alignment.ColumnLimit = OldColumnLimit; 14978 // Ensure function pointers don't screw up recursive alignment 14979 verifyFormat("int a(int x, void (*fp)(int y));\n" 14980 "double b();", 14981 Alignment); 14982 Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive; 14983 // Ensure recursive alignment is broken by function braces, so that the 14984 // "a = 1" does not align with subsequent assignments inside the function 14985 // body. 14986 verifyFormat("int func(int a = 1) {\n" 14987 " int b = 2;\n" 14988 " int cc = 3;\n" 14989 "}", 14990 Alignment); 14991 verifyFormat("float something = 2000;\n" 14992 "double another = 911;\n" 14993 "int i = 1, j = 10;\n" 14994 "const int *oneMore = 1;\n" 14995 "unsigned i = 2;", 14996 Alignment); 14997 verifyFormat("int oneTwoThree = {0}; // comment\n" 14998 "unsigned oneTwo = 0; // comment", 14999 Alignment); 15000 // Make sure that scope is correctly tracked, in the absence of braces 15001 verifyFormat("for (int i = 0; i < n; i++)\n" 15002 " j = i;\n" 15003 "double x = 1;\n", 15004 Alignment); 15005 verifyFormat("if (int i = 0)\n" 15006 " j = i;\n" 15007 "double x = 1;\n", 15008 Alignment); 15009 // Ensure operator[] and operator() are comprehended 15010 verifyFormat("struct test {\n" 15011 " long long int foo();\n" 15012 " int operator[](int a);\n" 15013 " double bar();\n" 15014 "};\n", 15015 Alignment); 15016 verifyFormat("struct test {\n" 15017 " long long int foo();\n" 15018 " int operator()(int a);\n" 15019 " double bar();\n" 15020 "};\n", 15021 Alignment); 15022 EXPECT_EQ("void SomeFunction(int parameter = 0) {\n" 15023 " int const i = 1;\n" 15024 " int * j = 2;\n" 15025 " int big = 10000;\n" 15026 "\n" 15027 " unsigned oneTwoThree = 123;\n" 15028 " int oneTwo = 12;\n" 15029 " method();\n" 15030 " float k = 2;\n" 15031 " int ll = 10000;\n" 15032 "}", 15033 format("void SomeFunction(int parameter= 0) {\n" 15034 " int const i= 1;\n" 15035 " int *j=2;\n" 15036 " int big = 10000;\n" 15037 "\n" 15038 "unsigned oneTwoThree =123;\n" 15039 "int oneTwo = 12;\n" 15040 " method();\n" 15041 "float k= 2;\n" 15042 "int ll=10000;\n" 15043 "}", 15044 Alignment)); 15045 Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_None; 15046 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign; 15047 verifyFormat("#define A \\\n" 15048 " int aaaa = 12; \\\n" 15049 " float b = 23; \\\n" 15050 " const int ccc = 234; \\\n" 15051 " unsigned dddddddddd = 2345;", 15052 Alignment); 15053 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Left; 15054 verifyFormat("#define A \\\n" 15055 " int aaaa = 12; \\\n" 15056 " float b = 23; \\\n" 15057 " const int ccc = 234; \\\n" 15058 " unsigned dddddddddd = 2345;", 15059 Alignment); 15060 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Right; 15061 Alignment.ColumnLimit = 30; 15062 verifyFormat("#define A \\\n" 15063 " int aaaa = 12; \\\n" 15064 " float b = 23; \\\n" 15065 " const int ccc = 234; \\\n" 15066 " int dddddddddd = 2345;", 15067 Alignment); 15068 Alignment.ColumnLimit = 80; 15069 verifyFormat("void SomeFunction(int parameter = 1, int i = 2, int j = 3, int " 15070 "k = 4, int l = 5,\n" 15071 " int m = 6) {\n" 15072 " const int j = 10;\n" 15073 " otherThing = 1;\n" 15074 "}", 15075 Alignment); 15076 verifyFormat("void SomeFunction(int parameter = 0) {\n" 15077 " int const i = 1;\n" 15078 " int * j = 2;\n" 15079 " int big = 10000;\n" 15080 "}", 15081 Alignment); 15082 verifyFormat("class C {\n" 15083 "public:\n" 15084 " int i = 1;\n" 15085 " virtual void f() = 0;\n" 15086 "};", 15087 Alignment); 15088 verifyFormat("float i = 1;\n" 15089 "if (SomeType t = getSomething()) {\n" 15090 "}\n" 15091 "const unsigned j = 2;\n" 15092 "int big = 10000;", 15093 Alignment); 15094 verifyFormat("float j = 7;\n" 15095 "for (int k = 0; k < N; ++k) {\n" 15096 "}\n" 15097 "unsigned j = 2;\n" 15098 "int big = 10000;\n" 15099 "}", 15100 Alignment); 15101 Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 15102 verifyFormat("float i = 1;\n" 15103 "LooooooooooongType loooooooooooooooooooooongVariable\n" 15104 " = someLooooooooooooooooongFunction();\n" 15105 "int j = 2;", 15106 Alignment); 15107 Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_None; 15108 verifyFormat("int i = 1;\n" 15109 "LooooooooooongType loooooooooooooooooooooongVariable =\n" 15110 " someLooooooooooooooooongFunction();\n" 15111 "int j = 2;", 15112 Alignment); 15113 15114 Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive; 15115 verifyFormat("auto lambda = []() {\n" 15116 " auto ii = 0;\n" 15117 " float j = 0;\n" 15118 " return 0;\n" 15119 "};\n" 15120 "int i = 0;\n" 15121 "float i2 = 0;\n" 15122 "auto v = type{\n" 15123 " i = 1, //\n" 15124 " (i = 2), //\n" 15125 " i = 3 //\n" 15126 "};", 15127 Alignment); 15128 Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_None; 15129 15130 verifyFormat( 15131 "int i = 1;\n" 15132 "SomeType a = SomeFunction(looooooooooooooooooooooongParameterA,\n" 15133 " loooooooooooooooooooooongParameterB);\n" 15134 "int j = 2;", 15135 Alignment); 15136 15137 // Test interactions with ColumnLimit and AlignConsecutiveAssignments: 15138 // We expect declarations and assignments to align, as long as it doesn't 15139 // exceed the column limit, starting a new alignment sequence whenever it 15140 // happens. 15141 Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive; 15142 Alignment.ColumnLimit = 30; 15143 verifyFormat("float ii = 1;\n" 15144 "unsigned j = 2;\n" 15145 "int someVerylongVariable = 1;\n" 15146 "AnotherLongType ll = 123456;\n" 15147 "VeryVeryLongType k = 2;\n" 15148 "int myvar = 1;", 15149 Alignment); 15150 Alignment.ColumnLimit = 80; 15151 Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_None; 15152 15153 verifyFormat( 15154 "template <typename LongTemplate, typename VeryLongTemplateTypeName,\n" 15155 " typename LongType, typename B>\n" 15156 "auto foo() {}\n", 15157 Alignment); 15158 verifyFormat("float a, b = 1;\n" 15159 "int c = 2;\n" 15160 "int dd = 3;\n", 15161 Alignment); 15162 verifyFormat("int aa = ((1 > 2) ? 3 : 4);\n" 15163 "float b[1][] = {{3.f}};\n", 15164 Alignment); 15165 Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive; 15166 verifyFormat("float a, b = 1;\n" 15167 "int c = 2;\n" 15168 "int dd = 3;\n", 15169 Alignment); 15170 verifyFormat("int aa = ((1 > 2) ? 3 : 4);\n" 15171 "float b[1][] = {{3.f}};\n", 15172 Alignment); 15173 Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_None; 15174 15175 Alignment.ColumnLimit = 30; 15176 Alignment.BinPackParameters = false; 15177 verifyFormat("void foo(float a,\n" 15178 " float b,\n" 15179 " int c,\n" 15180 " uint32_t *d) {\n" 15181 " int * e = 0;\n" 15182 " float f = 0;\n" 15183 " double g = 0;\n" 15184 "}\n" 15185 "void bar(ino_t a,\n" 15186 " int b,\n" 15187 " uint32_t *c,\n" 15188 " bool d) {}\n", 15189 Alignment); 15190 Alignment.BinPackParameters = true; 15191 Alignment.ColumnLimit = 80; 15192 15193 // Bug 33507 15194 Alignment.PointerAlignment = FormatStyle::PAS_Middle; 15195 verifyFormat( 15196 "auto found = range::find_if(vsProducts, [&](auto * aProduct) {\n" 15197 " static const Version verVs2017;\n" 15198 " return true;\n" 15199 "});\n", 15200 Alignment); 15201 Alignment.PointerAlignment = FormatStyle::PAS_Right; 15202 15203 // See llvm.org/PR35641 15204 Alignment.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 15205 verifyFormat("int func() { //\n" 15206 " int b;\n" 15207 " unsigned c;\n" 15208 "}", 15209 Alignment); 15210 15211 // See PR37175 15212 FormatStyle Style = getMozillaStyle(); 15213 Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 15214 EXPECT_EQ("DECOR1 /**/ int8_t /**/ DECOR2 /**/\n" 15215 "foo(int a);", 15216 format("DECOR1 /**/ int8_t /**/ DECOR2 /**/ foo (int a);", Style)); 15217 15218 Alignment.PointerAlignment = FormatStyle::PAS_Left; 15219 verifyFormat("unsigned int* a;\n" 15220 "int* b;\n" 15221 "unsigned int Const* c;\n" 15222 "unsigned int const* d;\n" 15223 "unsigned int Const& e;\n" 15224 "unsigned int const& f;", 15225 Alignment); 15226 verifyFormat("Const unsigned int* c;\n" 15227 "const unsigned int* d;\n" 15228 "Const unsigned int& e;\n" 15229 "const unsigned int& f;\n" 15230 "const unsigned g;\n" 15231 "Const unsigned h;", 15232 Alignment); 15233 15234 Alignment.PointerAlignment = FormatStyle::PAS_Middle; 15235 verifyFormat("unsigned int * a;\n" 15236 "int * b;\n" 15237 "unsigned int Const * c;\n" 15238 "unsigned int const * d;\n" 15239 "unsigned int Const & e;\n" 15240 "unsigned int const & f;", 15241 Alignment); 15242 verifyFormat("Const unsigned int * c;\n" 15243 "const unsigned int * d;\n" 15244 "Const unsigned int & e;\n" 15245 "const unsigned int & f;\n" 15246 "const unsigned g;\n" 15247 "Const unsigned h;", 15248 Alignment); 15249 } 15250 15251 TEST_F(FormatTest, AlignWithLineBreaks) { 15252 auto Style = getLLVMStyleWithColumns(120); 15253 15254 EXPECT_EQ(Style.AlignConsecutiveAssignments, FormatStyle::ACS_None); 15255 EXPECT_EQ(Style.AlignConsecutiveDeclarations, FormatStyle::ACS_None); 15256 verifyFormat("void foo() {\n" 15257 " int myVar = 5;\n" 15258 " double x = 3.14;\n" 15259 " auto str = \"Hello \"\n" 15260 " \"World\";\n" 15261 " auto s = \"Hello \"\n" 15262 " \"Again\";\n" 15263 "}", 15264 Style); 15265 15266 // clang-format off 15267 verifyFormat("void foo() {\n" 15268 " const int capacityBefore = Entries.capacity();\n" 15269 " const auto newEntry = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n" 15270 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n" 15271 " const X newEntry2 = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n" 15272 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n" 15273 "}", 15274 Style); 15275 // clang-format on 15276 15277 Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive; 15278 verifyFormat("void foo() {\n" 15279 " int myVar = 5;\n" 15280 " double x = 3.14;\n" 15281 " auto str = \"Hello \"\n" 15282 " \"World\";\n" 15283 " auto s = \"Hello \"\n" 15284 " \"Again\";\n" 15285 "}", 15286 Style); 15287 15288 // clang-format off 15289 verifyFormat("void foo() {\n" 15290 " const int capacityBefore = Entries.capacity();\n" 15291 " const auto newEntry = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n" 15292 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n" 15293 " const X newEntry2 = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n" 15294 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n" 15295 "}", 15296 Style); 15297 // clang-format on 15298 15299 Style.AlignConsecutiveAssignments = FormatStyle::ACS_None; 15300 Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 15301 verifyFormat("void foo() {\n" 15302 " int myVar = 5;\n" 15303 " double x = 3.14;\n" 15304 " auto str = \"Hello \"\n" 15305 " \"World\";\n" 15306 " auto s = \"Hello \"\n" 15307 " \"Again\";\n" 15308 "}", 15309 Style); 15310 15311 // clang-format off 15312 verifyFormat("void foo() {\n" 15313 " const int capacityBefore = Entries.capacity();\n" 15314 " const auto newEntry = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n" 15315 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n" 15316 " const X newEntry2 = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n" 15317 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n" 15318 "}", 15319 Style); 15320 // clang-format on 15321 15322 Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive; 15323 Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 15324 15325 verifyFormat("void foo() {\n" 15326 " int myVar = 5;\n" 15327 " double x = 3.14;\n" 15328 " auto str = \"Hello \"\n" 15329 " \"World\";\n" 15330 " auto s = \"Hello \"\n" 15331 " \"Again\";\n" 15332 "}", 15333 Style); 15334 15335 // clang-format off 15336 verifyFormat("void foo() {\n" 15337 " const int capacityBefore = Entries.capacity();\n" 15338 " const auto newEntry = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n" 15339 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n" 15340 " const X newEntry2 = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n" 15341 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n" 15342 "}", 15343 Style); 15344 // clang-format on 15345 } 15346 15347 TEST_F(FormatTest, LinuxBraceBreaking) { 15348 FormatStyle LinuxBraceStyle = getLLVMStyle(); 15349 LinuxBraceStyle.BreakBeforeBraces = FormatStyle::BS_Linux; 15350 verifyFormat("namespace a\n" 15351 "{\n" 15352 "class A\n" 15353 "{\n" 15354 " void f()\n" 15355 " {\n" 15356 " if (true) {\n" 15357 " a();\n" 15358 " b();\n" 15359 " } else {\n" 15360 " a();\n" 15361 " }\n" 15362 " }\n" 15363 " void g() { return; }\n" 15364 "};\n" 15365 "struct B {\n" 15366 " int x;\n" 15367 "};\n" 15368 "} // namespace a\n", 15369 LinuxBraceStyle); 15370 verifyFormat("enum X {\n" 15371 " Y = 0,\n" 15372 "}\n", 15373 LinuxBraceStyle); 15374 verifyFormat("struct S {\n" 15375 " int Type;\n" 15376 " union {\n" 15377 " int x;\n" 15378 " double y;\n" 15379 " } Value;\n" 15380 " class C\n" 15381 " {\n" 15382 " MyFavoriteType Value;\n" 15383 " } Class;\n" 15384 "}\n", 15385 LinuxBraceStyle); 15386 } 15387 15388 TEST_F(FormatTest, MozillaBraceBreaking) { 15389 FormatStyle MozillaBraceStyle = getLLVMStyle(); 15390 MozillaBraceStyle.BreakBeforeBraces = FormatStyle::BS_Mozilla; 15391 MozillaBraceStyle.FixNamespaceComments = false; 15392 verifyFormat("namespace a {\n" 15393 "class A\n" 15394 "{\n" 15395 " void f()\n" 15396 " {\n" 15397 " if (true) {\n" 15398 " a();\n" 15399 " b();\n" 15400 " }\n" 15401 " }\n" 15402 " void g() { return; }\n" 15403 "};\n" 15404 "enum E\n" 15405 "{\n" 15406 " A,\n" 15407 " // foo\n" 15408 " B,\n" 15409 " C\n" 15410 "};\n" 15411 "struct B\n" 15412 "{\n" 15413 " int x;\n" 15414 "};\n" 15415 "}\n", 15416 MozillaBraceStyle); 15417 verifyFormat("struct S\n" 15418 "{\n" 15419 " int Type;\n" 15420 " union\n" 15421 " {\n" 15422 " int x;\n" 15423 " double y;\n" 15424 " } Value;\n" 15425 " class C\n" 15426 " {\n" 15427 " MyFavoriteType Value;\n" 15428 " } Class;\n" 15429 "}\n", 15430 MozillaBraceStyle); 15431 } 15432 15433 TEST_F(FormatTest, StroustrupBraceBreaking) { 15434 FormatStyle StroustrupBraceStyle = getLLVMStyle(); 15435 StroustrupBraceStyle.BreakBeforeBraces = FormatStyle::BS_Stroustrup; 15436 verifyFormat("namespace a {\n" 15437 "class A {\n" 15438 " void f()\n" 15439 " {\n" 15440 " if (true) {\n" 15441 " a();\n" 15442 " b();\n" 15443 " }\n" 15444 " }\n" 15445 " void g() { return; }\n" 15446 "};\n" 15447 "struct B {\n" 15448 " int x;\n" 15449 "};\n" 15450 "} // namespace a\n", 15451 StroustrupBraceStyle); 15452 15453 verifyFormat("void foo()\n" 15454 "{\n" 15455 " if (a) {\n" 15456 " a();\n" 15457 " }\n" 15458 " else {\n" 15459 " b();\n" 15460 " }\n" 15461 "}\n", 15462 StroustrupBraceStyle); 15463 15464 verifyFormat("#ifdef _DEBUG\n" 15465 "int foo(int i = 0)\n" 15466 "#else\n" 15467 "int foo(int i = 5)\n" 15468 "#endif\n" 15469 "{\n" 15470 " return i;\n" 15471 "}", 15472 StroustrupBraceStyle); 15473 15474 verifyFormat("void foo() {}\n" 15475 "void bar()\n" 15476 "#ifdef _DEBUG\n" 15477 "{\n" 15478 " foo();\n" 15479 "}\n" 15480 "#else\n" 15481 "{\n" 15482 "}\n" 15483 "#endif", 15484 StroustrupBraceStyle); 15485 15486 verifyFormat("void foobar() { int i = 5; }\n" 15487 "#ifdef _DEBUG\n" 15488 "void bar() {}\n" 15489 "#else\n" 15490 "void bar() { foobar(); }\n" 15491 "#endif", 15492 StroustrupBraceStyle); 15493 } 15494 15495 TEST_F(FormatTest, AllmanBraceBreaking) { 15496 FormatStyle AllmanBraceStyle = getLLVMStyle(); 15497 AllmanBraceStyle.BreakBeforeBraces = FormatStyle::BS_Allman; 15498 15499 EXPECT_EQ("namespace a\n" 15500 "{\n" 15501 "void f();\n" 15502 "void g();\n" 15503 "} // namespace a\n", 15504 format("namespace a\n" 15505 "{\n" 15506 "void f();\n" 15507 "void g();\n" 15508 "}\n", 15509 AllmanBraceStyle)); 15510 15511 verifyFormat("namespace a\n" 15512 "{\n" 15513 "class A\n" 15514 "{\n" 15515 " void f()\n" 15516 " {\n" 15517 " if (true)\n" 15518 " {\n" 15519 " a();\n" 15520 " b();\n" 15521 " }\n" 15522 " }\n" 15523 " void g() { return; }\n" 15524 "};\n" 15525 "struct B\n" 15526 "{\n" 15527 " int x;\n" 15528 "};\n" 15529 "union C\n" 15530 "{\n" 15531 "};\n" 15532 "} // namespace a", 15533 AllmanBraceStyle); 15534 15535 verifyFormat("void f()\n" 15536 "{\n" 15537 " if (true)\n" 15538 " {\n" 15539 " a();\n" 15540 " }\n" 15541 " else if (false)\n" 15542 " {\n" 15543 " b();\n" 15544 " }\n" 15545 " else\n" 15546 " {\n" 15547 " c();\n" 15548 " }\n" 15549 "}\n", 15550 AllmanBraceStyle); 15551 15552 verifyFormat("void f()\n" 15553 "{\n" 15554 " for (int i = 0; i < 10; ++i)\n" 15555 " {\n" 15556 " a();\n" 15557 " }\n" 15558 " while (false)\n" 15559 " {\n" 15560 " b();\n" 15561 " }\n" 15562 " do\n" 15563 " {\n" 15564 " c();\n" 15565 " } while (false)\n" 15566 "}\n", 15567 AllmanBraceStyle); 15568 15569 verifyFormat("void f(int a)\n" 15570 "{\n" 15571 " switch (a)\n" 15572 " {\n" 15573 " case 0:\n" 15574 " break;\n" 15575 " case 1:\n" 15576 " {\n" 15577 " break;\n" 15578 " }\n" 15579 " case 2:\n" 15580 " {\n" 15581 " }\n" 15582 " break;\n" 15583 " default:\n" 15584 " break;\n" 15585 " }\n" 15586 "}\n", 15587 AllmanBraceStyle); 15588 15589 verifyFormat("enum X\n" 15590 "{\n" 15591 " Y = 0,\n" 15592 "}\n", 15593 AllmanBraceStyle); 15594 verifyFormat("enum X\n" 15595 "{\n" 15596 " Y = 0\n" 15597 "}\n", 15598 AllmanBraceStyle); 15599 15600 verifyFormat("@interface BSApplicationController ()\n" 15601 "{\n" 15602 "@private\n" 15603 " id _extraIvar;\n" 15604 "}\n" 15605 "@end\n", 15606 AllmanBraceStyle); 15607 15608 verifyFormat("#ifdef _DEBUG\n" 15609 "int foo(int i = 0)\n" 15610 "#else\n" 15611 "int foo(int i = 5)\n" 15612 "#endif\n" 15613 "{\n" 15614 " return i;\n" 15615 "}", 15616 AllmanBraceStyle); 15617 15618 verifyFormat("void foo() {}\n" 15619 "void bar()\n" 15620 "#ifdef _DEBUG\n" 15621 "{\n" 15622 " foo();\n" 15623 "}\n" 15624 "#else\n" 15625 "{\n" 15626 "}\n" 15627 "#endif", 15628 AllmanBraceStyle); 15629 15630 verifyFormat("void foobar() { int i = 5; }\n" 15631 "#ifdef _DEBUG\n" 15632 "void bar() {}\n" 15633 "#else\n" 15634 "void bar() { foobar(); }\n" 15635 "#endif", 15636 AllmanBraceStyle); 15637 15638 EXPECT_EQ(AllmanBraceStyle.AllowShortLambdasOnASingleLine, 15639 FormatStyle::SLS_All); 15640 15641 verifyFormat("[](int i) { return i + 2; };\n" 15642 "[](int i, int j)\n" 15643 "{\n" 15644 " auto x = i + j;\n" 15645 " auto y = i * j;\n" 15646 " return x ^ y;\n" 15647 "};\n" 15648 "void foo()\n" 15649 "{\n" 15650 " auto shortLambda = [](int i) { return i + 2; };\n" 15651 " auto longLambda = [](int i, int j)\n" 15652 " {\n" 15653 " auto x = i + j;\n" 15654 " auto y = i * j;\n" 15655 " return x ^ y;\n" 15656 " };\n" 15657 "}", 15658 AllmanBraceStyle); 15659 15660 AllmanBraceStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None; 15661 15662 verifyFormat("[](int i)\n" 15663 "{\n" 15664 " return i + 2;\n" 15665 "};\n" 15666 "[](int i, int j)\n" 15667 "{\n" 15668 " auto x = i + j;\n" 15669 " auto y = i * j;\n" 15670 " return x ^ y;\n" 15671 "};\n" 15672 "void foo()\n" 15673 "{\n" 15674 " auto shortLambda = [](int i)\n" 15675 " {\n" 15676 " return i + 2;\n" 15677 " };\n" 15678 " auto longLambda = [](int i, int j)\n" 15679 " {\n" 15680 " auto x = i + j;\n" 15681 " auto y = i * j;\n" 15682 " return x ^ y;\n" 15683 " };\n" 15684 "}", 15685 AllmanBraceStyle); 15686 15687 // Reset 15688 AllmanBraceStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_All; 15689 15690 // This shouldn't affect ObjC blocks.. 15691 verifyFormat("[self doSomeThingWithACompletionHandler:^{\n" 15692 " // ...\n" 15693 " int i;\n" 15694 "}];", 15695 AllmanBraceStyle); 15696 verifyFormat("void (^block)(void) = ^{\n" 15697 " // ...\n" 15698 " int i;\n" 15699 "};", 15700 AllmanBraceStyle); 15701 // .. or dict literals. 15702 verifyFormat("void f()\n" 15703 "{\n" 15704 " // ...\n" 15705 " [object someMethod:@{@\"a\" : @\"b\"}];\n" 15706 "}", 15707 AllmanBraceStyle); 15708 verifyFormat("void f()\n" 15709 "{\n" 15710 " // ...\n" 15711 " [object someMethod:@{a : @\"b\"}];\n" 15712 "}", 15713 AllmanBraceStyle); 15714 verifyFormat("int f()\n" 15715 "{ // comment\n" 15716 " return 42;\n" 15717 "}", 15718 AllmanBraceStyle); 15719 15720 AllmanBraceStyle.ColumnLimit = 19; 15721 verifyFormat("void f() { int i; }", AllmanBraceStyle); 15722 AllmanBraceStyle.ColumnLimit = 18; 15723 verifyFormat("void f()\n" 15724 "{\n" 15725 " int i;\n" 15726 "}", 15727 AllmanBraceStyle); 15728 AllmanBraceStyle.ColumnLimit = 80; 15729 15730 FormatStyle BreakBeforeBraceShortIfs = AllmanBraceStyle; 15731 BreakBeforeBraceShortIfs.AllowShortIfStatementsOnASingleLine = 15732 FormatStyle::SIS_WithoutElse; 15733 BreakBeforeBraceShortIfs.AllowShortLoopsOnASingleLine = true; 15734 verifyFormat("void f(bool b)\n" 15735 "{\n" 15736 " if (b)\n" 15737 " {\n" 15738 " return;\n" 15739 " }\n" 15740 "}\n", 15741 BreakBeforeBraceShortIfs); 15742 verifyFormat("void f(bool b)\n" 15743 "{\n" 15744 " if constexpr (b)\n" 15745 " {\n" 15746 " return;\n" 15747 " }\n" 15748 "}\n", 15749 BreakBeforeBraceShortIfs); 15750 verifyFormat("void f(bool b)\n" 15751 "{\n" 15752 " if CONSTEXPR (b)\n" 15753 " {\n" 15754 " return;\n" 15755 " }\n" 15756 "}\n", 15757 BreakBeforeBraceShortIfs); 15758 verifyFormat("void f(bool b)\n" 15759 "{\n" 15760 " if (b) return;\n" 15761 "}\n", 15762 BreakBeforeBraceShortIfs); 15763 verifyFormat("void f(bool b)\n" 15764 "{\n" 15765 " if constexpr (b) return;\n" 15766 "}\n", 15767 BreakBeforeBraceShortIfs); 15768 verifyFormat("void f(bool b)\n" 15769 "{\n" 15770 " if CONSTEXPR (b) return;\n" 15771 "}\n", 15772 BreakBeforeBraceShortIfs); 15773 verifyFormat("void f(bool b)\n" 15774 "{\n" 15775 " while (b)\n" 15776 " {\n" 15777 " return;\n" 15778 " }\n" 15779 "}\n", 15780 BreakBeforeBraceShortIfs); 15781 } 15782 15783 TEST_F(FormatTest, WhitesmithsBraceBreaking) { 15784 FormatStyle WhitesmithsBraceStyle = getLLVMStyle(); 15785 WhitesmithsBraceStyle.BreakBeforeBraces = FormatStyle::BS_Whitesmiths; 15786 15787 // Make a few changes to the style for testing purposes 15788 WhitesmithsBraceStyle.AllowShortFunctionsOnASingleLine = 15789 FormatStyle::SFS_Empty; 15790 WhitesmithsBraceStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None; 15791 WhitesmithsBraceStyle.ColumnLimit = 0; 15792 15793 // FIXME: this test case can't decide whether there should be a blank line 15794 // after the ~D() line or not. It adds one if one doesn't exist in the test 15795 // and it removes the line if one exists. 15796 /* 15797 verifyFormat("class A;\n" 15798 "namespace B\n" 15799 " {\n" 15800 "class C;\n" 15801 "// Comment\n" 15802 "class D\n" 15803 " {\n" 15804 "public:\n" 15805 " D();\n" 15806 " ~D() {}\n" 15807 "private:\n" 15808 " enum E\n" 15809 " {\n" 15810 " F\n" 15811 " }\n" 15812 " };\n" 15813 " } // namespace B\n", 15814 WhitesmithsBraceStyle); 15815 */ 15816 15817 WhitesmithsBraceStyle.NamespaceIndentation = FormatStyle::NI_None; 15818 verifyFormat("namespace a\n" 15819 " {\n" 15820 "class A\n" 15821 " {\n" 15822 " void f()\n" 15823 " {\n" 15824 " if (true)\n" 15825 " {\n" 15826 " a();\n" 15827 " b();\n" 15828 " }\n" 15829 " }\n" 15830 " void g()\n" 15831 " {\n" 15832 " return;\n" 15833 " }\n" 15834 " };\n" 15835 "struct B\n" 15836 " {\n" 15837 " int x;\n" 15838 " };\n" 15839 " } // namespace a", 15840 WhitesmithsBraceStyle); 15841 15842 verifyFormat("namespace a\n" 15843 " {\n" 15844 "namespace b\n" 15845 " {\n" 15846 "class A\n" 15847 " {\n" 15848 " void f()\n" 15849 " {\n" 15850 " if (true)\n" 15851 " {\n" 15852 " a();\n" 15853 " b();\n" 15854 " }\n" 15855 " }\n" 15856 " void g()\n" 15857 " {\n" 15858 " return;\n" 15859 " }\n" 15860 " };\n" 15861 "struct B\n" 15862 " {\n" 15863 " int x;\n" 15864 " };\n" 15865 " } // namespace b\n" 15866 " } // namespace a", 15867 WhitesmithsBraceStyle); 15868 15869 WhitesmithsBraceStyle.NamespaceIndentation = FormatStyle::NI_Inner; 15870 verifyFormat("namespace a\n" 15871 " {\n" 15872 "namespace b\n" 15873 " {\n" 15874 " class A\n" 15875 " {\n" 15876 " void f()\n" 15877 " {\n" 15878 " if (true)\n" 15879 " {\n" 15880 " a();\n" 15881 " b();\n" 15882 " }\n" 15883 " }\n" 15884 " void g()\n" 15885 " {\n" 15886 " return;\n" 15887 " }\n" 15888 " };\n" 15889 " struct B\n" 15890 " {\n" 15891 " int x;\n" 15892 " };\n" 15893 " } // namespace b\n" 15894 " } // namespace a", 15895 WhitesmithsBraceStyle); 15896 15897 WhitesmithsBraceStyle.NamespaceIndentation = FormatStyle::NI_All; 15898 verifyFormat("namespace a\n" 15899 " {\n" 15900 " namespace b\n" 15901 " {\n" 15902 " class A\n" 15903 " {\n" 15904 " void f()\n" 15905 " {\n" 15906 " if (true)\n" 15907 " {\n" 15908 " a();\n" 15909 " b();\n" 15910 " }\n" 15911 " }\n" 15912 " void g()\n" 15913 " {\n" 15914 " return;\n" 15915 " }\n" 15916 " };\n" 15917 " struct B\n" 15918 " {\n" 15919 " int x;\n" 15920 " };\n" 15921 " } // namespace b\n" 15922 " } // namespace a", 15923 WhitesmithsBraceStyle); 15924 15925 verifyFormat("void f()\n" 15926 " {\n" 15927 " if (true)\n" 15928 " {\n" 15929 " a();\n" 15930 " }\n" 15931 " else if (false)\n" 15932 " {\n" 15933 " b();\n" 15934 " }\n" 15935 " else\n" 15936 " {\n" 15937 " c();\n" 15938 " }\n" 15939 " }\n", 15940 WhitesmithsBraceStyle); 15941 15942 verifyFormat("void f()\n" 15943 " {\n" 15944 " for (int i = 0; i < 10; ++i)\n" 15945 " {\n" 15946 " a();\n" 15947 " }\n" 15948 " while (false)\n" 15949 " {\n" 15950 " b();\n" 15951 " }\n" 15952 " do\n" 15953 " {\n" 15954 " c();\n" 15955 " } while (false)\n" 15956 " }\n", 15957 WhitesmithsBraceStyle); 15958 15959 WhitesmithsBraceStyle.IndentCaseLabels = true; 15960 verifyFormat("void switchTest1(int a)\n" 15961 " {\n" 15962 " switch (a)\n" 15963 " {\n" 15964 " case 2:\n" 15965 " {\n" 15966 " }\n" 15967 " break;\n" 15968 " }\n" 15969 " }\n", 15970 WhitesmithsBraceStyle); 15971 15972 verifyFormat("void switchTest2(int a)\n" 15973 " {\n" 15974 " switch (a)\n" 15975 " {\n" 15976 " case 0:\n" 15977 " break;\n" 15978 " case 1:\n" 15979 " {\n" 15980 " break;\n" 15981 " }\n" 15982 " case 2:\n" 15983 " {\n" 15984 " }\n" 15985 " break;\n" 15986 " default:\n" 15987 " break;\n" 15988 " }\n" 15989 " }\n", 15990 WhitesmithsBraceStyle); 15991 15992 verifyFormat("void switchTest3(int a)\n" 15993 " {\n" 15994 " switch (a)\n" 15995 " {\n" 15996 " case 0:\n" 15997 " {\n" 15998 " foo(x);\n" 15999 " }\n" 16000 " break;\n" 16001 " default:\n" 16002 " {\n" 16003 " foo(1);\n" 16004 " }\n" 16005 " break;\n" 16006 " }\n" 16007 " }\n", 16008 WhitesmithsBraceStyle); 16009 16010 WhitesmithsBraceStyle.IndentCaseLabels = false; 16011 16012 verifyFormat("void switchTest4(int a)\n" 16013 " {\n" 16014 " switch (a)\n" 16015 " {\n" 16016 " case 2:\n" 16017 " {\n" 16018 " }\n" 16019 " break;\n" 16020 " }\n" 16021 " }\n", 16022 WhitesmithsBraceStyle); 16023 16024 verifyFormat("void switchTest5(int a)\n" 16025 " {\n" 16026 " switch (a)\n" 16027 " {\n" 16028 " case 0:\n" 16029 " break;\n" 16030 " case 1:\n" 16031 " {\n" 16032 " foo();\n" 16033 " break;\n" 16034 " }\n" 16035 " case 2:\n" 16036 " {\n" 16037 " }\n" 16038 " break;\n" 16039 " default:\n" 16040 " break;\n" 16041 " }\n" 16042 " }\n", 16043 WhitesmithsBraceStyle); 16044 16045 verifyFormat("void switchTest6(int a)\n" 16046 " {\n" 16047 " switch (a)\n" 16048 " {\n" 16049 " case 0:\n" 16050 " {\n" 16051 " foo(x);\n" 16052 " }\n" 16053 " break;\n" 16054 " default:\n" 16055 " {\n" 16056 " foo(1);\n" 16057 " }\n" 16058 " break;\n" 16059 " }\n" 16060 " }\n", 16061 WhitesmithsBraceStyle); 16062 16063 verifyFormat("enum X\n" 16064 " {\n" 16065 " Y = 0, // testing\n" 16066 " }\n", 16067 WhitesmithsBraceStyle); 16068 16069 verifyFormat("enum X\n" 16070 " {\n" 16071 " Y = 0\n" 16072 " }\n", 16073 WhitesmithsBraceStyle); 16074 verifyFormat("enum X\n" 16075 " {\n" 16076 " Y = 0,\n" 16077 " Z = 1\n" 16078 " };\n", 16079 WhitesmithsBraceStyle); 16080 16081 verifyFormat("@interface BSApplicationController ()\n" 16082 " {\n" 16083 "@private\n" 16084 " id _extraIvar;\n" 16085 " }\n" 16086 "@end\n", 16087 WhitesmithsBraceStyle); 16088 16089 verifyFormat("#ifdef _DEBUG\n" 16090 "int foo(int i = 0)\n" 16091 "#else\n" 16092 "int foo(int i = 5)\n" 16093 "#endif\n" 16094 " {\n" 16095 " return i;\n" 16096 " }", 16097 WhitesmithsBraceStyle); 16098 16099 verifyFormat("void foo() {}\n" 16100 "void bar()\n" 16101 "#ifdef _DEBUG\n" 16102 " {\n" 16103 " foo();\n" 16104 " }\n" 16105 "#else\n" 16106 " {\n" 16107 " }\n" 16108 "#endif", 16109 WhitesmithsBraceStyle); 16110 16111 verifyFormat("void foobar()\n" 16112 " {\n" 16113 " int i = 5;\n" 16114 " }\n" 16115 "#ifdef _DEBUG\n" 16116 "void bar()\n" 16117 " {\n" 16118 " }\n" 16119 "#else\n" 16120 "void bar()\n" 16121 " {\n" 16122 " foobar();\n" 16123 " }\n" 16124 "#endif", 16125 WhitesmithsBraceStyle); 16126 16127 // This shouldn't affect ObjC blocks.. 16128 verifyFormat("[self doSomeThingWithACompletionHandler:^{\n" 16129 " // ...\n" 16130 " int i;\n" 16131 "}];", 16132 WhitesmithsBraceStyle); 16133 verifyFormat("void (^block)(void) = ^{\n" 16134 " // ...\n" 16135 " int i;\n" 16136 "};", 16137 WhitesmithsBraceStyle); 16138 // .. or dict literals. 16139 verifyFormat("void f()\n" 16140 " {\n" 16141 " [object someMethod:@{@\"a\" : @\"b\"}];\n" 16142 " }", 16143 WhitesmithsBraceStyle); 16144 16145 verifyFormat("int f()\n" 16146 " { // comment\n" 16147 " return 42;\n" 16148 " }", 16149 WhitesmithsBraceStyle); 16150 16151 FormatStyle BreakBeforeBraceShortIfs = WhitesmithsBraceStyle; 16152 BreakBeforeBraceShortIfs.AllowShortIfStatementsOnASingleLine = 16153 FormatStyle::SIS_OnlyFirstIf; 16154 BreakBeforeBraceShortIfs.AllowShortLoopsOnASingleLine = true; 16155 verifyFormat("void f(bool b)\n" 16156 " {\n" 16157 " if (b)\n" 16158 " {\n" 16159 " return;\n" 16160 " }\n" 16161 " }\n", 16162 BreakBeforeBraceShortIfs); 16163 verifyFormat("void f(bool b)\n" 16164 " {\n" 16165 " if (b) return;\n" 16166 " }\n", 16167 BreakBeforeBraceShortIfs); 16168 verifyFormat("void f(bool b)\n" 16169 " {\n" 16170 " while (b)\n" 16171 " {\n" 16172 " return;\n" 16173 " }\n" 16174 " }\n", 16175 BreakBeforeBraceShortIfs); 16176 } 16177 16178 TEST_F(FormatTest, GNUBraceBreaking) { 16179 FormatStyle GNUBraceStyle = getLLVMStyle(); 16180 GNUBraceStyle.BreakBeforeBraces = FormatStyle::BS_GNU; 16181 verifyFormat("namespace a\n" 16182 "{\n" 16183 "class A\n" 16184 "{\n" 16185 " void f()\n" 16186 " {\n" 16187 " int a;\n" 16188 " {\n" 16189 " int b;\n" 16190 " }\n" 16191 " if (true)\n" 16192 " {\n" 16193 " a();\n" 16194 " b();\n" 16195 " }\n" 16196 " }\n" 16197 " void g() { return; }\n" 16198 "}\n" 16199 "} // namespace a", 16200 GNUBraceStyle); 16201 16202 verifyFormat("void f()\n" 16203 "{\n" 16204 " if (true)\n" 16205 " {\n" 16206 " a();\n" 16207 " }\n" 16208 " else if (false)\n" 16209 " {\n" 16210 " b();\n" 16211 " }\n" 16212 " else\n" 16213 " {\n" 16214 " c();\n" 16215 " }\n" 16216 "}\n", 16217 GNUBraceStyle); 16218 16219 verifyFormat("void f()\n" 16220 "{\n" 16221 " for (int i = 0; i < 10; ++i)\n" 16222 " {\n" 16223 " a();\n" 16224 " }\n" 16225 " while (false)\n" 16226 " {\n" 16227 " b();\n" 16228 " }\n" 16229 " do\n" 16230 " {\n" 16231 " c();\n" 16232 " }\n" 16233 " while (false);\n" 16234 "}\n", 16235 GNUBraceStyle); 16236 16237 verifyFormat("void f(int a)\n" 16238 "{\n" 16239 " switch (a)\n" 16240 " {\n" 16241 " case 0:\n" 16242 " break;\n" 16243 " case 1:\n" 16244 " {\n" 16245 " break;\n" 16246 " }\n" 16247 " case 2:\n" 16248 " {\n" 16249 " }\n" 16250 " break;\n" 16251 " default:\n" 16252 " break;\n" 16253 " }\n" 16254 "}\n", 16255 GNUBraceStyle); 16256 16257 verifyFormat("enum X\n" 16258 "{\n" 16259 " Y = 0,\n" 16260 "}\n", 16261 GNUBraceStyle); 16262 16263 verifyFormat("@interface BSApplicationController ()\n" 16264 "{\n" 16265 "@private\n" 16266 " id _extraIvar;\n" 16267 "}\n" 16268 "@end\n", 16269 GNUBraceStyle); 16270 16271 verifyFormat("#ifdef _DEBUG\n" 16272 "int foo(int i = 0)\n" 16273 "#else\n" 16274 "int foo(int i = 5)\n" 16275 "#endif\n" 16276 "{\n" 16277 " return i;\n" 16278 "}", 16279 GNUBraceStyle); 16280 16281 verifyFormat("void foo() {}\n" 16282 "void bar()\n" 16283 "#ifdef _DEBUG\n" 16284 "{\n" 16285 " foo();\n" 16286 "}\n" 16287 "#else\n" 16288 "{\n" 16289 "}\n" 16290 "#endif", 16291 GNUBraceStyle); 16292 16293 verifyFormat("void foobar() { int i = 5; }\n" 16294 "#ifdef _DEBUG\n" 16295 "void bar() {}\n" 16296 "#else\n" 16297 "void bar() { foobar(); }\n" 16298 "#endif", 16299 GNUBraceStyle); 16300 } 16301 16302 TEST_F(FormatTest, WebKitBraceBreaking) { 16303 FormatStyle WebKitBraceStyle = getLLVMStyle(); 16304 WebKitBraceStyle.BreakBeforeBraces = FormatStyle::BS_WebKit; 16305 WebKitBraceStyle.FixNamespaceComments = false; 16306 verifyFormat("namespace a {\n" 16307 "class A {\n" 16308 " void f()\n" 16309 " {\n" 16310 " if (true) {\n" 16311 " a();\n" 16312 " b();\n" 16313 " }\n" 16314 " }\n" 16315 " void g() { return; }\n" 16316 "};\n" 16317 "enum E {\n" 16318 " A,\n" 16319 " // foo\n" 16320 " B,\n" 16321 " C\n" 16322 "};\n" 16323 "struct B {\n" 16324 " int x;\n" 16325 "};\n" 16326 "}\n", 16327 WebKitBraceStyle); 16328 verifyFormat("struct S {\n" 16329 " int Type;\n" 16330 " union {\n" 16331 " int x;\n" 16332 " double y;\n" 16333 " } Value;\n" 16334 " class C {\n" 16335 " MyFavoriteType Value;\n" 16336 " } Class;\n" 16337 "};\n", 16338 WebKitBraceStyle); 16339 } 16340 16341 TEST_F(FormatTest, CatchExceptionReferenceBinding) { 16342 verifyFormat("void f() {\n" 16343 " try {\n" 16344 " } catch (const Exception &e) {\n" 16345 " }\n" 16346 "}\n", 16347 getLLVMStyle()); 16348 } 16349 16350 TEST_F(FormatTest, UnderstandsPragmas) { 16351 verifyFormat("#pragma omp reduction(| : var)"); 16352 verifyFormat("#pragma omp reduction(+ : var)"); 16353 16354 EXPECT_EQ("#pragma mark Any non-hyphenated or hyphenated string " 16355 "(including parentheses).", 16356 format("#pragma mark Any non-hyphenated or hyphenated string " 16357 "(including parentheses).")); 16358 } 16359 16360 TEST_F(FormatTest, UnderstandPragmaOption) { 16361 verifyFormat("#pragma option -C -A"); 16362 16363 EXPECT_EQ("#pragma option -C -A", format("#pragma option -C -A")); 16364 } 16365 16366 TEST_F(FormatTest, OptimizeBreakPenaltyVsExcess) { 16367 FormatStyle Style = getLLVMStyle(); 16368 Style.ColumnLimit = 20; 16369 16370 // See PR41213 16371 EXPECT_EQ("/*\n" 16372 " *\t9012345\n" 16373 " * /8901\n" 16374 " */", 16375 format("/*\n" 16376 " *\t9012345 /8901\n" 16377 " */", 16378 Style)); 16379 EXPECT_EQ("/*\n" 16380 " *345678\n" 16381 " *\t/8901\n" 16382 " */", 16383 format("/*\n" 16384 " *345678\t/8901\n" 16385 " */", 16386 Style)); 16387 16388 verifyFormat("int a; // the\n" 16389 " // comment", 16390 Style); 16391 EXPECT_EQ("int a; /* first line\n" 16392 " * second\n" 16393 " * line third\n" 16394 " * line\n" 16395 " */", 16396 format("int a; /* first line\n" 16397 " * second\n" 16398 " * line third\n" 16399 " * line\n" 16400 " */", 16401 Style)); 16402 EXPECT_EQ("int a; // first line\n" 16403 " // second\n" 16404 " // line third\n" 16405 " // line", 16406 format("int a; // first line\n" 16407 " // second line\n" 16408 " // third line", 16409 Style)); 16410 16411 Style.PenaltyExcessCharacter = 90; 16412 verifyFormat("int a; // the comment", Style); 16413 EXPECT_EQ("int a; // the comment\n" 16414 " // aaa", 16415 format("int a; // the comment aaa", Style)); 16416 EXPECT_EQ("int a; /* first line\n" 16417 " * second line\n" 16418 " * third line\n" 16419 " */", 16420 format("int a; /* first line\n" 16421 " * second line\n" 16422 " * third line\n" 16423 " */", 16424 Style)); 16425 EXPECT_EQ("int a; // first line\n" 16426 " // second line\n" 16427 " // third line", 16428 format("int a; // first line\n" 16429 " // second line\n" 16430 " // third line", 16431 Style)); 16432 // FIXME: Investigate why this is not getting the same layout as the test 16433 // above. 16434 EXPECT_EQ("int a; /* first line\n" 16435 " * second line\n" 16436 " * third line\n" 16437 " */", 16438 format("int a; /* first line second line third line" 16439 "\n*/", 16440 Style)); 16441 16442 EXPECT_EQ("// foo bar baz bazfoo\n" 16443 "// foo bar foo bar\n", 16444 format("// foo bar baz bazfoo\n" 16445 "// foo bar foo bar\n", 16446 Style)); 16447 EXPECT_EQ("// foo bar baz bazfoo\n" 16448 "// foo bar foo bar\n", 16449 format("// foo bar baz bazfoo\n" 16450 "// foo bar foo bar\n", 16451 Style)); 16452 16453 // FIXME: Optimally, we'd keep bazfoo on the first line and reflow bar to the 16454 // next one. 16455 EXPECT_EQ("// foo bar baz bazfoo\n" 16456 "// bar foo bar\n", 16457 format("// foo bar baz bazfoo bar\n" 16458 "// foo bar\n", 16459 Style)); 16460 16461 EXPECT_EQ("// foo bar baz bazfoo\n" 16462 "// foo bar baz bazfoo\n" 16463 "// bar foo bar\n", 16464 format("// foo bar baz bazfoo\n" 16465 "// foo bar baz bazfoo bar\n" 16466 "// foo bar\n", 16467 Style)); 16468 16469 EXPECT_EQ("// foo bar baz bazfoo\n" 16470 "// foo bar baz bazfoo\n" 16471 "// bar foo bar\n", 16472 format("// foo bar baz bazfoo\n" 16473 "// foo bar baz bazfoo bar\n" 16474 "// foo bar\n", 16475 Style)); 16476 16477 // Make sure we do not keep protruding characters if strict mode reflow is 16478 // cheaper than keeping protruding characters. 16479 Style.ColumnLimit = 21; 16480 EXPECT_EQ( 16481 "// foo foo foo foo\n" 16482 "// foo foo foo foo\n" 16483 "// foo foo foo foo\n", 16484 format("// foo foo foo foo foo foo foo foo foo foo foo foo\n", Style)); 16485 16486 EXPECT_EQ("int a = /* long block\n" 16487 " comment */\n" 16488 " 42;", 16489 format("int a = /* long block comment */ 42;", Style)); 16490 } 16491 16492 #define EXPECT_ALL_STYLES_EQUAL(Styles) \ 16493 for (size_t i = 1; i < Styles.size(); ++i) \ 16494 EXPECT_EQ(Styles[0], Styles[i]) \ 16495 << "Style #" << i << " of " << Styles.size() << " differs from Style #0" 16496 16497 TEST_F(FormatTest, GetsPredefinedStyleByName) { 16498 SmallVector<FormatStyle, 3> Styles; 16499 Styles.resize(3); 16500 16501 Styles[0] = getLLVMStyle(); 16502 EXPECT_TRUE(getPredefinedStyle("LLVM", FormatStyle::LK_Cpp, &Styles[1])); 16503 EXPECT_TRUE(getPredefinedStyle("lLvM", FormatStyle::LK_Cpp, &Styles[2])); 16504 EXPECT_ALL_STYLES_EQUAL(Styles); 16505 16506 Styles[0] = getGoogleStyle(); 16507 EXPECT_TRUE(getPredefinedStyle("Google", FormatStyle::LK_Cpp, &Styles[1])); 16508 EXPECT_TRUE(getPredefinedStyle("gOOgle", FormatStyle::LK_Cpp, &Styles[2])); 16509 EXPECT_ALL_STYLES_EQUAL(Styles); 16510 16511 Styles[0] = getGoogleStyle(FormatStyle::LK_JavaScript); 16512 EXPECT_TRUE( 16513 getPredefinedStyle("Google", FormatStyle::LK_JavaScript, &Styles[1])); 16514 EXPECT_TRUE( 16515 getPredefinedStyle("gOOgle", FormatStyle::LK_JavaScript, &Styles[2])); 16516 EXPECT_ALL_STYLES_EQUAL(Styles); 16517 16518 Styles[0] = getChromiumStyle(FormatStyle::LK_Cpp); 16519 EXPECT_TRUE(getPredefinedStyle("Chromium", FormatStyle::LK_Cpp, &Styles[1])); 16520 EXPECT_TRUE(getPredefinedStyle("cHRoMiUM", FormatStyle::LK_Cpp, &Styles[2])); 16521 EXPECT_ALL_STYLES_EQUAL(Styles); 16522 16523 Styles[0] = getMozillaStyle(); 16524 EXPECT_TRUE(getPredefinedStyle("Mozilla", FormatStyle::LK_Cpp, &Styles[1])); 16525 EXPECT_TRUE(getPredefinedStyle("moZILla", FormatStyle::LK_Cpp, &Styles[2])); 16526 EXPECT_ALL_STYLES_EQUAL(Styles); 16527 16528 Styles[0] = getWebKitStyle(); 16529 EXPECT_TRUE(getPredefinedStyle("WebKit", FormatStyle::LK_Cpp, &Styles[1])); 16530 EXPECT_TRUE(getPredefinedStyle("wEbKit", FormatStyle::LK_Cpp, &Styles[2])); 16531 EXPECT_ALL_STYLES_EQUAL(Styles); 16532 16533 Styles[0] = getGNUStyle(); 16534 EXPECT_TRUE(getPredefinedStyle("GNU", FormatStyle::LK_Cpp, &Styles[1])); 16535 EXPECT_TRUE(getPredefinedStyle("gnU", FormatStyle::LK_Cpp, &Styles[2])); 16536 EXPECT_ALL_STYLES_EQUAL(Styles); 16537 16538 EXPECT_FALSE(getPredefinedStyle("qwerty", FormatStyle::LK_Cpp, &Styles[0])); 16539 } 16540 16541 TEST_F(FormatTest, GetsCorrectBasedOnStyle) { 16542 SmallVector<FormatStyle, 8> Styles; 16543 Styles.resize(2); 16544 16545 Styles[0] = getGoogleStyle(); 16546 Styles[1] = getLLVMStyle(); 16547 EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Styles[1]).value()); 16548 EXPECT_ALL_STYLES_EQUAL(Styles); 16549 16550 Styles.resize(5); 16551 Styles[0] = getGoogleStyle(FormatStyle::LK_JavaScript); 16552 Styles[1] = getLLVMStyle(); 16553 Styles[1].Language = FormatStyle::LK_JavaScript; 16554 EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Styles[1]).value()); 16555 16556 Styles[2] = getLLVMStyle(); 16557 Styles[2].Language = FormatStyle::LK_JavaScript; 16558 EXPECT_EQ(0, parseConfiguration("Language: JavaScript\n" 16559 "BasedOnStyle: Google", 16560 &Styles[2]) 16561 .value()); 16562 16563 Styles[3] = getLLVMStyle(); 16564 Styles[3].Language = FormatStyle::LK_JavaScript; 16565 EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google\n" 16566 "Language: JavaScript", 16567 &Styles[3]) 16568 .value()); 16569 16570 Styles[4] = getLLVMStyle(); 16571 Styles[4].Language = FormatStyle::LK_JavaScript; 16572 EXPECT_EQ(0, parseConfiguration("---\n" 16573 "BasedOnStyle: LLVM\n" 16574 "IndentWidth: 123\n" 16575 "---\n" 16576 "BasedOnStyle: Google\n" 16577 "Language: JavaScript", 16578 &Styles[4]) 16579 .value()); 16580 EXPECT_ALL_STYLES_EQUAL(Styles); 16581 } 16582 16583 #define CHECK_PARSE_BOOL_FIELD(FIELD, CONFIG_NAME) \ 16584 Style.FIELD = false; \ 16585 EXPECT_EQ(0, parseConfiguration(CONFIG_NAME ": true", &Style).value()); \ 16586 EXPECT_TRUE(Style.FIELD); \ 16587 EXPECT_EQ(0, parseConfiguration(CONFIG_NAME ": false", &Style).value()); \ 16588 EXPECT_FALSE(Style.FIELD); 16589 16590 #define CHECK_PARSE_BOOL(FIELD) CHECK_PARSE_BOOL_FIELD(FIELD, #FIELD) 16591 16592 #define CHECK_PARSE_NESTED_BOOL_FIELD(STRUCT, FIELD, CONFIG_NAME) \ 16593 Style.STRUCT.FIELD = false; \ 16594 EXPECT_EQ(0, \ 16595 parseConfiguration(#STRUCT ":\n " CONFIG_NAME ": true", &Style) \ 16596 .value()); \ 16597 EXPECT_TRUE(Style.STRUCT.FIELD); \ 16598 EXPECT_EQ(0, \ 16599 parseConfiguration(#STRUCT ":\n " CONFIG_NAME ": false", &Style) \ 16600 .value()); \ 16601 EXPECT_FALSE(Style.STRUCT.FIELD); 16602 16603 #define CHECK_PARSE_NESTED_BOOL(STRUCT, FIELD) \ 16604 CHECK_PARSE_NESTED_BOOL_FIELD(STRUCT, FIELD, #FIELD) 16605 16606 #define CHECK_PARSE(TEXT, FIELD, VALUE) \ 16607 EXPECT_NE(VALUE, Style.FIELD) << "Initial value already the same!"; \ 16608 EXPECT_EQ(0, parseConfiguration(TEXT, &Style).value()); \ 16609 EXPECT_EQ(VALUE, Style.FIELD) << "Unexpected value after parsing!" 16610 16611 TEST_F(FormatTest, ParsesConfigurationBools) { 16612 FormatStyle Style = {}; 16613 Style.Language = FormatStyle::LK_Cpp; 16614 CHECK_PARSE_BOOL(AlignTrailingComments); 16615 CHECK_PARSE_BOOL(AllowAllArgumentsOnNextLine); 16616 CHECK_PARSE_BOOL(AllowAllConstructorInitializersOnNextLine); 16617 CHECK_PARSE_BOOL(AllowAllParametersOfDeclarationOnNextLine); 16618 CHECK_PARSE_BOOL(AllowShortCaseLabelsOnASingleLine); 16619 CHECK_PARSE_BOOL(AllowShortEnumsOnASingleLine); 16620 CHECK_PARSE_BOOL(AllowShortLoopsOnASingleLine); 16621 CHECK_PARSE_BOOL(BinPackArguments); 16622 CHECK_PARSE_BOOL(BinPackParameters); 16623 CHECK_PARSE_BOOL(BreakAfterJavaFieldAnnotations); 16624 CHECK_PARSE_BOOL(BreakBeforeConceptDeclarations); 16625 CHECK_PARSE_BOOL(BreakBeforeTernaryOperators); 16626 CHECK_PARSE_BOOL(BreakStringLiterals); 16627 CHECK_PARSE_BOOL(CompactNamespaces); 16628 CHECK_PARSE_BOOL(ConstructorInitializerAllOnOneLineOrOnePerLine); 16629 CHECK_PARSE_BOOL(DeriveLineEnding); 16630 CHECK_PARSE_BOOL(DerivePointerAlignment); 16631 CHECK_PARSE_BOOL_FIELD(DerivePointerAlignment, "DerivePointerBinding"); 16632 CHECK_PARSE_BOOL(DisableFormat); 16633 CHECK_PARSE_BOOL(IndentAccessModifiers); 16634 CHECK_PARSE_BOOL(IndentCaseLabels); 16635 CHECK_PARSE_BOOL(IndentCaseBlocks); 16636 CHECK_PARSE_BOOL(IndentGotoLabels); 16637 CHECK_PARSE_BOOL(IndentRequires); 16638 CHECK_PARSE_BOOL(IndentWrappedFunctionNames); 16639 CHECK_PARSE_BOOL(KeepEmptyLinesAtTheStartOfBlocks); 16640 CHECK_PARSE_BOOL(ObjCSpaceAfterProperty); 16641 CHECK_PARSE_BOOL(ObjCSpaceBeforeProtocolList); 16642 CHECK_PARSE_BOOL(Cpp11BracedListStyle); 16643 CHECK_PARSE_BOOL(ReflowComments); 16644 CHECK_PARSE_BOOL(SortUsingDeclarations); 16645 CHECK_PARSE_BOOL(SpacesInParentheses); 16646 CHECK_PARSE_BOOL(SpacesInSquareBrackets); 16647 CHECK_PARSE_BOOL(SpacesInConditionalStatement); 16648 CHECK_PARSE_BOOL(SpaceInEmptyBlock); 16649 CHECK_PARSE_BOOL(SpaceInEmptyParentheses); 16650 CHECK_PARSE_BOOL(SpacesInContainerLiterals); 16651 CHECK_PARSE_BOOL(SpacesInCStyleCastParentheses); 16652 CHECK_PARSE_BOOL(SpaceAfterCStyleCast); 16653 CHECK_PARSE_BOOL(SpaceAfterTemplateKeyword); 16654 CHECK_PARSE_BOOL(SpaceAfterLogicalNot); 16655 CHECK_PARSE_BOOL(SpaceBeforeAssignmentOperators); 16656 CHECK_PARSE_BOOL(SpaceBeforeCaseColon); 16657 CHECK_PARSE_BOOL(SpaceBeforeCpp11BracedList); 16658 CHECK_PARSE_BOOL(SpaceBeforeCtorInitializerColon); 16659 CHECK_PARSE_BOOL(SpaceBeforeInheritanceColon); 16660 CHECK_PARSE_BOOL(SpaceBeforeRangeBasedForLoopColon); 16661 CHECK_PARSE_BOOL(SpaceBeforeSquareBrackets); 16662 CHECK_PARSE_BOOL(UseCRLF); 16663 16664 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterCaseLabel); 16665 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterClass); 16666 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterEnum); 16667 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterFunction); 16668 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterNamespace); 16669 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterObjCDeclaration); 16670 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterStruct); 16671 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterUnion); 16672 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterExternBlock); 16673 CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeCatch); 16674 CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeElse); 16675 CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeLambdaBody); 16676 CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeWhile); 16677 CHECK_PARSE_NESTED_BOOL(BraceWrapping, IndentBraces); 16678 CHECK_PARSE_NESTED_BOOL(BraceWrapping, SplitEmptyFunction); 16679 CHECK_PARSE_NESTED_BOOL(BraceWrapping, SplitEmptyRecord); 16680 CHECK_PARSE_NESTED_BOOL(BraceWrapping, SplitEmptyNamespace); 16681 } 16682 16683 #undef CHECK_PARSE_BOOL 16684 16685 TEST_F(FormatTest, ParsesConfiguration) { 16686 FormatStyle Style = {}; 16687 Style.Language = FormatStyle::LK_Cpp; 16688 CHECK_PARSE("AccessModifierOffset: -1234", AccessModifierOffset, -1234); 16689 CHECK_PARSE("ConstructorInitializerIndentWidth: 1234", 16690 ConstructorInitializerIndentWidth, 1234u); 16691 CHECK_PARSE("ObjCBlockIndentWidth: 1234", ObjCBlockIndentWidth, 1234u); 16692 CHECK_PARSE("ColumnLimit: 1234", ColumnLimit, 1234u); 16693 CHECK_PARSE("MaxEmptyLinesToKeep: 1234", MaxEmptyLinesToKeep, 1234u); 16694 CHECK_PARSE("PenaltyBreakAssignment: 1234", PenaltyBreakAssignment, 1234u); 16695 CHECK_PARSE("PenaltyBreakBeforeFirstCallParameter: 1234", 16696 PenaltyBreakBeforeFirstCallParameter, 1234u); 16697 CHECK_PARSE("PenaltyBreakTemplateDeclaration: 1234", 16698 PenaltyBreakTemplateDeclaration, 1234u); 16699 CHECK_PARSE("PenaltyExcessCharacter: 1234", PenaltyExcessCharacter, 1234u); 16700 CHECK_PARSE("PenaltyReturnTypeOnItsOwnLine: 1234", 16701 PenaltyReturnTypeOnItsOwnLine, 1234u); 16702 CHECK_PARSE("SpacesBeforeTrailingComments: 1234", 16703 SpacesBeforeTrailingComments, 1234u); 16704 CHECK_PARSE("IndentWidth: 32", IndentWidth, 32u); 16705 CHECK_PARSE("ContinuationIndentWidth: 11", ContinuationIndentWidth, 11u); 16706 CHECK_PARSE("CommentPragmas: '// abc$'", CommentPragmas, "// abc$"); 16707 16708 Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive; 16709 CHECK_PARSE("AlignConsecutiveAssignments: None", AlignConsecutiveAssignments, 16710 FormatStyle::ACS_None); 16711 CHECK_PARSE("AlignConsecutiveAssignments: Consecutive", 16712 AlignConsecutiveAssignments, FormatStyle::ACS_Consecutive); 16713 CHECK_PARSE("AlignConsecutiveAssignments: AcrossEmptyLines", 16714 AlignConsecutiveAssignments, FormatStyle::ACS_AcrossEmptyLines); 16715 CHECK_PARSE("AlignConsecutiveAssignments: AcrossEmptyLinesAndComments", 16716 AlignConsecutiveAssignments, 16717 FormatStyle::ACS_AcrossEmptyLinesAndComments); 16718 // For backwards compability, false / true should still parse 16719 CHECK_PARSE("AlignConsecutiveAssignments: false", AlignConsecutiveAssignments, 16720 FormatStyle::ACS_None); 16721 CHECK_PARSE("AlignConsecutiveAssignments: true", AlignConsecutiveAssignments, 16722 FormatStyle::ACS_Consecutive); 16723 16724 Style.AlignConsecutiveBitFields = FormatStyle::ACS_Consecutive; 16725 CHECK_PARSE("AlignConsecutiveBitFields: None", AlignConsecutiveBitFields, 16726 FormatStyle::ACS_None); 16727 CHECK_PARSE("AlignConsecutiveBitFields: Consecutive", 16728 AlignConsecutiveBitFields, FormatStyle::ACS_Consecutive); 16729 CHECK_PARSE("AlignConsecutiveBitFields: AcrossEmptyLines", 16730 AlignConsecutiveBitFields, FormatStyle::ACS_AcrossEmptyLines); 16731 CHECK_PARSE("AlignConsecutiveBitFields: AcrossEmptyLinesAndComments", 16732 AlignConsecutiveBitFields, 16733 FormatStyle::ACS_AcrossEmptyLinesAndComments); 16734 // For backwards compability, false / true should still parse 16735 CHECK_PARSE("AlignConsecutiveBitFields: false", AlignConsecutiveBitFields, 16736 FormatStyle::ACS_None); 16737 CHECK_PARSE("AlignConsecutiveBitFields: true", AlignConsecutiveBitFields, 16738 FormatStyle::ACS_Consecutive); 16739 16740 Style.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive; 16741 CHECK_PARSE("AlignConsecutiveMacros: None", AlignConsecutiveMacros, 16742 FormatStyle::ACS_None); 16743 CHECK_PARSE("AlignConsecutiveMacros: Consecutive", AlignConsecutiveMacros, 16744 FormatStyle::ACS_Consecutive); 16745 CHECK_PARSE("AlignConsecutiveMacros: AcrossEmptyLines", 16746 AlignConsecutiveMacros, FormatStyle::ACS_AcrossEmptyLines); 16747 CHECK_PARSE("AlignConsecutiveMacros: AcrossEmptyLinesAndComments", 16748 AlignConsecutiveMacros, 16749 FormatStyle::ACS_AcrossEmptyLinesAndComments); 16750 // For backwards compability, false / true should still parse 16751 CHECK_PARSE("AlignConsecutiveMacros: false", AlignConsecutiveMacros, 16752 FormatStyle::ACS_None); 16753 CHECK_PARSE("AlignConsecutiveMacros: true", AlignConsecutiveMacros, 16754 FormatStyle::ACS_Consecutive); 16755 16756 Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 16757 CHECK_PARSE("AlignConsecutiveDeclarations: None", 16758 AlignConsecutiveDeclarations, FormatStyle::ACS_None); 16759 CHECK_PARSE("AlignConsecutiveDeclarations: Consecutive", 16760 AlignConsecutiveDeclarations, FormatStyle::ACS_Consecutive); 16761 CHECK_PARSE("AlignConsecutiveDeclarations: AcrossEmptyLines", 16762 AlignConsecutiveDeclarations, FormatStyle::ACS_AcrossEmptyLines); 16763 CHECK_PARSE("AlignConsecutiveDeclarations: AcrossEmptyLinesAndComments", 16764 AlignConsecutiveDeclarations, 16765 FormatStyle::ACS_AcrossEmptyLinesAndComments); 16766 // For backwards compability, false / true should still parse 16767 CHECK_PARSE("AlignConsecutiveDeclarations: false", 16768 AlignConsecutiveDeclarations, FormatStyle::ACS_None); 16769 CHECK_PARSE("AlignConsecutiveDeclarations: true", 16770 AlignConsecutiveDeclarations, FormatStyle::ACS_Consecutive); 16771 16772 Style.PointerAlignment = FormatStyle::PAS_Middle; 16773 CHECK_PARSE("PointerAlignment: Left", PointerAlignment, 16774 FormatStyle::PAS_Left); 16775 CHECK_PARSE("PointerAlignment: Right", PointerAlignment, 16776 FormatStyle::PAS_Right); 16777 CHECK_PARSE("PointerAlignment: Middle", PointerAlignment, 16778 FormatStyle::PAS_Middle); 16779 // For backward compatibility: 16780 CHECK_PARSE("PointerBindsToType: Left", PointerAlignment, 16781 FormatStyle::PAS_Left); 16782 CHECK_PARSE("PointerBindsToType: Right", PointerAlignment, 16783 FormatStyle::PAS_Right); 16784 CHECK_PARSE("PointerBindsToType: Middle", PointerAlignment, 16785 FormatStyle::PAS_Middle); 16786 16787 Style.Standard = FormatStyle::LS_Auto; 16788 CHECK_PARSE("Standard: c++03", Standard, FormatStyle::LS_Cpp03); 16789 CHECK_PARSE("Standard: c++11", Standard, FormatStyle::LS_Cpp11); 16790 CHECK_PARSE("Standard: c++14", Standard, FormatStyle::LS_Cpp14); 16791 CHECK_PARSE("Standard: c++17", Standard, FormatStyle::LS_Cpp17); 16792 CHECK_PARSE("Standard: c++20", Standard, FormatStyle::LS_Cpp20); 16793 CHECK_PARSE("Standard: Auto", Standard, FormatStyle::LS_Auto); 16794 CHECK_PARSE("Standard: Latest", Standard, FormatStyle::LS_Latest); 16795 // Legacy aliases: 16796 CHECK_PARSE("Standard: Cpp03", Standard, FormatStyle::LS_Cpp03); 16797 CHECK_PARSE("Standard: Cpp11", Standard, FormatStyle::LS_Latest); 16798 CHECK_PARSE("Standard: C++03", Standard, FormatStyle::LS_Cpp03); 16799 CHECK_PARSE("Standard: C++11", Standard, FormatStyle::LS_Cpp11); 16800 16801 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 16802 CHECK_PARSE("BreakBeforeBinaryOperators: NonAssignment", 16803 BreakBeforeBinaryOperators, FormatStyle::BOS_NonAssignment); 16804 CHECK_PARSE("BreakBeforeBinaryOperators: None", BreakBeforeBinaryOperators, 16805 FormatStyle::BOS_None); 16806 CHECK_PARSE("BreakBeforeBinaryOperators: All", BreakBeforeBinaryOperators, 16807 FormatStyle::BOS_All); 16808 // For backward compatibility: 16809 CHECK_PARSE("BreakBeforeBinaryOperators: false", BreakBeforeBinaryOperators, 16810 FormatStyle::BOS_None); 16811 CHECK_PARSE("BreakBeforeBinaryOperators: true", BreakBeforeBinaryOperators, 16812 FormatStyle::BOS_All); 16813 16814 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon; 16815 CHECK_PARSE("BreakConstructorInitializers: BeforeComma", 16816 BreakConstructorInitializers, FormatStyle::BCIS_BeforeComma); 16817 CHECK_PARSE("BreakConstructorInitializers: AfterColon", 16818 BreakConstructorInitializers, FormatStyle::BCIS_AfterColon); 16819 CHECK_PARSE("BreakConstructorInitializers: BeforeColon", 16820 BreakConstructorInitializers, FormatStyle::BCIS_BeforeColon); 16821 // For backward compatibility: 16822 CHECK_PARSE("BreakConstructorInitializersBeforeComma: true", 16823 BreakConstructorInitializers, FormatStyle::BCIS_BeforeComma); 16824 16825 Style.BreakInheritanceList = FormatStyle::BILS_BeforeColon; 16826 CHECK_PARSE("BreakInheritanceList: BeforeComma", BreakInheritanceList, 16827 FormatStyle::BILS_BeforeComma); 16828 CHECK_PARSE("BreakInheritanceList: AfterColon", BreakInheritanceList, 16829 FormatStyle::BILS_AfterColon); 16830 CHECK_PARSE("BreakInheritanceList: BeforeColon", BreakInheritanceList, 16831 FormatStyle::BILS_BeforeColon); 16832 // For backward compatibility: 16833 CHECK_PARSE("BreakBeforeInheritanceComma: true", BreakInheritanceList, 16834 FormatStyle::BILS_BeforeComma); 16835 16836 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock; 16837 CHECK_PARSE("EmptyLineBeforeAccessModifier: Never", 16838 EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_Never); 16839 CHECK_PARSE("EmptyLineBeforeAccessModifier: Leave", 16840 EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_Leave); 16841 CHECK_PARSE("EmptyLineBeforeAccessModifier: LogicalBlock", 16842 EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_LogicalBlock); 16843 CHECK_PARSE("EmptyLineBeforeAccessModifier: Always", 16844 EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_Always); 16845 16846 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 16847 CHECK_PARSE("AlignAfterOpenBracket: Align", AlignAfterOpenBracket, 16848 FormatStyle::BAS_Align); 16849 CHECK_PARSE("AlignAfterOpenBracket: DontAlign", AlignAfterOpenBracket, 16850 FormatStyle::BAS_DontAlign); 16851 CHECK_PARSE("AlignAfterOpenBracket: AlwaysBreak", AlignAfterOpenBracket, 16852 FormatStyle::BAS_AlwaysBreak); 16853 // For backward compatibility: 16854 CHECK_PARSE("AlignAfterOpenBracket: false", AlignAfterOpenBracket, 16855 FormatStyle::BAS_DontAlign); 16856 CHECK_PARSE("AlignAfterOpenBracket: true", AlignAfterOpenBracket, 16857 FormatStyle::BAS_Align); 16858 16859 Style.AlignEscapedNewlines = FormatStyle::ENAS_Left; 16860 CHECK_PARSE("AlignEscapedNewlines: DontAlign", AlignEscapedNewlines, 16861 FormatStyle::ENAS_DontAlign); 16862 CHECK_PARSE("AlignEscapedNewlines: Left", AlignEscapedNewlines, 16863 FormatStyle::ENAS_Left); 16864 CHECK_PARSE("AlignEscapedNewlines: Right", AlignEscapedNewlines, 16865 FormatStyle::ENAS_Right); 16866 // For backward compatibility: 16867 CHECK_PARSE("AlignEscapedNewlinesLeft: true", AlignEscapedNewlines, 16868 FormatStyle::ENAS_Left); 16869 CHECK_PARSE("AlignEscapedNewlinesLeft: false", AlignEscapedNewlines, 16870 FormatStyle::ENAS_Right); 16871 16872 Style.AlignOperands = FormatStyle::OAS_Align; 16873 CHECK_PARSE("AlignOperands: DontAlign", AlignOperands, 16874 FormatStyle::OAS_DontAlign); 16875 CHECK_PARSE("AlignOperands: Align", AlignOperands, FormatStyle::OAS_Align); 16876 CHECK_PARSE("AlignOperands: AlignAfterOperator", AlignOperands, 16877 FormatStyle::OAS_AlignAfterOperator); 16878 // For backward compatibility: 16879 CHECK_PARSE("AlignOperands: false", AlignOperands, 16880 FormatStyle::OAS_DontAlign); 16881 CHECK_PARSE("AlignOperands: true", AlignOperands, FormatStyle::OAS_Align); 16882 16883 Style.UseTab = FormatStyle::UT_ForIndentation; 16884 CHECK_PARSE("UseTab: Never", UseTab, FormatStyle::UT_Never); 16885 CHECK_PARSE("UseTab: ForIndentation", UseTab, FormatStyle::UT_ForIndentation); 16886 CHECK_PARSE("UseTab: Always", UseTab, FormatStyle::UT_Always); 16887 CHECK_PARSE("UseTab: ForContinuationAndIndentation", UseTab, 16888 FormatStyle::UT_ForContinuationAndIndentation); 16889 CHECK_PARSE("UseTab: AlignWithSpaces", UseTab, 16890 FormatStyle::UT_AlignWithSpaces); 16891 // For backward compatibility: 16892 CHECK_PARSE("UseTab: false", UseTab, FormatStyle::UT_Never); 16893 CHECK_PARSE("UseTab: true", UseTab, FormatStyle::UT_Always); 16894 16895 Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Empty; 16896 CHECK_PARSE("AllowShortBlocksOnASingleLine: Never", 16897 AllowShortBlocksOnASingleLine, FormatStyle::SBS_Never); 16898 CHECK_PARSE("AllowShortBlocksOnASingleLine: Empty", 16899 AllowShortBlocksOnASingleLine, FormatStyle::SBS_Empty); 16900 CHECK_PARSE("AllowShortBlocksOnASingleLine: Always", 16901 AllowShortBlocksOnASingleLine, FormatStyle::SBS_Always); 16902 // For backward compatibility: 16903 CHECK_PARSE("AllowShortBlocksOnASingleLine: false", 16904 AllowShortBlocksOnASingleLine, FormatStyle::SBS_Never); 16905 CHECK_PARSE("AllowShortBlocksOnASingleLine: true", 16906 AllowShortBlocksOnASingleLine, FormatStyle::SBS_Always); 16907 16908 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline; 16909 CHECK_PARSE("AllowShortFunctionsOnASingleLine: None", 16910 AllowShortFunctionsOnASingleLine, FormatStyle::SFS_None); 16911 CHECK_PARSE("AllowShortFunctionsOnASingleLine: Inline", 16912 AllowShortFunctionsOnASingleLine, FormatStyle::SFS_Inline); 16913 CHECK_PARSE("AllowShortFunctionsOnASingleLine: Empty", 16914 AllowShortFunctionsOnASingleLine, FormatStyle::SFS_Empty); 16915 CHECK_PARSE("AllowShortFunctionsOnASingleLine: All", 16916 AllowShortFunctionsOnASingleLine, FormatStyle::SFS_All); 16917 // For backward compatibility: 16918 CHECK_PARSE("AllowShortFunctionsOnASingleLine: false", 16919 AllowShortFunctionsOnASingleLine, FormatStyle::SFS_None); 16920 CHECK_PARSE("AllowShortFunctionsOnASingleLine: true", 16921 AllowShortFunctionsOnASingleLine, FormatStyle::SFS_All); 16922 16923 Style.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Both; 16924 CHECK_PARSE("SpaceAroundPointerQualifiers: Default", 16925 SpaceAroundPointerQualifiers, FormatStyle::SAPQ_Default); 16926 CHECK_PARSE("SpaceAroundPointerQualifiers: Before", 16927 SpaceAroundPointerQualifiers, FormatStyle::SAPQ_Before); 16928 CHECK_PARSE("SpaceAroundPointerQualifiers: After", 16929 SpaceAroundPointerQualifiers, FormatStyle::SAPQ_After); 16930 CHECK_PARSE("SpaceAroundPointerQualifiers: Both", 16931 SpaceAroundPointerQualifiers, FormatStyle::SAPQ_Both); 16932 16933 Style.SpaceBeforeParens = FormatStyle::SBPO_Always; 16934 CHECK_PARSE("SpaceBeforeParens: Never", SpaceBeforeParens, 16935 FormatStyle::SBPO_Never); 16936 CHECK_PARSE("SpaceBeforeParens: Always", SpaceBeforeParens, 16937 FormatStyle::SBPO_Always); 16938 CHECK_PARSE("SpaceBeforeParens: ControlStatements", SpaceBeforeParens, 16939 FormatStyle::SBPO_ControlStatements); 16940 CHECK_PARSE("SpaceBeforeParens: NonEmptyParentheses", SpaceBeforeParens, 16941 FormatStyle::SBPO_NonEmptyParentheses); 16942 // For backward compatibility: 16943 CHECK_PARSE("SpaceAfterControlStatementKeyword: false", SpaceBeforeParens, 16944 FormatStyle::SBPO_Never); 16945 CHECK_PARSE("SpaceAfterControlStatementKeyword: true", SpaceBeforeParens, 16946 FormatStyle::SBPO_ControlStatements); 16947 16948 Style.ColumnLimit = 123; 16949 FormatStyle BaseStyle = getLLVMStyle(); 16950 CHECK_PARSE("BasedOnStyle: LLVM", ColumnLimit, BaseStyle.ColumnLimit); 16951 CHECK_PARSE("BasedOnStyle: LLVM\nColumnLimit: 1234", ColumnLimit, 1234u); 16952 16953 Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup; 16954 CHECK_PARSE("BreakBeforeBraces: Attach", BreakBeforeBraces, 16955 FormatStyle::BS_Attach); 16956 CHECK_PARSE("BreakBeforeBraces: Linux", BreakBeforeBraces, 16957 FormatStyle::BS_Linux); 16958 CHECK_PARSE("BreakBeforeBraces: Mozilla", BreakBeforeBraces, 16959 FormatStyle::BS_Mozilla); 16960 CHECK_PARSE("BreakBeforeBraces: Stroustrup", BreakBeforeBraces, 16961 FormatStyle::BS_Stroustrup); 16962 CHECK_PARSE("BreakBeforeBraces: Allman", BreakBeforeBraces, 16963 FormatStyle::BS_Allman); 16964 CHECK_PARSE("BreakBeforeBraces: Whitesmiths", BreakBeforeBraces, 16965 FormatStyle::BS_Whitesmiths); 16966 CHECK_PARSE("BreakBeforeBraces: GNU", BreakBeforeBraces, FormatStyle::BS_GNU); 16967 CHECK_PARSE("BreakBeforeBraces: WebKit", BreakBeforeBraces, 16968 FormatStyle::BS_WebKit); 16969 CHECK_PARSE("BreakBeforeBraces: Custom", BreakBeforeBraces, 16970 FormatStyle::BS_Custom); 16971 16972 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Never; 16973 CHECK_PARSE("BraceWrapping:\n" 16974 " AfterControlStatement: MultiLine", 16975 BraceWrapping.AfterControlStatement, 16976 FormatStyle::BWACS_MultiLine); 16977 CHECK_PARSE("BraceWrapping:\n" 16978 " AfterControlStatement: Always", 16979 BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Always); 16980 CHECK_PARSE("BraceWrapping:\n" 16981 " AfterControlStatement: Never", 16982 BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Never); 16983 // For backward compatibility: 16984 CHECK_PARSE("BraceWrapping:\n" 16985 " AfterControlStatement: true", 16986 BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Always); 16987 CHECK_PARSE("BraceWrapping:\n" 16988 " AfterControlStatement: false", 16989 BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Never); 16990 16991 Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_All; 16992 CHECK_PARSE("AlwaysBreakAfterReturnType: None", AlwaysBreakAfterReturnType, 16993 FormatStyle::RTBS_None); 16994 CHECK_PARSE("AlwaysBreakAfterReturnType: All", AlwaysBreakAfterReturnType, 16995 FormatStyle::RTBS_All); 16996 CHECK_PARSE("AlwaysBreakAfterReturnType: TopLevel", 16997 AlwaysBreakAfterReturnType, FormatStyle::RTBS_TopLevel); 16998 CHECK_PARSE("AlwaysBreakAfterReturnType: AllDefinitions", 16999 AlwaysBreakAfterReturnType, FormatStyle::RTBS_AllDefinitions); 17000 CHECK_PARSE("AlwaysBreakAfterReturnType: TopLevelDefinitions", 17001 AlwaysBreakAfterReturnType, 17002 FormatStyle::RTBS_TopLevelDefinitions); 17003 17004 Style.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes; 17005 CHECK_PARSE("AlwaysBreakTemplateDeclarations: No", 17006 AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_No); 17007 CHECK_PARSE("AlwaysBreakTemplateDeclarations: MultiLine", 17008 AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_MultiLine); 17009 CHECK_PARSE("AlwaysBreakTemplateDeclarations: Yes", 17010 AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_Yes); 17011 CHECK_PARSE("AlwaysBreakTemplateDeclarations: false", 17012 AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_MultiLine); 17013 CHECK_PARSE("AlwaysBreakTemplateDeclarations: true", 17014 AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_Yes); 17015 17016 Style.AlwaysBreakAfterDefinitionReturnType = FormatStyle::DRTBS_All; 17017 CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: None", 17018 AlwaysBreakAfterDefinitionReturnType, FormatStyle::DRTBS_None); 17019 CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: All", 17020 AlwaysBreakAfterDefinitionReturnType, FormatStyle::DRTBS_All); 17021 CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: TopLevel", 17022 AlwaysBreakAfterDefinitionReturnType, 17023 FormatStyle::DRTBS_TopLevel); 17024 17025 Style.NamespaceIndentation = FormatStyle::NI_All; 17026 CHECK_PARSE("NamespaceIndentation: None", NamespaceIndentation, 17027 FormatStyle::NI_None); 17028 CHECK_PARSE("NamespaceIndentation: Inner", NamespaceIndentation, 17029 FormatStyle::NI_Inner); 17030 CHECK_PARSE("NamespaceIndentation: All", NamespaceIndentation, 17031 FormatStyle::NI_All); 17032 17033 Style.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_OnlyFirstIf; 17034 CHECK_PARSE("AllowShortIfStatementsOnASingleLine: Never", 17035 AllowShortIfStatementsOnASingleLine, FormatStyle::SIS_Never); 17036 CHECK_PARSE("AllowShortIfStatementsOnASingleLine: WithoutElse", 17037 AllowShortIfStatementsOnASingleLine, 17038 FormatStyle::SIS_WithoutElse); 17039 CHECK_PARSE("AllowShortIfStatementsOnASingleLine: OnlyFirstIf", 17040 AllowShortIfStatementsOnASingleLine, 17041 FormatStyle::SIS_OnlyFirstIf); 17042 CHECK_PARSE("AllowShortIfStatementsOnASingleLine: AllIfsAndElse", 17043 AllowShortIfStatementsOnASingleLine, 17044 FormatStyle::SIS_AllIfsAndElse); 17045 CHECK_PARSE("AllowShortIfStatementsOnASingleLine: Always", 17046 AllowShortIfStatementsOnASingleLine, 17047 FormatStyle::SIS_OnlyFirstIf); 17048 CHECK_PARSE("AllowShortIfStatementsOnASingleLine: false", 17049 AllowShortIfStatementsOnASingleLine, FormatStyle::SIS_Never); 17050 CHECK_PARSE("AllowShortIfStatementsOnASingleLine: true", 17051 AllowShortIfStatementsOnASingleLine, 17052 FormatStyle::SIS_WithoutElse); 17053 17054 Style.IndentExternBlock = FormatStyle::IEBS_NoIndent; 17055 CHECK_PARSE("IndentExternBlock: AfterExternBlock", IndentExternBlock, 17056 FormatStyle::IEBS_AfterExternBlock); 17057 CHECK_PARSE("IndentExternBlock: Indent", IndentExternBlock, 17058 FormatStyle::IEBS_Indent); 17059 CHECK_PARSE("IndentExternBlock: NoIndent", IndentExternBlock, 17060 FormatStyle::IEBS_NoIndent); 17061 CHECK_PARSE("IndentExternBlock: true", IndentExternBlock, 17062 FormatStyle::IEBS_Indent); 17063 CHECK_PARSE("IndentExternBlock: false", IndentExternBlock, 17064 FormatStyle::IEBS_NoIndent); 17065 17066 Style.BitFieldColonSpacing = FormatStyle::BFCS_None; 17067 CHECK_PARSE("BitFieldColonSpacing: Both", BitFieldColonSpacing, 17068 FormatStyle::BFCS_Both); 17069 CHECK_PARSE("BitFieldColonSpacing: None", BitFieldColonSpacing, 17070 FormatStyle::BFCS_None); 17071 CHECK_PARSE("BitFieldColonSpacing: Before", BitFieldColonSpacing, 17072 FormatStyle::BFCS_Before); 17073 CHECK_PARSE("BitFieldColonSpacing: After", BitFieldColonSpacing, 17074 FormatStyle::BFCS_After); 17075 17076 Style.SortJavaStaticImport = FormatStyle::SJSIO_Before; 17077 CHECK_PARSE("SortJavaStaticImport: After", SortJavaStaticImport, 17078 FormatStyle::SJSIO_After); 17079 CHECK_PARSE("SortJavaStaticImport: Before", SortJavaStaticImport, 17080 FormatStyle::SJSIO_Before); 17081 17082 // FIXME: This is required because parsing a configuration simply overwrites 17083 // the first N elements of the list instead of resetting it. 17084 Style.ForEachMacros.clear(); 17085 std::vector<std::string> BoostForeach; 17086 BoostForeach.push_back("BOOST_FOREACH"); 17087 CHECK_PARSE("ForEachMacros: [BOOST_FOREACH]", ForEachMacros, BoostForeach); 17088 std::vector<std::string> BoostAndQForeach; 17089 BoostAndQForeach.push_back("BOOST_FOREACH"); 17090 BoostAndQForeach.push_back("Q_FOREACH"); 17091 CHECK_PARSE("ForEachMacros: [BOOST_FOREACH, Q_FOREACH]", ForEachMacros, 17092 BoostAndQForeach); 17093 17094 Style.AttributeMacros.clear(); 17095 CHECK_PARSE("BasedOnStyle: LLVM", AttributeMacros, 17096 std::vector<std::string>{"__capability"}); 17097 CHECK_PARSE("AttributeMacros: [attr1, attr2]", AttributeMacros, 17098 std::vector<std::string>({"attr1", "attr2"})); 17099 17100 Style.StatementAttributeLikeMacros.clear(); 17101 CHECK_PARSE("StatementAttributeLikeMacros: [emit,Q_EMIT]", 17102 StatementAttributeLikeMacros, 17103 std::vector<std::string>({"emit", "Q_EMIT"})); 17104 17105 Style.StatementMacros.clear(); 17106 CHECK_PARSE("StatementMacros: [QUNUSED]", StatementMacros, 17107 std::vector<std::string>{"QUNUSED"}); 17108 CHECK_PARSE("StatementMacros: [QUNUSED, QT_REQUIRE_VERSION]", StatementMacros, 17109 std::vector<std::string>({"QUNUSED", "QT_REQUIRE_VERSION"})); 17110 17111 Style.NamespaceMacros.clear(); 17112 CHECK_PARSE("NamespaceMacros: [TESTSUITE]", NamespaceMacros, 17113 std::vector<std::string>{"TESTSUITE"}); 17114 CHECK_PARSE("NamespaceMacros: [TESTSUITE, SUITE]", NamespaceMacros, 17115 std::vector<std::string>({"TESTSUITE", "SUITE"})); 17116 17117 Style.WhitespaceSensitiveMacros.clear(); 17118 CHECK_PARSE("WhitespaceSensitiveMacros: [STRINGIZE]", 17119 WhitespaceSensitiveMacros, std::vector<std::string>{"STRINGIZE"}); 17120 CHECK_PARSE("WhitespaceSensitiveMacros: [STRINGIZE, ASSERT]", 17121 WhitespaceSensitiveMacros, 17122 std::vector<std::string>({"STRINGIZE", "ASSERT"})); 17123 Style.WhitespaceSensitiveMacros.clear(); 17124 CHECK_PARSE("WhitespaceSensitiveMacros: ['STRINGIZE']", 17125 WhitespaceSensitiveMacros, std::vector<std::string>{"STRINGIZE"}); 17126 CHECK_PARSE("WhitespaceSensitiveMacros: ['STRINGIZE', 'ASSERT']", 17127 WhitespaceSensitiveMacros, 17128 std::vector<std::string>({"STRINGIZE", "ASSERT"})); 17129 17130 Style.IncludeStyle.IncludeCategories.clear(); 17131 std::vector<tooling::IncludeStyle::IncludeCategory> ExpectedCategories = { 17132 {"abc/.*", 2, 0, false}, {".*", 1, 0, true}}; 17133 CHECK_PARSE("IncludeCategories:\n" 17134 " - Regex: abc/.*\n" 17135 " Priority: 2\n" 17136 " - Regex: .*\n" 17137 " Priority: 1\n" 17138 " CaseSensitive: true\n", 17139 IncludeStyle.IncludeCategories, ExpectedCategories); 17140 CHECK_PARSE("IncludeIsMainRegex: 'abc$'", IncludeStyle.IncludeIsMainRegex, 17141 "abc$"); 17142 CHECK_PARSE("IncludeIsMainSourceRegex: 'abc$'", 17143 IncludeStyle.IncludeIsMainSourceRegex, "abc$"); 17144 17145 Style.SortIncludes = FormatStyle::SI_Never; 17146 CHECK_PARSE("SortIncludes: true", SortIncludes, 17147 FormatStyle::SI_CaseSensitive); 17148 CHECK_PARSE("SortIncludes: false", SortIncludes, FormatStyle::SI_Never); 17149 CHECK_PARSE("SortIncludes: CaseInsensitive", SortIncludes, 17150 FormatStyle::SI_CaseInsensitive); 17151 CHECK_PARSE("SortIncludes: CaseSensitive", SortIncludes, 17152 FormatStyle::SI_CaseSensitive); 17153 CHECK_PARSE("SortIncludes: Never", SortIncludes, FormatStyle::SI_Never); 17154 17155 Style.RawStringFormats.clear(); 17156 std::vector<FormatStyle::RawStringFormat> ExpectedRawStringFormats = { 17157 { 17158 FormatStyle::LK_TextProto, 17159 {"pb", "proto"}, 17160 {"PARSE_TEXT_PROTO"}, 17161 /*CanonicalDelimiter=*/"", 17162 "llvm", 17163 }, 17164 { 17165 FormatStyle::LK_Cpp, 17166 {"cc", "cpp"}, 17167 {"C_CODEBLOCK", "CPPEVAL"}, 17168 /*CanonicalDelimiter=*/"cc", 17169 /*BasedOnStyle=*/"", 17170 }, 17171 }; 17172 17173 CHECK_PARSE("RawStringFormats:\n" 17174 " - Language: TextProto\n" 17175 " Delimiters:\n" 17176 " - 'pb'\n" 17177 " - 'proto'\n" 17178 " EnclosingFunctions:\n" 17179 " - 'PARSE_TEXT_PROTO'\n" 17180 " BasedOnStyle: llvm\n" 17181 " - Language: Cpp\n" 17182 " Delimiters:\n" 17183 " - 'cc'\n" 17184 " - 'cpp'\n" 17185 " EnclosingFunctions:\n" 17186 " - 'C_CODEBLOCK'\n" 17187 " - 'CPPEVAL'\n" 17188 " CanonicalDelimiter: 'cc'", 17189 RawStringFormats, ExpectedRawStringFormats); 17190 17191 CHECK_PARSE("SpacesInLineCommentPrefix:\n" 17192 " Minimum: 0\n" 17193 " Maximum: 0", 17194 SpacesInLineCommentPrefix.Minimum, 0u); 17195 EXPECT_EQ(Style.SpacesInLineCommentPrefix.Maximum, 0u); 17196 Style.SpacesInLineCommentPrefix.Minimum = 1; 17197 CHECK_PARSE("SpacesInLineCommentPrefix:\n" 17198 " Minimum: 2", 17199 SpacesInLineCommentPrefix.Minimum, 0u); 17200 CHECK_PARSE("SpacesInLineCommentPrefix:\n" 17201 " Maximum: -1", 17202 SpacesInLineCommentPrefix.Maximum, -1u); 17203 CHECK_PARSE("SpacesInLineCommentPrefix:\n" 17204 " Minimum: 2", 17205 SpacesInLineCommentPrefix.Minimum, 2u); 17206 CHECK_PARSE("SpacesInLineCommentPrefix:\n" 17207 " Maximum: 1", 17208 SpacesInLineCommentPrefix.Maximum, 1u); 17209 EXPECT_EQ(Style.SpacesInLineCommentPrefix.Minimum, 1u); 17210 17211 Style.SpacesInAngles = FormatStyle::SIAS_Always; 17212 CHECK_PARSE("SpacesInAngles: Never", SpacesInAngles, FormatStyle::SIAS_Never); 17213 CHECK_PARSE("SpacesInAngles: Always", SpacesInAngles, 17214 FormatStyle::SIAS_Always); 17215 CHECK_PARSE("SpacesInAngles: Leave", SpacesInAngles, FormatStyle::SIAS_Leave); 17216 // For backward compatibility: 17217 CHECK_PARSE("SpacesInAngles: false", SpacesInAngles, FormatStyle::SIAS_Never); 17218 CHECK_PARSE("SpacesInAngles: true", SpacesInAngles, FormatStyle::SIAS_Always); 17219 } 17220 17221 TEST_F(FormatTest, ParsesConfigurationWithLanguages) { 17222 FormatStyle Style = {}; 17223 Style.Language = FormatStyle::LK_Cpp; 17224 CHECK_PARSE("Language: Cpp\n" 17225 "IndentWidth: 12", 17226 IndentWidth, 12u); 17227 EXPECT_EQ(parseConfiguration("Language: JavaScript\n" 17228 "IndentWidth: 34", 17229 &Style), 17230 ParseError::Unsuitable); 17231 FormatStyle BinPackedTCS = {}; 17232 BinPackedTCS.Language = FormatStyle::LK_JavaScript; 17233 EXPECT_EQ(parseConfiguration("BinPackArguments: true\n" 17234 "InsertTrailingCommas: Wrapped", 17235 &BinPackedTCS), 17236 ParseError::BinPackTrailingCommaConflict); 17237 EXPECT_EQ(12u, Style.IndentWidth); 17238 CHECK_PARSE("IndentWidth: 56", IndentWidth, 56u); 17239 EXPECT_EQ(FormatStyle::LK_Cpp, Style.Language); 17240 17241 Style.Language = FormatStyle::LK_JavaScript; 17242 CHECK_PARSE("Language: JavaScript\n" 17243 "IndentWidth: 12", 17244 IndentWidth, 12u); 17245 CHECK_PARSE("IndentWidth: 23", IndentWidth, 23u); 17246 EXPECT_EQ(parseConfiguration("Language: Cpp\n" 17247 "IndentWidth: 34", 17248 &Style), 17249 ParseError::Unsuitable); 17250 EXPECT_EQ(23u, Style.IndentWidth); 17251 CHECK_PARSE("IndentWidth: 56", IndentWidth, 56u); 17252 EXPECT_EQ(FormatStyle::LK_JavaScript, Style.Language); 17253 17254 CHECK_PARSE("BasedOnStyle: LLVM\n" 17255 "IndentWidth: 67", 17256 IndentWidth, 67u); 17257 17258 CHECK_PARSE("---\n" 17259 "Language: JavaScript\n" 17260 "IndentWidth: 12\n" 17261 "---\n" 17262 "Language: Cpp\n" 17263 "IndentWidth: 34\n" 17264 "...\n", 17265 IndentWidth, 12u); 17266 17267 Style.Language = FormatStyle::LK_Cpp; 17268 CHECK_PARSE("---\n" 17269 "Language: JavaScript\n" 17270 "IndentWidth: 12\n" 17271 "---\n" 17272 "Language: Cpp\n" 17273 "IndentWidth: 34\n" 17274 "...\n", 17275 IndentWidth, 34u); 17276 CHECK_PARSE("---\n" 17277 "IndentWidth: 78\n" 17278 "---\n" 17279 "Language: JavaScript\n" 17280 "IndentWidth: 56\n" 17281 "...\n", 17282 IndentWidth, 78u); 17283 17284 Style.ColumnLimit = 123; 17285 Style.IndentWidth = 234; 17286 Style.BreakBeforeBraces = FormatStyle::BS_Linux; 17287 Style.TabWidth = 345; 17288 EXPECT_FALSE(parseConfiguration("---\n" 17289 "IndentWidth: 456\n" 17290 "BreakBeforeBraces: Allman\n" 17291 "---\n" 17292 "Language: JavaScript\n" 17293 "IndentWidth: 111\n" 17294 "TabWidth: 111\n" 17295 "---\n" 17296 "Language: Cpp\n" 17297 "BreakBeforeBraces: Stroustrup\n" 17298 "TabWidth: 789\n" 17299 "...\n", 17300 &Style)); 17301 EXPECT_EQ(123u, Style.ColumnLimit); 17302 EXPECT_EQ(456u, Style.IndentWidth); 17303 EXPECT_EQ(FormatStyle::BS_Stroustrup, Style.BreakBeforeBraces); 17304 EXPECT_EQ(789u, Style.TabWidth); 17305 17306 EXPECT_EQ(parseConfiguration("---\n" 17307 "Language: JavaScript\n" 17308 "IndentWidth: 56\n" 17309 "---\n" 17310 "IndentWidth: 78\n" 17311 "...\n", 17312 &Style), 17313 ParseError::Error); 17314 EXPECT_EQ(parseConfiguration("---\n" 17315 "Language: JavaScript\n" 17316 "IndentWidth: 56\n" 17317 "---\n" 17318 "Language: JavaScript\n" 17319 "IndentWidth: 78\n" 17320 "...\n", 17321 &Style), 17322 ParseError::Error); 17323 17324 EXPECT_EQ(FormatStyle::LK_Cpp, Style.Language); 17325 } 17326 17327 #undef CHECK_PARSE 17328 17329 TEST_F(FormatTest, UsesLanguageForBasedOnStyle) { 17330 FormatStyle Style = {}; 17331 Style.Language = FormatStyle::LK_JavaScript; 17332 Style.BreakBeforeTernaryOperators = true; 17333 EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Style).value()); 17334 EXPECT_FALSE(Style.BreakBeforeTernaryOperators); 17335 17336 Style.BreakBeforeTernaryOperators = true; 17337 EXPECT_EQ(0, parseConfiguration("---\n" 17338 "BasedOnStyle: Google\n" 17339 "---\n" 17340 "Language: JavaScript\n" 17341 "IndentWidth: 76\n" 17342 "...\n", 17343 &Style) 17344 .value()); 17345 EXPECT_FALSE(Style.BreakBeforeTernaryOperators); 17346 EXPECT_EQ(76u, Style.IndentWidth); 17347 EXPECT_EQ(FormatStyle::LK_JavaScript, Style.Language); 17348 } 17349 17350 TEST_F(FormatTest, ConfigurationRoundTripTest) { 17351 FormatStyle Style = getLLVMStyle(); 17352 std::string YAML = configurationAsText(Style); 17353 FormatStyle ParsedStyle = {}; 17354 ParsedStyle.Language = FormatStyle::LK_Cpp; 17355 EXPECT_EQ(0, parseConfiguration(YAML, &ParsedStyle).value()); 17356 EXPECT_EQ(Style, ParsedStyle); 17357 } 17358 17359 TEST_F(FormatTest, WorksFor8bitEncodings) { 17360 EXPECT_EQ("\"\xce\xe4\xed\xe0\xe6\xe4\xfb \xe2 \"\n" 17361 "\"\xf1\xf2\xf3\xe4\xb8\xed\xf3\xfe \"\n" 17362 "\"\xe7\xe8\xec\xed\xfe\xfe \"\n" 17363 "\"\xef\xee\xf0\xf3...\"", 17364 format("\"\xce\xe4\xed\xe0\xe6\xe4\xfb \xe2 " 17365 "\xf1\xf2\xf3\xe4\xb8\xed\xf3\xfe \xe7\xe8\xec\xed\xfe\xfe " 17366 "\xef\xee\xf0\xf3...\"", 17367 getLLVMStyleWithColumns(12))); 17368 } 17369 17370 TEST_F(FormatTest, HandlesUTF8BOM) { 17371 EXPECT_EQ("\xef\xbb\xbf", format("\xef\xbb\xbf")); 17372 EXPECT_EQ("\xef\xbb\xbf#include <iostream>", 17373 format("\xef\xbb\xbf#include <iostream>")); 17374 EXPECT_EQ("\xef\xbb\xbf\n#include <iostream>", 17375 format("\xef\xbb\xbf\n#include <iostream>")); 17376 } 17377 17378 // FIXME: Encode Cyrillic and CJK characters below to appease MS compilers. 17379 #if !defined(_MSC_VER) 17380 17381 TEST_F(FormatTest, CountsUTF8CharactersProperly) { 17382 verifyFormat("\"Однажды в студёную зимнюю пору...\"", 17383 getLLVMStyleWithColumns(35)); 17384 verifyFormat("\"一 二 三 四 五 六 七 八 九 十\"", 17385 getLLVMStyleWithColumns(31)); 17386 verifyFormat("// Однажды в студёную зимнюю пору...", 17387 getLLVMStyleWithColumns(36)); 17388 verifyFormat("// 一 二 三 四 五 六 七 八 九 十", getLLVMStyleWithColumns(32)); 17389 verifyFormat("/* Однажды в студёную зимнюю пору... */", 17390 getLLVMStyleWithColumns(39)); 17391 verifyFormat("/* 一 二 三 四 五 六 七 八 九 十 */", 17392 getLLVMStyleWithColumns(35)); 17393 } 17394 17395 TEST_F(FormatTest, SplitsUTF8Strings) { 17396 // Non-printable characters' width is currently considered to be the length in 17397 // bytes in UTF8. The characters can be displayed in very different manner 17398 // (zero-width, single width with a substitution glyph, expanded to their code 17399 // (e.g. "<8d>"), so there's no single correct way to handle them. 17400 EXPECT_EQ("\"aaaaÄ\"\n" 17401 "\"\xc2\x8d\";", 17402 format("\"aaaaÄ\xc2\x8d\";", getLLVMStyleWithColumns(10))); 17403 EXPECT_EQ("\"aaaaaaaÄ\"\n" 17404 "\"\xc2\x8d\";", 17405 format("\"aaaaaaaÄ\xc2\x8d\";", getLLVMStyleWithColumns(10))); 17406 EXPECT_EQ("\"Однажды, в \"\n" 17407 "\"студёную \"\n" 17408 "\"зимнюю \"\n" 17409 "\"пору,\"", 17410 format("\"Однажды, в студёную зимнюю пору,\"", 17411 getLLVMStyleWithColumns(13))); 17412 EXPECT_EQ( 17413 "\"一 二 三 \"\n" 17414 "\"四 五六 \"\n" 17415 "\"七 八 九 \"\n" 17416 "\"十\"", 17417 format("\"一 二 三 四 五六 七 八 九 十\"", getLLVMStyleWithColumns(11))); 17418 EXPECT_EQ("\"一\t\"\n" 17419 "\"二 \t\"\n" 17420 "\"三 四 \"\n" 17421 "\"五\t\"\n" 17422 "\"六 \t\"\n" 17423 "\"七 \"\n" 17424 "\"八九十\tqq\"", 17425 format("\"一\t二 \t三 四 五\t六 \t七 八九十\tqq\"", 17426 getLLVMStyleWithColumns(11))); 17427 17428 // UTF8 character in an escape sequence. 17429 EXPECT_EQ("\"aaaaaa\"\n" 17430 "\"\\\xC2\x8D\"", 17431 format("\"aaaaaa\\\xC2\x8D\"", getLLVMStyleWithColumns(10))); 17432 } 17433 17434 TEST_F(FormatTest, HandlesDoubleWidthCharsInMultiLineStrings) { 17435 EXPECT_EQ("const char *sssss =\n" 17436 " \"一二三四五六七八\\\n" 17437 " 九 十\";", 17438 format("const char *sssss = \"一二三四五六七八\\\n" 17439 " 九 十\";", 17440 getLLVMStyleWithColumns(30))); 17441 } 17442 17443 TEST_F(FormatTest, SplitsUTF8LineComments) { 17444 EXPECT_EQ("// aaaaÄ\xc2\x8d", 17445 format("// aaaaÄ\xc2\x8d", getLLVMStyleWithColumns(10))); 17446 EXPECT_EQ("// Я из лесу\n" 17447 "// вышел; был\n" 17448 "// сильный\n" 17449 "// мороз.", 17450 format("// Я из лесу вышел; был сильный мороз.", 17451 getLLVMStyleWithColumns(13))); 17452 EXPECT_EQ("// 一二三\n" 17453 "// 四五六七\n" 17454 "// 八 九\n" 17455 "// 十", 17456 format("// 一二三 四五六七 八 九 十", getLLVMStyleWithColumns(9))); 17457 } 17458 17459 TEST_F(FormatTest, SplitsUTF8BlockComments) { 17460 EXPECT_EQ("/* Гляжу,\n" 17461 " * поднимается\n" 17462 " * медленно в\n" 17463 " * гору\n" 17464 " * Лошадка,\n" 17465 " * везущая\n" 17466 " * хворосту\n" 17467 " * воз. */", 17468 format("/* Гляжу, поднимается медленно в гору\n" 17469 " * Лошадка, везущая хворосту воз. */", 17470 getLLVMStyleWithColumns(13))); 17471 EXPECT_EQ( 17472 "/* 一二三\n" 17473 " * 四五六七\n" 17474 " * 八 九\n" 17475 " * 十 */", 17476 format("/* 一二三 四五六七 八 九 十 */", getLLVMStyleWithColumns(9))); 17477 EXPECT_EQ("/* \n" 17478 " * \n" 17479 " * - */", 17480 format("/* - */", getLLVMStyleWithColumns(12))); 17481 } 17482 17483 #endif // _MSC_VER 17484 17485 TEST_F(FormatTest, ConstructorInitializerIndentWidth) { 17486 FormatStyle Style = getLLVMStyle(); 17487 17488 Style.ConstructorInitializerIndentWidth = 4; 17489 verifyFormat( 17490 "SomeClass::Constructor()\n" 17491 " : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 17492 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", 17493 Style); 17494 17495 Style.ConstructorInitializerIndentWidth = 2; 17496 verifyFormat( 17497 "SomeClass::Constructor()\n" 17498 " : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 17499 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", 17500 Style); 17501 17502 Style.ConstructorInitializerIndentWidth = 0; 17503 verifyFormat( 17504 "SomeClass::Constructor()\n" 17505 ": aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 17506 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", 17507 Style); 17508 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 17509 verifyFormat( 17510 "SomeLongTemplateVariableName<\n" 17511 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>", 17512 Style); 17513 verifyFormat("bool smaller = 1 < " 17514 "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n" 17515 " " 17516 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 17517 Style); 17518 17519 Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon; 17520 verifyFormat("SomeClass::Constructor() :\n" 17521 "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa),\n" 17522 "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa) {}", 17523 Style); 17524 } 17525 17526 TEST_F(FormatTest, BreakConstructorInitializersBeforeComma) { 17527 FormatStyle Style = getLLVMStyle(); 17528 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma; 17529 Style.ConstructorInitializerIndentWidth = 4; 17530 verifyFormat("SomeClass::Constructor()\n" 17531 " : a(a)\n" 17532 " , b(b)\n" 17533 " , c(c) {}", 17534 Style); 17535 verifyFormat("SomeClass::Constructor()\n" 17536 " : a(a) {}", 17537 Style); 17538 17539 Style.ColumnLimit = 0; 17540 verifyFormat("SomeClass::Constructor()\n" 17541 " : a(a) {}", 17542 Style); 17543 verifyFormat("SomeClass::Constructor() noexcept\n" 17544 " : a(a) {}", 17545 Style); 17546 verifyFormat("SomeClass::Constructor()\n" 17547 " : a(a)\n" 17548 " , b(b)\n" 17549 " , c(c) {}", 17550 Style); 17551 verifyFormat("SomeClass::Constructor()\n" 17552 " : a(a) {\n" 17553 " foo();\n" 17554 " bar();\n" 17555 "}", 17556 Style); 17557 17558 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 17559 verifyFormat("SomeClass::Constructor()\n" 17560 " : a(a)\n" 17561 " , b(b)\n" 17562 " , c(c) {\n}", 17563 Style); 17564 verifyFormat("SomeClass::Constructor()\n" 17565 " : a(a) {\n}", 17566 Style); 17567 17568 Style.ColumnLimit = 80; 17569 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All; 17570 Style.ConstructorInitializerIndentWidth = 2; 17571 verifyFormat("SomeClass::Constructor()\n" 17572 " : a(a)\n" 17573 " , b(b)\n" 17574 " , c(c) {}", 17575 Style); 17576 17577 Style.ConstructorInitializerIndentWidth = 0; 17578 verifyFormat("SomeClass::Constructor()\n" 17579 ": a(a)\n" 17580 ", b(b)\n" 17581 ", c(c) {}", 17582 Style); 17583 17584 Style.ConstructorInitializerAllOnOneLineOrOnePerLine = true; 17585 Style.ConstructorInitializerIndentWidth = 4; 17586 verifyFormat("SomeClass::Constructor() : aaaaaaaa(aaaaaaaa) {}", Style); 17587 verifyFormat( 17588 "SomeClass::Constructor() : aaaaa(aaaaa), aaaaa(aaaaa), aaaaa(aaaaa)\n", 17589 Style); 17590 verifyFormat( 17591 "SomeClass::Constructor()\n" 17592 " : aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaa) {}", 17593 Style); 17594 Style.ConstructorInitializerIndentWidth = 4; 17595 Style.ColumnLimit = 60; 17596 verifyFormat("SomeClass::Constructor()\n" 17597 " : aaaaaaaa(aaaaaaaa)\n" 17598 " , aaaaaaaa(aaaaaaaa)\n" 17599 " , aaaaaaaa(aaaaaaaa) {}", 17600 Style); 17601 } 17602 17603 TEST_F(FormatTest, Destructors) { 17604 verifyFormat("void F(int &i) { i.~int(); }"); 17605 verifyFormat("void F(int &i) { i->~int(); }"); 17606 } 17607 17608 TEST_F(FormatTest, FormatsWithWebKitStyle) { 17609 FormatStyle Style = getWebKitStyle(); 17610 17611 // Don't indent in outer namespaces. 17612 verifyFormat("namespace outer {\n" 17613 "int i;\n" 17614 "namespace inner {\n" 17615 " int i;\n" 17616 "} // namespace inner\n" 17617 "} // namespace outer\n" 17618 "namespace other_outer {\n" 17619 "int i;\n" 17620 "}", 17621 Style); 17622 17623 // Don't indent case labels. 17624 verifyFormat("switch (variable) {\n" 17625 "case 1:\n" 17626 "case 2:\n" 17627 " doSomething();\n" 17628 " break;\n" 17629 "default:\n" 17630 " ++variable;\n" 17631 "}", 17632 Style); 17633 17634 // Wrap before binary operators. 17635 EXPECT_EQ("void f()\n" 17636 "{\n" 17637 " if (aaaaaaaaaaaaaaaa\n" 17638 " && bbbbbbbbbbbbbbbbbbbbbbbb\n" 17639 " && (cccccccccccccccccccccccccc || dddddddddddddddddddd))\n" 17640 " return;\n" 17641 "}", 17642 format("void f() {\n" 17643 "if (aaaaaaaaaaaaaaaa\n" 17644 "&& bbbbbbbbbbbbbbbbbbbbbbbb\n" 17645 "&& (cccccccccccccccccccccccccc || dddddddddddddddddddd))\n" 17646 "return;\n" 17647 "}", 17648 Style)); 17649 17650 // Allow functions on a single line. 17651 verifyFormat("void f() { return; }", Style); 17652 17653 // Allow empty blocks on a single line and insert a space in empty blocks. 17654 EXPECT_EQ("void f() { }", format("void f() {}", Style)); 17655 EXPECT_EQ("while (true) { }", format("while (true) {}", Style)); 17656 // However, don't merge non-empty short loops. 17657 EXPECT_EQ("while (true) {\n" 17658 " continue;\n" 17659 "}", 17660 format("while (true) { continue; }", Style)); 17661 17662 // Constructor initializers are formatted one per line with the "," on the 17663 // new line. 17664 verifyFormat("Constructor()\n" 17665 " : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 17666 " , aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaa, // break\n" 17667 " aaaaaaaaaaaaaa)\n" 17668 " , aaaaaaaaaaaaaaaaaaaaaaa()\n" 17669 "{\n" 17670 "}", 17671 Style); 17672 verifyFormat("SomeClass::Constructor()\n" 17673 " : a(a)\n" 17674 "{\n" 17675 "}", 17676 Style); 17677 EXPECT_EQ("SomeClass::Constructor()\n" 17678 " : a(a)\n" 17679 "{\n" 17680 "}", 17681 format("SomeClass::Constructor():a(a){}", Style)); 17682 verifyFormat("SomeClass::Constructor()\n" 17683 " : a(a)\n" 17684 " , b(b)\n" 17685 " , c(c)\n" 17686 "{\n" 17687 "}", 17688 Style); 17689 verifyFormat("SomeClass::Constructor()\n" 17690 " : a(a)\n" 17691 "{\n" 17692 " foo();\n" 17693 " bar();\n" 17694 "}", 17695 Style); 17696 17697 // Access specifiers should be aligned left. 17698 verifyFormat("class C {\n" 17699 "public:\n" 17700 " int i;\n" 17701 "};", 17702 Style); 17703 17704 // Do not align comments. 17705 verifyFormat("int a; // Do not\n" 17706 "double b; // align comments.", 17707 Style); 17708 17709 // Do not align operands. 17710 EXPECT_EQ("ASSERT(aaaa\n" 17711 " || bbbb);", 17712 format("ASSERT ( aaaa\n||bbbb);", Style)); 17713 17714 // Accept input's line breaks. 17715 EXPECT_EQ("if (aaaaaaaaaaaaaaa\n" 17716 " || bbbbbbbbbbbbbbb) {\n" 17717 " i++;\n" 17718 "}", 17719 format("if (aaaaaaaaaaaaaaa\n" 17720 "|| bbbbbbbbbbbbbbb) { i++; }", 17721 Style)); 17722 EXPECT_EQ("if (aaaaaaaaaaaaaaa || bbbbbbbbbbbbbbb) {\n" 17723 " i++;\n" 17724 "}", 17725 format("if (aaaaaaaaaaaaaaa || bbbbbbbbbbbbbbb) { i++; }", Style)); 17726 17727 // Don't automatically break all macro definitions (llvm.org/PR17842). 17728 verifyFormat("#define aNumber 10", Style); 17729 // However, generally keep the line breaks that the user authored. 17730 EXPECT_EQ("#define aNumber \\\n" 17731 " 10", 17732 format("#define aNumber \\\n" 17733 " 10", 17734 Style)); 17735 17736 // Keep empty and one-element array literals on a single line. 17737 EXPECT_EQ("NSArray* a = [[NSArray alloc] initWithArray:@[]\n" 17738 " copyItems:YES];", 17739 format("NSArray*a=[[NSArray alloc] initWithArray:@[]\n" 17740 "copyItems:YES];", 17741 Style)); 17742 EXPECT_EQ("NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\" ]\n" 17743 " copyItems:YES];", 17744 format("NSArray*a=[[NSArray alloc]initWithArray:@[ @\"a\" ]\n" 17745 " copyItems:YES];", 17746 Style)); 17747 // FIXME: This does not seem right, there should be more indentation before 17748 // the array literal's entries. Nested blocks have the same problem. 17749 EXPECT_EQ("NSArray* a = [[NSArray alloc] initWithArray:@[\n" 17750 " @\"a\",\n" 17751 " @\"a\"\n" 17752 "]\n" 17753 " copyItems:YES];", 17754 format("NSArray* a = [[NSArray alloc] initWithArray:@[\n" 17755 " @\"a\",\n" 17756 " @\"a\"\n" 17757 " ]\n" 17758 " copyItems:YES];", 17759 Style)); 17760 EXPECT_EQ( 17761 "NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\", @\"a\" ]\n" 17762 " copyItems:YES];", 17763 format("NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\", @\"a\" ]\n" 17764 " copyItems:YES];", 17765 Style)); 17766 17767 verifyFormat("[self.a b:c c:d];", Style); 17768 EXPECT_EQ("[self.a b:c\n" 17769 " c:d];", 17770 format("[self.a b:c\n" 17771 "c:d];", 17772 Style)); 17773 } 17774 17775 TEST_F(FormatTest, FormatsLambdas) { 17776 verifyFormat("int c = [b]() mutable { return [&b] { return b++; }(); }();\n"); 17777 verifyFormat( 17778 "int c = [b]() mutable noexcept { return [&b] { return b++; }(); }();\n"); 17779 verifyFormat("int c = [&] { [=] { return b++; }(); }();\n"); 17780 verifyFormat("int c = [&, &a, a] { [=, c, &d] { return b++; }(); }();\n"); 17781 verifyFormat("int c = [&a, &a, a] { [=, a, b, &c] { return b++; }(); }();\n"); 17782 verifyFormat("auto c = {[&a, &a, a] { [=, a, b, &c] { return b++; }(); }}\n"); 17783 verifyFormat("auto c = {[&a, &a, a] { [=, a, b, &c] {}(); }}\n"); 17784 verifyFormat("auto c = [a = [b = 42] {}] {};\n"); 17785 verifyFormat("auto c = [a = &i + 10, b = [] {}] {};\n"); 17786 verifyFormat("int x = f(*+[] {});"); 17787 verifyFormat("void f() {\n" 17788 " other(x.begin(), x.end(), [&](int, int) { return 1; });\n" 17789 "}\n"); 17790 verifyFormat("void f() {\n" 17791 " other(x.begin(), //\n" 17792 " x.end(), //\n" 17793 " [&](int, int) { return 1; });\n" 17794 "}\n"); 17795 verifyFormat("void f() {\n" 17796 " other.other.other.other.other(\n" 17797 " x.begin(), x.end(),\n" 17798 " [something, rather](int, int, int, int, int, int, int) { " 17799 "return 1; });\n" 17800 "}\n"); 17801 verifyFormat( 17802 "void f() {\n" 17803 " other.other.other.other.other(\n" 17804 " x.begin(), x.end(),\n" 17805 " [something, rather](int, int, int, int, int, int, int) {\n" 17806 " //\n" 17807 " });\n" 17808 "}\n"); 17809 verifyFormat("SomeFunction([]() { // A cool function...\n" 17810 " return 43;\n" 17811 "});"); 17812 EXPECT_EQ("SomeFunction([]() {\n" 17813 "#define A a\n" 17814 " return 43;\n" 17815 "});", 17816 format("SomeFunction([](){\n" 17817 "#define A a\n" 17818 "return 43;\n" 17819 "});")); 17820 verifyFormat("void f() {\n" 17821 " SomeFunction([](decltype(x), A *a) {});\n" 17822 " SomeFunction([](typeof(x), A *a) {});\n" 17823 " SomeFunction([](_Atomic(x), A *a) {});\n" 17824 " SomeFunction([](__underlying_type(x), A *a) {});\n" 17825 "}"); 17826 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 17827 " [](const aaaaaaaaaa &a) { return a; });"); 17828 verifyFormat("string abc = SomeFunction(aaaaaaaaaaaaa, aaaaa, []() {\n" 17829 " SomeOtherFunctioooooooooooooooooooooooooon();\n" 17830 "});"); 17831 verifyFormat("Constructor()\n" 17832 " : Field([] { // comment\n" 17833 " int i;\n" 17834 " }) {}"); 17835 verifyFormat("auto my_lambda = [](const string &some_parameter) {\n" 17836 " return some_parameter.size();\n" 17837 "};"); 17838 verifyFormat("std::function<std::string(const std::string &)> my_lambda =\n" 17839 " [](const string &s) { return s; };"); 17840 verifyFormat("int i = aaaaaa ? 1 //\n" 17841 " : [] {\n" 17842 " return 2; //\n" 17843 " }();"); 17844 verifyFormat("llvm::errs() << \"number of twos is \"\n" 17845 " << std::count_if(v.begin(), v.end(), [](int x) {\n" 17846 " return x == 2; // force break\n" 17847 " });"); 17848 verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 17849 " [=](int iiiiiiiiiiii) {\n" 17850 " return aaaaaaaaaaaaaaaaaaaaaaa !=\n" 17851 " aaaaaaaaaaaaaaaaaaaaaaa;\n" 17852 " });", 17853 getLLVMStyleWithColumns(60)); 17854 verifyFormat("SomeFunction({[&] {\n" 17855 " // comment\n" 17856 " },\n" 17857 " [&] {\n" 17858 " // comment\n" 17859 " }});"); 17860 verifyFormat("SomeFunction({[&] {\n" 17861 " // comment\n" 17862 "}});"); 17863 verifyFormat( 17864 "virtual aaaaaaaaaaaaaaaa(\n" 17865 " std::function<bool()> bbbbbbbbbbbb = [&]() { return true; },\n" 17866 " aaaaa aaaaaaaaa);"); 17867 17868 // Lambdas with return types. 17869 verifyFormat("int c = []() -> int { return 2; }();\n"); 17870 verifyFormat("int c = []() -> int * { return 2; }();\n"); 17871 verifyFormat("int c = []() -> vector<int> { return {2}; }();\n"); 17872 verifyFormat("Foo([]() -> std::vector<int> { return {2}; }());"); 17873 verifyGoogleFormat("auto a = [&b, c](D* d) -> D* {};"); 17874 verifyGoogleFormat("auto a = [&b, c](D* d) -> pair<D*, D*> {};"); 17875 verifyGoogleFormat("auto a = [&b, c](D* d) -> D& {};"); 17876 verifyGoogleFormat("auto a = [&b, c](D* d) -> const D* {};"); 17877 verifyFormat("[a, a]() -> a<1> {};"); 17878 verifyFormat("[]() -> foo<5 + 2> { return {}; };"); 17879 verifyFormat("[]() -> foo<5 - 2> { return {}; };"); 17880 verifyFormat("[]() -> foo<5 / 2> { return {}; };"); 17881 verifyFormat("[]() -> foo<5 * 2> { return {}; };"); 17882 verifyFormat("[]() -> foo<5 % 2> { return {}; };"); 17883 verifyFormat("[]() -> foo<5 << 2> { return {}; };"); 17884 verifyFormat("[]() -> foo<!5> { return {}; };"); 17885 verifyFormat("[]() -> foo<~5> { return {}; };"); 17886 verifyFormat("[]() -> foo<5 | 2> { return {}; };"); 17887 verifyFormat("[]() -> foo<5 || 2> { return {}; };"); 17888 verifyFormat("[]() -> foo<5 & 2> { return {}; };"); 17889 verifyFormat("[]() -> foo<5 && 2> { return {}; };"); 17890 verifyFormat("[]() -> foo<5 == 2> { return {}; };"); 17891 verifyFormat("[]() -> foo<5 != 2> { return {}; };"); 17892 verifyFormat("[]() -> foo<5 >= 2> { return {}; };"); 17893 verifyFormat("[]() -> foo<5 <= 2> { return {}; };"); 17894 verifyFormat("[]() -> foo<5 < 2> { return {}; };"); 17895 verifyFormat("[]() -> foo<2 ? 1 : 0> { return {}; };"); 17896 verifyFormat("namespace bar {\n" 17897 "// broken:\n" 17898 "auto foo{[]() -> foo<5 + 2> { return {}; }};\n" 17899 "} // namespace bar"); 17900 verifyFormat("namespace bar {\n" 17901 "// broken:\n" 17902 "auto foo{[]() -> foo<5 - 2> { return {}; }};\n" 17903 "} // namespace bar"); 17904 verifyFormat("namespace bar {\n" 17905 "// broken:\n" 17906 "auto foo{[]() -> foo<5 / 2> { return {}; }};\n" 17907 "} // namespace bar"); 17908 verifyFormat("namespace bar {\n" 17909 "// broken:\n" 17910 "auto foo{[]() -> foo<5 * 2> { return {}; }};\n" 17911 "} // namespace bar"); 17912 verifyFormat("namespace bar {\n" 17913 "// broken:\n" 17914 "auto foo{[]() -> foo<5 % 2> { return {}; }};\n" 17915 "} // namespace bar"); 17916 verifyFormat("namespace bar {\n" 17917 "// broken:\n" 17918 "auto foo{[]() -> foo<5 << 2> { return {}; }};\n" 17919 "} // namespace bar"); 17920 verifyFormat("namespace bar {\n" 17921 "// broken:\n" 17922 "auto foo{[]() -> foo<!5> { return {}; }};\n" 17923 "} // namespace bar"); 17924 verifyFormat("namespace bar {\n" 17925 "// broken:\n" 17926 "auto foo{[]() -> foo<~5> { return {}; }};\n" 17927 "} // namespace bar"); 17928 verifyFormat("namespace bar {\n" 17929 "// broken:\n" 17930 "auto foo{[]() -> foo<5 | 2> { return {}; }};\n" 17931 "} // namespace bar"); 17932 verifyFormat("namespace bar {\n" 17933 "// broken:\n" 17934 "auto foo{[]() -> foo<5 || 2> { return {}; }};\n" 17935 "} // namespace bar"); 17936 verifyFormat("namespace bar {\n" 17937 "// broken:\n" 17938 "auto foo{[]() -> foo<5 & 2> { return {}; }};\n" 17939 "} // namespace bar"); 17940 verifyFormat("namespace bar {\n" 17941 "// broken:\n" 17942 "auto foo{[]() -> foo<5 && 2> { return {}; }};\n" 17943 "} // namespace bar"); 17944 verifyFormat("namespace bar {\n" 17945 "// broken:\n" 17946 "auto foo{[]() -> foo<5 == 2> { return {}; }};\n" 17947 "} // namespace bar"); 17948 verifyFormat("namespace bar {\n" 17949 "// broken:\n" 17950 "auto foo{[]() -> foo<5 != 2> { return {}; }};\n" 17951 "} // namespace bar"); 17952 verifyFormat("namespace bar {\n" 17953 "// broken:\n" 17954 "auto foo{[]() -> foo<5 >= 2> { return {}; }};\n" 17955 "} // namespace bar"); 17956 verifyFormat("namespace bar {\n" 17957 "// broken:\n" 17958 "auto foo{[]() -> foo<5 <= 2> { return {}; }};\n" 17959 "} // namespace bar"); 17960 verifyFormat("namespace bar {\n" 17961 "// broken:\n" 17962 "auto foo{[]() -> foo<5 < 2> { return {}; }};\n" 17963 "} // namespace bar"); 17964 verifyFormat("namespace bar {\n" 17965 "// broken:\n" 17966 "auto foo{[]() -> foo<2 ? 1 : 0> { return {}; }};\n" 17967 "} // namespace bar"); 17968 verifyFormat("[]() -> a<1> {};"); 17969 verifyFormat("[]() -> a<1> { ; };"); 17970 verifyFormat("[]() -> a<1> { ; }();"); 17971 verifyFormat("[a, a]() -> a<true> {};"); 17972 verifyFormat("[]() -> a<true> {};"); 17973 verifyFormat("[]() -> a<true> { ; };"); 17974 verifyFormat("[]() -> a<true> { ; }();"); 17975 verifyFormat("[a, a]() -> a<false> {};"); 17976 verifyFormat("[]() -> a<false> {};"); 17977 verifyFormat("[]() -> a<false> { ; };"); 17978 verifyFormat("[]() -> a<false> { ; }();"); 17979 verifyFormat("auto foo{[]() -> foo<false> { ; }};"); 17980 verifyFormat("namespace bar {\n" 17981 "auto foo{[]() -> foo<false> { ; }};\n" 17982 "} // namespace bar"); 17983 verifyFormat("auto aaaaaaaa = [](int i, // break for some reason\n" 17984 " int j) -> int {\n" 17985 " return ffffffffffffffffffffffffffffffffffffffffffff(i * j);\n" 17986 "};"); 17987 verifyFormat( 17988 "aaaaaaaaaaaaaaaaaaaaaa(\n" 17989 " [](aaaaaaaaaaaaaaaaaaaaaaaaaaa &aaa) -> aaaaaaaaaaaaaaaa {\n" 17990 " return aaaaaaaaaaaaaaaaa;\n" 17991 " });", 17992 getLLVMStyleWithColumns(70)); 17993 verifyFormat("[]() //\n" 17994 " -> int {\n" 17995 " return 1; //\n" 17996 "};"); 17997 verifyFormat("[]() -> Void<T...> {};"); 17998 verifyFormat("[a, b]() -> Tuple<T...> { return {}; };"); 17999 18000 // Lambdas with explicit template argument lists. 18001 verifyFormat( 18002 "auto L = []<template <typename> class T, class U>(T<U> &&a) {};\n"); 18003 18004 // Multiple lambdas in the same parentheses change indentation rules. These 18005 // lambdas are forced to start on new lines. 18006 verifyFormat("SomeFunction(\n" 18007 " []() {\n" 18008 " //\n" 18009 " },\n" 18010 " []() {\n" 18011 " //\n" 18012 " });"); 18013 18014 // A lambda passed as arg0 is always pushed to the next line. 18015 verifyFormat("SomeFunction(\n" 18016 " [this] {\n" 18017 " //\n" 18018 " },\n" 18019 " 1);\n"); 18020 18021 // A multi-line lambda passed as arg1 forces arg0 to be pushed out, just like 18022 // the arg0 case above. 18023 auto Style = getGoogleStyle(); 18024 Style.BinPackArguments = false; 18025 verifyFormat("SomeFunction(\n" 18026 " a,\n" 18027 " [this] {\n" 18028 " //\n" 18029 " },\n" 18030 " b);\n", 18031 Style); 18032 verifyFormat("SomeFunction(\n" 18033 " a,\n" 18034 " [this] {\n" 18035 " //\n" 18036 " },\n" 18037 " b);\n"); 18038 18039 // A lambda with a very long line forces arg0 to be pushed out irrespective of 18040 // the BinPackArguments value (as long as the code is wide enough). 18041 verifyFormat( 18042 "something->SomeFunction(\n" 18043 " a,\n" 18044 " [this] {\n" 18045 " " 18046 "D0000000000000000000000000000000000000000000000000000000000001();\n" 18047 " },\n" 18048 " b);\n"); 18049 18050 // A multi-line lambda is pulled up as long as the introducer fits on the 18051 // previous line and there are no further args. 18052 verifyFormat("function(1, [this, that] {\n" 18053 " //\n" 18054 "});\n"); 18055 verifyFormat("function([this, that] {\n" 18056 " //\n" 18057 "});\n"); 18058 // FIXME: this format is not ideal and we should consider forcing the first 18059 // arg onto its own line. 18060 verifyFormat("function(a, b, c, //\n" 18061 " d, [this, that] {\n" 18062 " //\n" 18063 " });\n"); 18064 18065 // Multiple lambdas are treated correctly even when there is a short arg0. 18066 verifyFormat("SomeFunction(\n" 18067 " 1,\n" 18068 " [this] {\n" 18069 " //\n" 18070 " },\n" 18071 " [this] {\n" 18072 " //\n" 18073 " },\n" 18074 " 1);\n"); 18075 18076 // More complex introducers. 18077 verifyFormat("return [i, args...] {};"); 18078 18079 // Not lambdas. 18080 verifyFormat("constexpr char hello[]{\"hello\"};"); 18081 verifyFormat("double &operator[](int i) { return 0; }\n" 18082 "int i;"); 18083 verifyFormat("std::unique_ptr<int[]> foo() {}"); 18084 verifyFormat("int i = a[a][a]->f();"); 18085 verifyFormat("int i = (*b)[a]->f();"); 18086 18087 // Other corner cases. 18088 verifyFormat("void f() {\n" 18089 " bar([]() {} // Did not respect SpacesBeforeTrailingComments\n" 18090 " );\n" 18091 "}"); 18092 18093 // Lambdas created through weird macros. 18094 verifyFormat("void f() {\n" 18095 " MACRO((const AA &a) { return 1; });\n" 18096 " MACRO((AA &a) { return 1; });\n" 18097 "}"); 18098 18099 verifyFormat("if (blah_blah(whatever, whatever, [] {\n" 18100 " doo_dah();\n" 18101 " doo_dah();\n" 18102 " })) {\n" 18103 "}"); 18104 verifyFormat("if constexpr (blah_blah(whatever, whatever, [] {\n" 18105 " doo_dah();\n" 18106 " doo_dah();\n" 18107 " })) {\n" 18108 "}"); 18109 verifyFormat("if CONSTEXPR (blah_blah(whatever, whatever, [] {\n" 18110 " doo_dah();\n" 18111 " doo_dah();\n" 18112 " })) {\n" 18113 "}"); 18114 verifyFormat("auto lambda = []() {\n" 18115 " int a = 2\n" 18116 "#if A\n" 18117 " + 2\n" 18118 "#endif\n" 18119 " ;\n" 18120 "};"); 18121 18122 // Lambdas with complex multiline introducers. 18123 verifyFormat( 18124 "aaaaaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 18125 " [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]()\n" 18126 " -> ::std::unordered_set<\n" 18127 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa> {\n" 18128 " //\n" 18129 " });"); 18130 18131 FormatStyle DoNotMerge = getLLVMStyle(); 18132 DoNotMerge.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None; 18133 verifyFormat("auto c = []() {\n" 18134 " return b;\n" 18135 "};", 18136 "auto c = []() { return b; };", DoNotMerge); 18137 verifyFormat("auto c = []() {\n" 18138 "};", 18139 " auto c = []() {};", DoNotMerge); 18140 18141 FormatStyle MergeEmptyOnly = getLLVMStyle(); 18142 MergeEmptyOnly.AllowShortLambdasOnASingleLine = FormatStyle::SLS_Empty; 18143 verifyFormat("auto c = []() {\n" 18144 " return b;\n" 18145 "};", 18146 "auto c = []() {\n" 18147 " return b;\n" 18148 " };", 18149 MergeEmptyOnly); 18150 verifyFormat("auto c = []() {};", 18151 "auto c = []() {\n" 18152 "};", 18153 MergeEmptyOnly); 18154 18155 FormatStyle MergeInline = getLLVMStyle(); 18156 MergeInline.AllowShortLambdasOnASingleLine = FormatStyle::SLS_Inline; 18157 verifyFormat("auto c = []() {\n" 18158 " return b;\n" 18159 "};", 18160 "auto c = []() { return b; };", MergeInline); 18161 verifyFormat("function([]() { return b; })", "function([]() { return b; })", 18162 MergeInline); 18163 verifyFormat("function([]() { return b; }, a)", 18164 "function([]() { return b; }, a)", MergeInline); 18165 verifyFormat("function(a, []() { return b; })", 18166 "function(a, []() { return b; })", MergeInline); 18167 18168 // Check option "BraceWrapping.BeforeLambdaBody" and different state of 18169 // AllowShortLambdasOnASingleLine 18170 FormatStyle LLVMWithBeforeLambdaBody = getLLVMStyle(); 18171 LLVMWithBeforeLambdaBody.BreakBeforeBraces = FormatStyle::BS_Custom; 18172 LLVMWithBeforeLambdaBody.BraceWrapping.BeforeLambdaBody = true; 18173 LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine = 18174 FormatStyle::ShortLambdaStyle::SLS_None; 18175 verifyFormat("FctWithOneNestedLambdaInline_SLS_None(\n" 18176 " []()\n" 18177 " {\n" 18178 " return 17;\n" 18179 " });", 18180 LLVMWithBeforeLambdaBody); 18181 verifyFormat("FctWithOneNestedLambdaEmpty_SLS_None(\n" 18182 " []()\n" 18183 " {\n" 18184 " });", 18185 LLVMWithBeforeLambdaBody); 18186 verifyFormat("auto fct_SLS_None = []()\n" 18187 "{\n" 18188 " return 17;\n" 18189 "};", 18190 LLVMWithBeforeLambdaBody); 18191 verifyFormat("TwoNestedLambdas_SLS_None(\n" 18192 " []()\n" 18193 " {\n" 18194 " return Call(\n" 18195 " []()\n" 18196 " {\n" 18197 " return 17;\n" 18198 " });\n" 18199 " });", 18200 LLVMWithBeforeLambdaBody); 18201 verifyFormat("void Fct()\n" 18202 "{\n" 18203 " return {[]()\n" 18204 " {\n" 18205 " return 17;\n" 18206 " }};\n" 18207 "}", 18208 LLVMWithBeforeLambdaBody); 18209 18210 LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine = 18211 FormatStyle::ShortLambdaStyle::SLS_Empty; 18212 verifyFormat("FctWithOneNestedLambdaInline_SLS_Empty(\n" 18213 " []()\n" 18214 " {\n" 18215 " return 17;\n" 18216 " });", 18217 LLVMWithBeforeLambdaBody); 18218 verifyFormat("FctWithOneNestedLambdaEmpty_SLS_Empty([]() {});", 18219 LLVMWithBeforeLambdaBody); 18220 verifyFormat("FctWithOneNestedLambdaEmptyInsideAVeryVeryVeryVeryVeryVeryVeryL" 18221 "ongFunctionName_SLS_Empty(\n" 18222 " []() {});", 18223 LLVMWithBeforeLambdaBody); 18224 verifyFormat("FctWithMultipleParams_SLS_Empty(A, B,\n" 18225 " []()\n" 18226 " {\n" 18227 " return 17;\n" 18228 " });", 18229 LLVMWithBeforeLambdaBody); 18230 verifyFormat("auto fct_SLS_Empty = []()\n" 18231 "{\n" 18232 " return 17;\n" 18233 "};", 18234 LLVMWithBeforeLambdaBody); 18235 verifyFormat("TwoNestedLambdas_SLS_Empty(\n" 18236 " []()\n" 18237 " {\n" 18238 " return Call([]() {});\n" 18239 " });", 18240 LLVMWithBeforeLambdaBody); 18241 verifyFormat("TwoNestedLambdas_SLS_Empty(A,\n" 18242 " []()\n" 18243 " {\n" 18244 " return Call([]() {});\n" 18245 " });", 18246 LLVMWithBeforeLambdaBody); 18247 verifyFormat( 18248 "FctWithLongLineInLambda_SLS_Empty(\n" 18249 " []()\n" 18250 " {\n" 18251 " return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n" 18252 " AndShouldNotBeConsiderAsInline,\n" 18253 " LambdaBodyMustBeBreak);\n" 18254 " });", 18255 LLVMWithBeforeLambdaBody); 18256 18257 LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine = 18258 FormatStyle::ShortLambdaStyle::SLS_Inline; 18259 verifyFormat("FctWithOneNestedLambdaInline_SLS_Inline([]() { return 17; });", 18260 LLVMWithBeforeLambdaBody); 18261 verifyFormat("FctWithOneNestedLambdaEmpty_SLS_Inline([]() {});", 18262 LLVMWithBeforeLambdaBody); 18263 verifyFormat("auto fct_SLS_Inline = []()\n" 18264 "{\n" 18265 " return 17;\n" 18266 "};", 18267 LLVMWithBeforeLambdaBody); 18268 verifyFormat("TwoNestedLambdas_SLS_Inline([]() { return Call([]() { return " 18269 "17; }); });", 18270 LLVMWithBeforeLambdaBody); 18271 verifyFormat( 18272 "FctWithLongLineInLambda_SLS_Inline(\n" 18273 " []()\n" 18274 " {\n" 18275 " return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n" 18276 " AndShouldNotBeConsiderAsInline,\n" 18277 " LambdaBodyMustBeBreak);\n" 18278 " });", 18279 LLVMWithBeforeLambdaBody); 18280 verifyFormat("FctWithMultipleParams_SLS_Inline(" 18281 "VeryLongParameterThatShouldAskToBeOnMultiLine,\n" 18282 " []() { return 17; });", 18283 LLVMWithBeforeLambdaBody); 18284 verifyFormat( 18285 "FctWithMultipleParams_SLS_Inline(FirstParam, []() { return 17; });", 18286 LLVMWithBeforeLambdaBody); 18287 18288 LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine = 18289 FormatStyle::ShortLambdaStyle::SLS_All; 18290 verifyFormat("FctWithOneNestedLambdaInline_SLS_All([]() { return 17; });", 18291 LLVMWithBeforeLambdaBody); 18292 verifyFormat("FctWithOneNestedLambdaEmpty_SLS_All([]() {});", 18293 LLVMWithBeforeLambdaBody); 18294 verifyFormat("auto fct_SLS_All = []() { return 17; };", 18295 LLVMWithBeforeLambdaBody); 18296 verifyFormat("FctWithOneParam_SLS_All(\n" 18297 " []()\n" 18298 " {\n" 18299 " // A cool function...\n" 18300 " return 43;\n" 18301 " });", 18302 LLVMWithBeforeLambdaBody); 18303 verifyFormat("FctWithMultipleParams_SLS_All(" 18304 "VeryLongParameterThatShouldAskToBeOnMultiLine,\n" 18305 " []() { return 17; });", 18306 LLVMWithBeforeLambdaBody); 18307 verifyFormat("FctWithMultipleParams_SLS_All(A, []() { return 17; });", 18308 LLVMWithBeforeLambdaBody); 18309 verifyFormat("FctWithMultipleParams_SLS_All(A, B, []() { return 17; });", 18310 LLVMWithBeforeLambdaBody); 18311 verifyFormat( 18312 "FctWithLongLineInLambda_SLS_All(\n" 18313 " []()\n" 18314 " {\n" 18315 " return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n" 18316 " AndShouldNotBeConsiderAsInline,\n" 18317 " LambdaBodyMustBeBreak);\n" 18318 " });", 18319 LLVMWithBeforeLambdaBody); 18320 verifyFormat( 18321 "auto fct_SLS_All = []()\n" 18322 "{\n" 18323 " return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n" 18324 " AndShouldNotBeConsiderAsInline,\n" 18325 " LambdaBodyMustBeBreak);\n" 18326 "};", 18327 LLVMWithBeforeLambdaBody); 18328 LLVMWithBeforeLambdaBody.BinPackParameters = false; 18329 verifyFormat("FctAllOnSameLine_SLS_All([]() { return S; }, Fst, Second);", 18330 LLVMWithBeforeLambdaBody); 18331 verifyFormat( 18332 "FctWithLongLineInLambda_SLS_All([]() { return SomeValueNotSoLong; },\n" 18333 " FirstParam,\n" 18334 " SecondParam,\n" 18335 " ThirdParam,\n" 18336 " FourthParam);", 18337 LLVMWithBeforeLambdaBody); 18338 verifyFormat("FctWithLongLineInLambda_SLS_All(\n" 18339 " []() { return " 18340 "SomeValueVeryVeryVeryVeryVeryVeryVeryVeryVeryLong; },\n" 18341 " FirstParam,\n" 18342 " SecondParam,\n" 18343 " ThirdParam,\n" 18344 " FourthParam);", 18345 LLVMWithBeforeLambdaBody); 18346 verifyFormat( 18347 "FctWithLongLineInLambda_SLS_All(FirstParam,\n" 18348 " SecondParam,\n" 18349 " ThirdParam,\n" 18350 " FourthParam,\n" 18351 " []() { return SomeValueNotSoLong; });", 18352 LLVMWithBeforeLambdaBody); 18353 verifyFormat("FctWithLongLineInLambda_SLS_All(\n" 18354 " []()\n" 18355 " {\n" 18356 " return " 18357 "HereAVeryLongLineThatWillBeFormattedOnMultipleLineAndShouldNotB" 18358 "eConsiderAsInline;\n" 18359 " });", 18360 LLVMWithBeforeLambdaBody); 18361 verifyFormat( 18362 "FctWithLongLineInLambda_SLS_All(\n" 18363 " []()\n" 18364 " {\n" 18365 " return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n" 18366 " AndShouldNotBeConsiderAsInline,\n" 18367 " LambdaBodyMustBeBreak);\n" 18368 " });", 18369 LLVMWithBeforeLambdaBody); 18370 verifyFormat("FctWithTwoParams_SLS_All(\n" 18371 " []()\n" 18372 " {\n" 18373 " // A cool function...\n" 18374 " return 43;\n" 18375 " },\n" 18376 " 87);", 18377 LLVMWithBeforeLambdaBody); 18378 verifyFormat("FctWithTwoParams_SLS_All([]() { return 43; }, 87);", 18379 LLVMWithBeforeLambdaBody); 18380 verifyFormat("FctWithOneNestedLambdas_SLS_All([]() { return 17; });", 18381 LLVMWithBeforeLambdaBody); 18382 verifyFormat( 18383 "TwoNestedLambdas_SLS_All([]() { return Call([]() { return 17; }); });", 18384 LLVMWithBeforeLambdaBody); 18385 verifyFormat("TwoNestedLambdas_SLS_All([]() { return Call([]() { return 17; " 18386 "}); }, x);", 18387 LLVMWithBeforeLambdaBody); 18388 verifyFormat("TwoNestedLambdas_SLS_All(\n" 18389 " []()\n" 18390 " {\n" 18391 " // A cool function...\n" 18392 " return Call([]() { return 17; });\n" 18393 " });", 18394 LLVMWithBeforeLambdaBody); 18395 verifyFormat("TwoNestedLambdas_SLS_All(\n" 18396 " []()\n" 18397 " {\n" 18398 " return Call(\n" 18399 " []()\n" 18400 " {\n" 18401 " // A cool function...\n" 18402 " return 17;\n" 18403 " });\n" 18404 " });", 18405 LLVMWithBeforeLambdaBody); 18406 } 18407 18408 TEST_F(FormatTest, LambdaWithLineComments) { 18409 FormatStyle LLVMWithBeforeLambdaBody = getLLVMStyle(); 18410 LLVMWithBeforeLambdaBody.BreakBeforeBraces = FormatStyle::BS_Custom; 18411 LLVMWithBeforeLambdaBody.BraceWrapping.BeforeLambdaBody = true; 18412 LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine = 18413 FormatStyle::ShortLambdaStyle::SLS_All; 18414 18415 verifyFormat("auto k = []() { return; }", LLVMWithBeforeLambdaBody); 18416 verifyFormat("auto k = []() // comment\n" 18417 "{ return; }", 18418 LLVMWithBeforeLambdaBody); 18419 verifyFormat("auto k = []() /* comment */ { return; }", 18420 LLVMWithBeforeLambdaBody); 18421 verifyFormat("auto k = []() /* comment */ /* comment */ { return; }", 18422 LLVMWithBeforeLambdaBody); 18423 verifyFormat("auto k = []() // X\n" 18424 "{ return; }", 18425 LLVMWithBeforeLambdaBody); 18426 verifyFormat( 18427 "auto k = []() // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n" 18428 "{ return; }", 18429 LLVMWithBeforeLambdaBody); 18430 } 18431 18432 TEST_F(FormatTest, EmptyLinesInLambdas) { 18433 verifyFormat("auto lambda = []() {\n" 18434 " x(); //\n" 18435 "};", 18436 "auto lambda = []() {\n" 18437 "\n" 18438 " x(); //\n" 18439 "\n" 18440 "};"); 18441 } 18442 18443 TEST_F(FormatTest, FormatsBlocks) { 18444 FormatStyle ShortBlocks = getLLVMStyle(); 18445 ShortBlocks.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always; 18446 verifyFormat("int (^Block)(int, int);", ShortBlocks); 18447 verifyFormat("int (^Block1)(int, int) = ^(int i, int j)", ShortBlocks); 18448 verifyFormat("void (^block)(int) = ^(id test) { int i; };", ShortBlocks); 18449 verifyFormat("void (^block)(int) = ^(int test) { int i; };", ShortBlocks); 18450 verifyFormat("void (^block)(int) = ^id(int test) { int i; };", ShortBlocks); 18451 verifyFormat("void (^block)(int) = ^int(int test) { int i; };", ShortBlocks); 18452 18453 verifyFormat("foo(^{ bar(); });", ShortBlocks); 18454 verifyFormat("foo(a, ^{ bar(); });", ShortBlocks); 18455 verifyFormat("{ void (^block)(Object *x); }", ShortBlocks); 18456 18457 verifyFormat("[operation setCompletionBlock:^{\n" 18458 " [self onOperationDone];\n" 18459 "}];"); 18460 verifyFormat("int i = {[operation setCompletionBlock:^{\n" 18461 " [self onOperationDone];\n" 18462 "}]};"); 18463 verifyFormat("[operation setCompletionBlock:^(int *i) {\n" 18464 " f();\n" 18465 "}];"); 18466 verifyFormat("int a = [operation block:^int(int *i) {\n" 18467 " return 1;\n" 18468 "}];"); 18469 verifyFormat("[myObject doSomethingWith:arg1\n" 18470 " aaa:^int(int *a) {\n" 18471 " return 1;\n" 18472 " }\n" 18473 " bbb:f(a * bbbbbbbb)];"); 18474 18475 verifyFormat("[operation setCompletionBlock:^{\n" 18476 " [self.delegate newDataAvailable];\n" 18477 "}];", 18478 getLLVMStyleWithColumns(60)); 18479 verifyFormat("dispatch_async(_fileIOQueue, ^{\n" 18480 " NSString *path = [self sessionFilePath];\n" 18481 " if (path) {\n" 18482 " // ...\n" 18483 " }\n" 18484 "});"); 18485 verifyFormat("[[SessionService sharedService]\n" 18486 " loadWindowWithCompletionBlock:^(SessionWindow *window) {\n" 18487 " if (window) {\n" 18488 " [self windowDidLoad:window];\n" 18489 " } else {\n" 18490 " [self errorLoadingWindow];\n" 18491 " }\n" 18492 " }];"); 18493 verifyFormat("void (^largeBlock)(void) = ^{\n" 18494 " // ...\n" 18495 "};\n", 18496 getLLVMStyleWithColumns(40)); 18497 verifyFormat("[[SessionService sharedService]\n" 18498 " loadWindowWithCompletionBlock: //\n" 18499 " ^(SessionWindow *window) {\n" 18500 " if (window) {\n" 18501 " [self windowDidLoad:window];\n" 18502 " } else {\n" 18503 " [self errorLoadingWindow];\n" 18504 " }\n" 18505 " }];", 18506 getLLVMStyleWithColumns(60)); 18507 verifyFormat("[myObject doSomethingWith:arg1\n" 18508 " firstBlock:^(Foo *a) {\n" 18509 " // ...\n" 18510 " int i;\n" 18511 " }\n" 18512 " secondBlock:^(Bar *b) {\n" 18513 " // ...\n" 18514 " int i;\n" 18515 " }\n" 18516 " thirdBlock:^Foo(Bar *b) {\n" 18517 " // ...\n" 18518 " int i;\n" 18519 " }];"); 18520 verifyFormat("[myObject doSomethingWith:arg1\n" 18521 " firstBlock:-1\n" 18522 " secondBlock:^(Bar *b) {\n" 18523 " // ...\n" 18524 " int i;\n" 18525 " }];"); 18526 18527 verifyFormat("f(^{\n" 18528 " @autoreleasepool {\n" 18529 " if (a) {\n" 18530 " g();\n" 18531 " }\n" 18532 " }\n" 18533 "});"); 18534 verifyFormat("Block b = ^int *(A *a, B *b) {}"); 18535 verifyFormat("BOOL (^aaa)(void) = ^BOOL {\n" 18536 "};"); 18537 18538 FormatStyle FourIndent = getLLVMStyle(); 18539 FourIndent.ObjCBlockIndentWidth = 4; 18540 verifyFormat("[operation setCompletionBlock:^{\n" 18541 " [self onOperationDone];\n" 18542 "}];", 18543 FourIndent); 18544 } 18545 18546 TEST_F(FormatTest, FormatsBlocksWithZeroColumnWidth) { 18547 FormatStyle ZeroColumn = getLLVMStyle(); 18548 ZeroColumn.ColumnLimit = 0; 18549 18550 verifyFormat("[[SessionService sharedService] " 18551 "loadWindowWithCompletionBlock:^(SessionWindow *window) {\n" 18552 " if (window) {\n" 18553 " [self windowDidLoad:window];\n" 18554 " } else {\n" 18555 " [self errorLoadingWindow];\n" 18556 " }\n" 18557 "}];", 18558 ZeroColumn); 18559 EXPECT_EQ("[[SessionService sharedService]\n" 18560 " loadWindowWithCompletionBlock:^(SessionWindow *window) {\n" 18561 " if (window) {\n" 18562 " [self windowDidLoad:window];\n" 18563 " } else {\n" 18564 " [self errorLoadingWindow];\n" 18565 " }\n" 18566 " }];", 18567 format("[[SessionService sharedService]\n" 18568 "loadWindowWithCompletionBlock:^(SessionWindow *window) {\n" 18569 " if (window) {\n" 18570 " [self windowDidLoad:window];\n" 18571 " } else {\n" 18572 " [self errorLoadingWindow];\n" 18573 " }\n" 18574 "}];", 18575 ZeroColumn)); 18576 verifyFormat("[myObject doSomethingWith:arg1\n" 18577 " firstBlock:^(Foo *a) {\n" 18578 " // ...\n" 18579 " int i;\n" 18580 " }\n" 18581 " secondBlock:^(Bar *b) {\n" 18582 " // ...\n" 18583 " int i;\n" 18584 " }\n" 18585 " thirdBlock:^Foo(Bar *b) {\n" 18586 " // ...\n" 18587 " int i;\n" 18588 " }];", 18589 ZeroColumn); 18590 verifyFormat("f(^{\n" 18591 " @autoreleasepool {\n" 18592 " if (a) {\n" 18593 " g();\n" 18594 " }\n" 18595 " }\n" 18596 "});", 18597 ZeroColumn); 18598 verifyFormat("void (^largeBlock)(void) = ^{\n" 18599 " // ...\n" 18600 "};", 18601 ZeroColumn); 18602 18603 ZeroColumn.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always; 18604 EXPECT_EQ("void (^largeBlock)(void) = ^{ int i; };", 18605 format("void (^largeBlock)(void) = ^{ int i; };", ZeroColumn)); 18606 ZeroColumn.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Never; 18607 EXPECT_EQ("void (^largeBlock)(void) = ^{\n" 18608 " int i;\n" 18609 "};", 18610 format("void (^largeBlock)(void) = ^{ int i; };", ZeroColumn)); 18611 } 18612 18613 TEST_F(FormatTest, SupportsCRLF) { 18614 EXPECT_EQ("int a;\r\n" 18615 "int b;\r\n" 18616 "int c;\r\n", 18617 format("int a;\r\n" 18618 " int b;\r\n" 18619 " int c;\r\n", 18620 getLLVMStyle())); 18621 EXPECT_EQ("int a;\r\n" 18622 "int b;\r\n" 18623 "int c;\r\n", 18624 format("int a;\r\n" 18625 " int b;\n" 18626 " int c;\r\n", 18627 getLLVMStyle())); 18628 EXPECT_EQ("int a;\n" 18629 "int b;\n" 18630 "int c;\n", 18631 format("int a;\r\n" 18632 " int b;\n" 18633 " int c;\n", 18634 getLLVMStyle())); 18635 EXPECT_EQ("\"aaaaaaa \"\r\n" 18636 "\"bbbbbbb\";\r\n", 18637 format("\"aaaaaaa bbbbbbb\";\r\n", getLLVMStyleWithColumns(10))); 18638 EXPECT_EQ("#define A \\\r\n" 18639 " b; \\\r\n" 18640 " c; \\\r\n" 18641 " d;\r\n", 18642 format("#define A \\\r\n" 18643 " b; \\\r\n" 18644 " c; d; \r\n", 18645 getGoogleStyle())); 18646 18647 EXPECT_EQ("/*\r\n" 18648 "multi line block comments\r\n" 18649 "should not introduce\r\n" 18650 "an extra carriage return\r\n" 18651 "*/\r\n", 18652 format("/*\r\n" 18653 "multi line block comments\r\n" 18654 "should not introduce\r\n" 18655 "an extra carriage return\r\n" 18656 "*/\r\n")); 18657 EXPECT_EQ("/*\r\n" 18658 "\r\n" 18659 "*/", 18660 format("/*\r\n" 18661 " \r\r\r\n" 18662 "*/")); 18663 18664 FormatStyle style = getLLVMStyle(); 18665 18666 style.DeriveLineEnding = true; 18667 style.UseCRLF = false; 18668 EXPECT_EQ("union FooBarBazQux {\n" 18669 " int foo;\n" 18670 " int bar;\n" 18671 " int baz;\n" 18672 "};", 18673 format("union FooBarBazQux {\r\n" 18674 " int foo;\n" 18675 " int bar;\r\n" 18676 " int baz;\n" 18677 "};", 18678 style)); 18679 style.UseCRLF = true; 18680 EXPECT_EQ("union FooBarBazQux {\r\n" 18681 " int foo;\r\n" 18682 " int bar;\r\n" 18683 " int baz;\r\n" 18684 "};", 18685 format("union FooBarBazQux {\r\n" 18686 " int foo;\n" 18687 " int bar;\r\n" 18688 " int baz;\n" 18689 "};", 18690 style)); 18691 18692 style.DeriveLineEnding = false; 18693 style.UseCRLF = false; 18694 EXPECT_EQ("union FooBarBazQux {\n" 18695 " int foo;\n" 18696 " int bar;\n" 18697 " int baz;\n" 18698 " int qux;\n" 18699 "};", 18700 format("union FooBarBazQux {\r\n" 18701 " int foo;\n" 18702 " int bar;\r\n" 18703 " int baz;\n" 18704 " int qux;\r\n" 18705 "};", 18706 style)); 18707 style.UseCRLF = true; 18708 EXPECT_EQ("union FooBarBazQux {\r\n" 18709 " int foo;\r\n" 18710 " int bar;\r\n" 18711 " int baz;\r\n" 18712 " int qux;\r\n" 18713 "};", 18714 format("union FooBarBazQux {\r\n" 18715 " int foo;\n" 18716 " int bar;\r\n" 18717 " int baz;\n" 18718 " int qux;\n" 18719 "};", 18720 style)); 18721 18722 style.DeriveLineEnding = true; 18723 style.UseCRLF = false; 18724 EXPECT_EQ("union FooBarBazQux {\r\n" 18725 " int foo;\r\n" 18726 " int bar;\r\n" 18727 " int baz;\r\n" 18728 " int qux;\r\n" 18729 "};", 18730 format("union FooBarBazQux {\r\n" 18731 " int foo;\n" 18732 " int bar;\r\n" 18733 " int baz;\n" 18734 " int qux;\r\n" 18735 "};", 18736 style)); 18737 style.UseCRLF = true; 18738 EXPECT_EQ("union FooBarBazQux {\n" 18739 " int foo;\n" 18740 " int bar;\n" 18741 " int baz;\n" 18742 " int qux;\n" 18743 "};", 18744 format("union FooBarBazQux {\r\n" 18745 " int foo;\n" 18746 " int bar;\r\n" 18747 " int baz;\n" 18748 " int qux;\n" 18749 "};", 18750 style)); 18751 } 18752 18753 TEST_F(FormatTest, MunchSemicolonAfterBlocks) { 18754 verifyFormat("MY_CLASS(C) {\n" 18755 " int i;\n" 18756 " int j;\n" 18757 "};"); 18758 } 18759 18760 TEST_F(FormatTest, ConfigurableContinuationIndentWidth) { 18761 FormatStyle TwoIndent = getLLVMStyleWithColumns(15); 18762 TwoIndent.ContinuationIndentWidth = 2; 18763 18764 EXPECT_EQ("int i =\n" 18765 " longFunction(\n" 18766 " arg);", 18767 format("int i = longFunction(arg);", TwoIndent)); 18768 18769 FormatStyle SixIndent = getLLVMStyleWithColumns(20); 18770 SixIndent.ContinuationIndentWidth = 6; 18771 18772 EXPECT_EQ("int i =\n" 18773 " longFunction(\n" 18774 " arg);", 18775 format("int i = longFunction(arg);", SixIndent)); 18776 } 18777 18778 TEST_F(FormatTest, WrappedClosingParenthesisIndent) { 18779 FormatStyle Style = getLLVMStyle(); 18780 verifyFormat("int Foo::getter(\n" 18781 " //\n" 18782 ") const {\n" 18783 " return foo;\n" 18784 "}", 18785 Style); 18786 verifyFormat("void Foo::setter(\n" 18787 " //\n" 18788 ") {\n" 18789 " foo = 1;\n" 18790 "}", 18791 Style); 18792 } 18793 18794 TEST_F(FormatTest, SpacesInAngles) { 18795 FormatStyle Spaces = getLLVMStyle(); 18796 Spaces.SpacesInAngles = FormatStyle::SIAS_Always; 18797 18798 verifyFormat("vector< ::std::string > x1;", Spaces); 18799 verifyFormat("Foo< int, Bar > x2;", Spaces); 18800 verifyFormat("Foo< ::int, ::Bar > x3;", Spaces); 18801 18802 verifyFormat("static_cast< int >(arg);", Spaces); 18803 verifyFormat("template < typename T0, typename T1 > void f() {}", Spaces); 18804 verifyFormat("f< int, float >();", Spaces); 18805 verifyFormat("template <> g() {}", Spaces); 18806 verifyFormat("template < std::vector< int > > f() {}", Spaces); 18807 verifyFormat("std::function< void(int, int) > fct;", Spaces); 18808 verifyFormat("void inFunction() { std::function< void(int, int) > fct; }", 18809 Spaces); 18810 18811 Spaces.Standard = FormatStyle::LS_Cpp03; 18812 Spaces.SpacesInAngles = FormatStyle::SIAS_Always; 18813 verifyFormat("A< A< int > >();", Spaces); 18814 18815 Spaces.SpacesInAngles = FormatStyle::SIAS_Never; 18816 verifyFormat("A<A<int> >();", Spaces); 18817 18818 Spaces.SpacesInAngles = FormatStyle::SIAS_Leave; 18819 verifyFormat("vector< ::std::string> x4;", "vector<::std::string> x4;", 18820 Spaces); 18821 verifyFormat("vector< ::std::string > x4;", "vector<::std::string > x4;", 18822 Spaces); 18823 18824 verifyFormat("A<A<int> >();", Spaces); 18825 verifyFormat("A<A<int> >();", "A<A<int>>();", Spaces); 18826 verifyFormat("A< A< int > >();", Spaces); 18827 18828 Spaces.Standard = FormatStyle::LS_Cpp11; 18829 Spaces.SpacesInAngles = FormatStyle::SIAS_Always; 18830 verifyFormat("A< A< int > >();", Spaces); 18831 18832 Spaces.SpacesInAngles = FormatStyle::SIAS_Never; 18833 verifyFormat("vector<::std::string> x4;", Spaces); 18834 verifyFormat("vector<int> x5;", Spaces); 18835 verifyFormat("Foo<int, Bar> x6;", Spaces); 18836 verifyFormat("Foo<::int, ::Bar> x7;", Spaces); 18837 18838 verifyFormat("A<A<int>>();", Spaces); 18839 18840 Spaces.SpacesInAngles = FormatStyle::SIAS_Leave; 18841 verifyFormat("vector<::std::string> x4;", Spaces); 18842 verifyFormat("vector< ::std::string > x4;", Spaces); 18843 verifyFormat("vector<int> x5;", Spaces); 18844 verifyFormat("vector< int > x5;", Spaces); 18845 verifyFormat("Foo<int, Bar> x6;", Spaces); 18846 verifyFormat("Foo< int, Bar > x6;", Spaces); 18847 verifyFormat("Foo<::int, ::Bar> x7;", Spaces); 18848 verifyFormat("Foo< ::int, ::Bar > x7;", Spaces); 18849 18850 verifyFormat("A<A<int>>();", Spaces); 18851 verifyFormat("A< A< int > >();", Spaces); 18852 verifyFormat("A<A<int > >();", Spaces); 18853 verifyFormat("A< A< int>>();", Spaces); 18854 } 18855 18856 TEST_F(FormatTest, SpaceAfterTemplateKeyword) { 18857 FormatStyle Style = getLLVMStyle(); 18858 Style.SpaceAfterTemplateKeyword = false; 18859 verifyFormat("template<int> void foo();", Style); 18860 } 18861 18862 TEST_F(FormatTest, TripleAngleBrackets) { 18863 verifyFormat("f<<<1, 1>>>();"); 18864 verifyFormat("f<<<1, 1, 1, s>>>();"); 18865 verifyFormat("f<<<a, b, c, d>>>();"); 18866 EXPECT_EQ("f<<<1, 1>>>();", format("f <<< 1, 1 >>> ();")); 18867 verifyFormat("f<param><<<1, 1>>>();"); 18868 verifyFormat("f<1><<<1, 1>>>();"); 18869 EXPECT_EQ("f<param><<<1, 1>>>();", format("f< param > <<< 1, 1 >>> ();")); 18870 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" 18871 "aaaaaaaaaaa<<<\n 1, 1>>>();"); 18872 verifyFormat("aaaaaaaaaaaaaaa<aaaaaaaaa, aaaaaaaaaa, aaaaaaaaaaaaaa>\n" 18873 " <<<aaaaaaaaa, aaaaaaaaaa, aaaaaaaaaaaaaaaaaa>>>();"); 18874 } 18875 18876 TEST_F(FormatTest, MergeLessLessAtEnd) { 18877 verifyFormat("<<"); 18878 EXPECT_EQ("< < <", format("\\\n<<<")); 18879 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" 18880 "aaallvm::outs() <<"); 18881 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" 18882 "aaaallvm::outs()\n <<"); 18883 } 18884 18885 TEST_F(FormatTest, HandleUnbalancedImplicitBracesAcrossPPBranches) { 18886 std::string code = "#if A\n" 18887 "#if B\n" 18888 "a.\n" 18889 "#endif\n" 18890 " a = 1;\n" 18891 "#else\n" 18892 "#endif\n" 18893 "#if C\n" 18894 "#else\n" 18895 "#endif\n"; 18896 EXPECT_EQ(code, format(code)); 18897 } 18898 18899 TEST_F(FormatTest, HandleConflictMarkers) { 18900 // Git/SVN conflict markers. 18901 EXPECT_EQ("int a;\n" 18902 "void f() {\n" 18903 " callme(some(parameter1,\n" 18904 "<<<<<<< text by the vcs\n" 18905 " parameter2),\n" 18906 "||||||| text by the vcs\n" 18907 " parameter2),\n" 18908 " parameter3,\n" 18909 "======= text by the vcs\n" 18910 " parameter2, parameter3),\n" 18911 ">>>>>>> text by the vcs\n" 18912 " otherparameter);\n", 18913 format("int a;\n" 18914 "void f() {\n" 18915 " callme(some(parameter1,\n" 18916 "<<<<<<< text by the vcs\n" 18917 " parameter2),\n" 18918 "||||||| text by the vcs\n" 18919 " parameter2),\n" 18920 " parameter3,\n" 18921 "======= text by the vcs\n" 18922 " parameter2,\n" 18923 " parameter3),\n" 18924 ">>>>>>> text by the vcs\n" 18925 " otherparameter);\n")); 18926 18927 // Perforce markers. 18928 EXPECT_EQ("void f() {\n" 18929 " function(\n" 18930 ">>>> text by the vcs\n" 18931 " parameter,\n" 18932 "==== text by the vcs\n" 18933 " parameter,\n" 18934 "==== text by the vcs\n" 18935 " parameter,\n" 18936 "<<<< text by the vcs\n" 18937 " parameter);\n", 18938 format("void f() {\n" 18939 " function(\n" 18940 ">>>> text by the vcs\n" 18941 " parameter,\n" 18942 "==== text by the vcs\n" 18943 " parameter,\n" 18944 "==== text by the vcs\n" 18945 " parameter,\n" 18946 "<<<< text by the vcs\n" 18947 " parameter);\n")); 18948 18949 EXPECT_EQ("<<<<<<<\n" 18950 "|||||||\n" 18951 "=======\n" 18952 ">>>>>>>", 18953 format("<<<<<<<\n" 18954 "|||||||\n" 18955 "=======\n" 18956 ">>>>>>>")); 18957 18958 EXPECT_EQ("<<<<<<<\n" 18959 "|||||||\n" 18960 "int i;\n" 18961 "=======\n" 18962 ">>>>>>>", 18963 format("<<<<<<<\n" 18964 "|||||||\n" 18965 "int i;\n" 18966 "=======\n" 18967 ">>>>>>>")); 18968 18969 // FIXME: Handle parsing of macros around conflict markers correctly: 18970 EXPECT_EQ("#define Macro \\\n" 18971 "<<<<<<<\n" 18972 "Something \\\n" 18973 "|||||||\n" 18974 "Else \\\n" 18975 "=======\n" 18976 "Other \\\n" 18977 ">>>>>>>\n" 18978 " End int i;\n", 18979 format("#define Macro \\\n" 18980 "<<<<<<<\n" 18981 " Something \\\n" 18982 "|||||||\n" 18983 " Else \\\n" 18984 "=======\n" 18985 " Other \\\n" 18986 ">>>>>>>\n" 18987 " End\n" 18988 "int i;\n")); 18989 } 18990 18991 TEST_F(FormatTest, DisableRegions) { 18992 EXPECT_EQ("int i;\n" 18993 "// clang-format off\n" 18994 " int j;\n" 18995 "// clang-format on\n" 18996 "int k;", 18997 format(" int i;\n" 18998 " // clang-format off\n" 18999 " int j;\n" 19000 " // clang-format on\n" 19001 " int k;")); 19002 EXPECT_EQ("int i;\n" 19003 "/* clang-format off */\n" 19004 " int j;\n" 19005 "/* clang-format on */\n" 19006 "int k;", 19007 format(" int i;\n" 19008 " /* clang-format off */\n" 19009 " int j;\n" 19010 " /* clang-format on */\n" 19011 " int k;")); 19012 19013 // Don't reflow comments within disabled regions. 19014 EXPECT_EQ("// clang-format off\n" 19015 "// long long long long long long line\n" 19016 "/* clang-format on */\n" 19017 "/* long long long\n" 19018 " * long long long\n" 19019 " * line */\n" 19020 "int i;\n" 19021 "/* clang-format off */\n" 19022 "/* long long long long long long line */\n", 19023 format("// clang-format off\n" 19024 "// long long long long long long line\n" 19025 "/* clang-format on */\n" 19026 "/* long long long long long long line */\n" 19027 "int i;\n" 19028 "/* clang-format off */\n" 19029 "/* long long long long long long line */\n", 19030 getLLVMStyleWithColumns(20))); 19031 } 19032 19033 TEST_F(FormatTest, DoNotCrashOnInvalidInput) { 19034 format("? ) ="); 19035 verifyNoCrash("#define a\\\n /**/}"); 19036 } 19037 19038 TEST_F(FormatTest, FormatsTableGenCode) { 19039 FormatStyle Style = getLLVMStyle(); 19040 Style.Language = FormatStyle::LK_TableGen; 19041 verifyFormat("include \"a.td\"\ninclude \"b.td\"", Style); 19042 } 19043 19044 TEST_F(FormatTest, ArrayOfTemplates) { 19045 EXPECT_EQ("auto a = new unique_ptr<int>[10];", 19046 format("auto a = new unique_ptr<int > [ 10];")); 19047 19048 FormatStyle Spaces = getLLVMStyle(); 19049 Spaces.SpacesInSquareBrackets = true; 19050 EXPECT_EQ("auto a = new unique_ptr<int>[ 10 ];", 19051 format("auto a = new unique_ptr<int > [10];", Spaces)); 19052 } 19053 19054 TEST_F(FormatTest, ArrayAsTemplateType) { 19055 EXPECT_EQ("auto a = unique_ptr<Foo<Bar>[10]>;", 19056 format("auto a = unique_ptr < Foo < Bar>[ 10]> ;")); 19057 19058 FormatStyle Spaces = getLLVMStyle(); 19059 Spaces.SpacesInSquareBrackets = true; 19060 EXPECT_EQ("auto a = unique_ptr<Foo<Bar>[ 10 ]>;", 19061 format("auto a = unique_ptr < Foo < Bar>[10]> ;", Spaces)); 19062 } 19063 19064 TEST_F(FormatTest, NoSpaceAfterSuper) { verifyFormat("__super::FooBar();"); } 19065 19066 TEST(FormatStyle, GetStyleWithEmptyFileName) { 19067 llvm::vfs::InMemoryFileSystem FS; 19068 auto Style1 = getStyle("file", "", "Google", "", &FS); 19069 ASSERT_TRUE((bool)Style1); 19070 ASSERT_EQ(*Style1, getGoogleStyle()); 19071 } 19072 19073 TEST(FormatStyle, GetStyleOfFile) { 19074 llvm::vfs::InMemoryFileSystem FS; 19075 // Test 1: format file in the same directory. 19076 ASSERT_TRUE( 19077 FS.addFile("/a/.clang-format", 0, 19078 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: LLVM"))); 19079 ASSERT_TRUE( 19080 FS.addFile("/a/test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int i;"))); 19081 auto Style1 = getStyle("file", "/a/.clang-format", "Google", "", &FS); 19082 ASSERT_TRUE((bool)Style1); 19083 ASSERT_EQ(*Style1, getLLVMStyle()); 19084 19085 // Test 2.1: fallback to default. 19086 ASSERT_TRUE( 19087 FS.addFile("/b/test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int i;"))); 19088 auto Style2 = getStyle("file", "/b/test.cpp", "Mozilla", "", &FS); 19089 ASSERT_TRUE((bool)Style2); 19090 ASSERT_EQ(*Style2, getMozillaStyle()); 19091 19092 // Test 2.2: no format on 'none' fallback style. 19093 Style2 = getStyle("file", "/b/test.cpp", "none", "", &FS); 19094 ASSERT_TRUE((bool)Style2); 19095 ASSERT_EQ(*Style2, getNoStyle()); 19096 19097 // Test 2.3: format if config is found with no based style while fallback is 19098 // 'none'. 19099 ASSERT_TRUE(FS.addFile("/b/.clang-format", 0, 19100 llvm::MemoryBuffer::getMemBuffer("IndentWidth: 2"))); 19101 Style2 = getStyle("file", "/b/test.cpp", "none", "", &FS); 19102 ASSERT_TRUE((bool)Style2); 19103 ASSERT_EQ(*Style2, getLLVMStyle()); 19104 19105 // Test 2.4: format if yaml with no based style, while fallback is 'none'. 19106 Style2 = getStyle("{}", "a.h", "none", "", &FS); 19107 ASSERT_TRUE((bool)Style2); 19108 ASSERT_EQ(*Style2, getLLVMStyle()); 19109 19110 // Test 3: format file in parent directory. 19111 ASSERT_TRUE( 19112 FS.addFile("/c/.clang-format", 0, 19113 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google"))); 19114 ASSERT_TRUE(FS.addFile("/c/sub/sub/sub/test.cpp", 0, 19115 llvm::MemoryBuffer::getMemBuffer("int i;"))); 19116 auto Style3 = getStyle("file", "/c/sub/sub/sub/test.cpp", "LLVM", "", &FS); 19117 ASSERT_TRUE((bool)Style3); 19118 ASSERT_EQ(*Style3, getGoogleStyle()); 19119 19120 // Test 4: error on invalid fallback style 19121 auto Style4 = getStyle("file", "a.h", "KungFu", "", &FS); 19122 ASSERT_FALSE((bool)Style4); 19123 llvm::consumeError(Style4.takeError()); 19124 19125 // Test 5: error on invalid yaml on command line 19126 auto Style5 = getStyle("{invalid_key=invalid_value}", "a.h", "LLVM", "", &FS); 19127 ASSERT_FALSE((bool)Style5); 19128 llvm::consumeError(Style5.takeError()); 19129 19130 // Test 6: error on invalid style 19131 auto Style6 = getStyle("KungFu", "a.h", "LLVM", "", &FS); 19132 ASSERT_FALSE((bool)Style6); 19133 llvm::consumeError(Style6.takeError()); 19134 19135 // Test 7: found config file, error on parsing it 19136 ASSERT_TRUE( 19137 FS.addFile("/d/.clang-format", 0, 19138 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: LLVM\n" 19139 "InvalidKey: InvalidValue"))); 19140 ASSERT_TRUE( 19141 FS.addFile("/d/test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int i;"))); 19142 auto Style7a = getStyle("file", "/d/.clang-format", "LLVM", "", &FS); 19143 ASSERT_FALSE((bool)Style7a); 19144 llvm::consumeError(Style7a.takeError()); 19145 19146 auto Style7b = getStyle("file", "/d/.clang-format", "LLVM", "", &FS, true); 19147 ASSERT_TRUE((bool)Style7b); 19148 19149 // Test 8: inferred per-language defaults apply. 19150 auto StyleTd = getStyle("file", "x.td", "llvm", "", &FS); 19151 ASSERT_TRUE((bool)StyleTd); 19152 ASSERT_EQ(*StyleTd, getLLVMStyle(FormatStyle::LK_TableGen)); 19153 19154 // Test 9.1: overwriting a file style, when parent no file exists with no 19155 // fallback style 19156 ASSERT_TRUE(FS.addFile( 19157 "/e/sub/.clang-format", 0, 19158 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: InheritParentConfig\n" 19159 "ColumnLimit: 20"))); 19160 ASSERT_TRUE(FS.addFile("/e/sub/code.cpp", 0, 19161 llvm::MemoryBuffer::getMemBuffer("int i;"))); 19162 auto Style9 = getStyle("file", "/e/sub/code.cpp", "none", "", &FS); 19163 ASSERT_TRUE(static_cast<bool>(Style9)); 19164 ASSERT_EQ(*Style9, [] { 19165 auto Style = getNoStyle(); 19166 Style.ColumnLimit = 20; 19167 return Style; 19168 }()); 19169 19170 // Test 9.2: with LLVM fallback style 19171 Style9 = getStyle("file", "/e/sub/code.cpp", "LLVM", "", &FS); 19172 ASSERT_TRUE(static_cast<bool>(Style9)); 19173 ASSERT_EQ(*Style9, [] { 19174 auto Style = getLLVMStyle(); 19175 Style.ColumnLimit = 20; 19176 return Style; 19177 }()); 19178 19179 // Test 9.3: with a parent file 19180 ASSERT_TRUE( 19181 FS.addFile("/e/.clang-format", 0, 19182 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google\n" 19183 "UseTab: Always"))); 19184 Style9 = getStyle("file", "/e/sub/code.cpp", "none", "", &FS); 19185 ASSERT_TRUE(static_cast<bool>(Style9)); 19186 ASSERT_EQ(*Style9, [] { 19187 auto Style = getGoogleStyle(); 19188 Style.ColumnLimit = 20; 19189 Style.UseTab = FormatStyle::UT_Always; 19190 return Style; 19191 }()); 19192 19193 // Test 9.4: propagate more than one level 19194 ASSERT_TRUE(FS.addFile("/e/sub/sub/code.cpp", 0, 19195 llvm::MemoryBuffer::getMemBuffer("int i;"))); 19196 ASSERT_TRUE(FS.addFile("/e/sub/sub/.clang-format", 0, 19197 llvm::MemoryBuffer::getMemBuffer( 19198 "BasedOnStyle: InheritParentConfig\n" 19199 "WhitespaceSensitiveMacros: ['FOO', 'BAR']"))); 19200 std::vector<std::string> NonDefaultWhiteSpaceMacros{"FOO", "BAR"}; 19201 19202 const auto SubSubStyle = [&NonDefaultWhiteSpaceMacros] { 19203 auto Style = getGoogleStyle(); 19204 Style.ColumnLimit = 20; 19205 Style.UseTab = FormatStyle::UT_Always; 19206 Style.WhitespaceSensitiveMacros = NonDefaultWhiteSpaceMacros; 19207 return Style; 19208 }(); 19209 19210 ASSERT_NE(Style9->WhitespaceSensitiveMacros, NonDefaultWhiteSpaceMacros); 19211 Style9 = getStyle("file", "/e/sub/sub/code.cpp", "none", "", &FS); 19212 ASSERT_TRUE(static_cast<bool>(Style9)); 19213 ASSERT_EQ(*Style9, SubSubStyle); 19214 19215 // Test 9.5: use InheritParentConfig as style name 19216 Style9 = 19217 getStyle("inheritparentconfig", "/e/sub/sub/code.cpp", "none", "", &FS); 19218 ASSERT_TRUE(static_cast<bool>(Style9)); 19219 ASSERT_EQ(*Style9, SubSubStyle); 19220 19221 // Test 9.6: use command line style with inheritance 19222 Style9 = getStyle("{BasedOnStyle: InheritParentConfig}", "/e/sub/code.cpp", 19223 "none", "", &FS); 19224 ASSERT_TRUE(static_cast<bool>(Style9)); 19225 ASSERT_EQ(*Style9, SubSubStyle); 19226 19227 // Test 9.7: use command line style with inheritance and own config 19228 Style9 = getStyle("{BasedOnStyle: InheritParentConfig, " 19229 "WhitespaceSensitiveMacros: ['FOO', 'BAR']}", 19230 "/e/sub/code.cpp", "none", "", &FS); 19231 ASSERT_TRUE(static_cast<bool>(Style9)); 19232 ASSERT_EQ(*Style9, SubSubStyle); 19233 19234 // Test 9.8: use inheritance from a file without BasedOnStyle 19235 ASSERT_TRUE(FS.addFile("/e/withoutbase/.clang-format", 0, 19236 llvm::MemoryBuffer::getMemBuffer("ColumnLimit: 123"))); 19237 ASSERT_TRUE( 19238 FS.addFile("/e/withoutbase/sub/.clang-format", 0, 19239 llvm::MemoryBuffer::getMemBuffer( 19240 "BasedOnStyle: InheritParentConfig\nIndentWidth: 7"))); 19241 // Make sure we do not use the fallback style 19242 Style9 = getStyle("file", "/e/withoutbase/code.cpp", "google", "", &FS); 19243 ASSERT_TRUE(static_cast<bool>(Style9)); 19244 ASSERT_EQ(*Style9, [] { 19245 auto Style = getLLVMStyle(); 19246 Style.ColumnLimit = 123; 19247 return Style; 19248 }()); 19249 19250 Style9 = getStyle("file", "/e/withoutbase/sub/code.cpp", "google", "", &FS); 19251 ASSERT_TRUE(static_cast<bool>(Style9)); 19252 ASSERT_EQ(*Style9, [] { 19253 auto Style = getLLVMStyle(); 19254 Style.ColumnLimit = 123; 19255 Style.IndentWidth = 7; 19256 return Style; 19257 }()); 19258 } 19259 19260 TEST_F(ReplacementTest, FormatCodeAfterReplacements) { 19261 // Column limit is 20. 19262 std::string Code = "Type *a =\n" 19263 " new Type();\n" 19264 "g(iiiii, 0, jjjjj,\n" 19265 " 0, kkkkk, 0, mm);\n" 19266 "int bad = format ;"; 19267 std::string Expected = "auto a = new Type();\n" 19268 "g(iiiii, nullptr,\n" 19269 " jjjjj, nullptr,\n" 19270 " kkkkk, nullptr,\n" 19271 " mm);\n" 19272 "int bad = format ;"; 19273 FileID ID = Context.createInMemoryFile("format.cpp", Code); 19274 tooling::Replacements Replaces = toReplacements( 19275 {tooling::Replacement(Context.Sources, Context.getLocation(ID, 1, 1), 6, 19276 "auto "), 19277 tooling::Replacement(Context.Sources, Context.getLocation(ID, 3, 10), 1, 19278 "nullptr"), 19279 tooling::Replacement(Context.Sources, Context.getLocation(ID, 4, 3), 1, 19280 "nullptr"), 19281 tooling::Replacement(Context.Sources, Context.getLocation(ID, 4, 13), 1, 19282 "nullptr")}); 19283 19284 format::FormatStyle Style = format::getLLVMStyle(); 19285 Style.ColumnLimit = 20; // Set column limit to 20 to increase readibility. 19286 auto FormattedReplaces = formatReplacements(Code, Replaces, Style); 19287 EXPECT_TRUE(static_cast<bool>(FormattedReplaces)) 19288 << llvm::toString(FormattedReplaces.takeError()) << "\n"; 19289 auto Result = applyAllReplacements(Code, *FormattedReplaces); 19290 EXPECT_TRUE(static_cast<bool>(Result)); 19291 EXPECT_EQ(Expected, *Result); 19292 } 19293 19294 TEST_F(ReplacementTest, SortIncludesAfterReplacement) { 19295 std::string Code = "#include \"a.h\"\n" 19296 "#include \"c.h\"\n" 19297 "\n" 19298 "int main() {\n" 19299 " return 0;\n" 19300 "}"; 19301 std::string Expected = "#include \"a.h\"\n" 19302 "#include \"b.h\"\n" 19303 "#include \"c.h\"\n" 19304 "\n" 19305 "int main() {\n" 19306 " return 0;\n" 19307 "}"; 19308 FileID ID = Context.createInMemoryFile("fix.cpp", Code); 19309 tooling::Replacements Replaces = toReplacements( 19310 {tooling::Replacement(Context.Sources, Context.getLocation(ID, 1, 1), 0, 19311 "#include \"b.h\"\n")}); 19312 19313 format::FormatStyle Style = format::getLLVMStyle(); 19314 Style.SortIncludes = FormatStyle::SI_CaseSensitive; 19315 auto FormattedReplaces = formatReplacements(Code, Replaces, Style); 19316 EXPECT_TRUE(static_cast<bool>(FormattedReplaces)) 19317 << llvm::toString(FormattedReplaces.takeError()) << "\n"; 19318 auto Result = applyAllReplacements(Code, *FormattedReplaces); 19319 EXPECT_TRUE(static_cast<bool>(Result)); 19320 EXPECT_EQ(Expected, *Result); 19321 } 19322 19323 TEST_F(FormatTest, FormatSortsUsingDeclarations) { 19324 EXPECT_EQ("using std::cin;\n" 19325 "using std::cout;", 19326 format("using std::cout;\n" 19327 "using std::cin;", 19328 getGoogleStyle())); 19329 } 19330 19331 TEST_F(FormatTest, UTF8CharacterLiteralCpp03) { 19332 format::FormatStyle Style = format::getLLVMStyle(); 19333 Style.Standard = FormatStyle::LS_Cpp03; 19334 // cpp03 recognize this string as identifier u8 and literal character 'a' 19335 EXPECT_EQ("auto c = u8 'a';", format("auto c = u8'a';", Style)); 19336 } 19337 19338 TEST_F(FormatTest, UTF8CharacterLiteralCpp11) { 19339 // u8'a' is a C++17 feature, utf8 literal character, LS_Cpp11 covers 19340 // all modes, including C++11, C++14 and C++17 19341 EXPECT_EQ("auto c = u8'a';", format("auto c = u8'a';")); 19342 } 19343 19344 TEST_F(FormatTest, DoNotFormatLikelyXml) { 19345 EXPECT_EQ("<!-- ;> -->", format("<!-- ;> -->", getGoogleStyle())); 19346 EXPECT_EQ(" <!-- >; -->", format(" <!-- >; -->", getGoogleStyle())); 19347 } 19348 19349 TEST_F(FormatTest, StructuredBindings) { 19350 // Structured bindings is a C++17 feature. 19351 // all modes, including C++11, C++14 and C++17 19352 verifyFormat("auto [a, b] = f();"); 19353 EXPECT_EQ("auto [a, b] = f();", format("auto[a, b] = f();")); 19354 EXPECT_EQ("const auto [a, b] = f();", format("const auto[a, b] = f();")); 19355 EXPECT_EQ("auto const [a, b] = f();", format("auto const[a, b] = f();")); 19356 EXPECT_EQ("auto const volatile [a, b] = f();", 19357 format("auto const volatile[a, b] = f();")); 19358 EXPECT_EQ("auto [a, b, c] = f();", format("auto [ a , b,c ] = f();")); 19359 EXPECT_EQ("auto &[a, b, c] = f();", 19360 format("auto &[ a , b,c ] = f();")); 19361 EXPECT_EQ("auto &&[a, b, c] = f();", 19362 format("auto &&[ a , b,c ] = f();")); 19363 EXPECT_EQ("auto const &[a, b] = f();", format("auto const&[a, b] = f();")); 19364 EXPECT_EQ("auto const volatile &&[a, b] = f();", 19365 format("auto const volatile &&[a, b] = f();")); 19366 EXPECT_EQ("auto const &&[a, b] = f();", 19367 format("auto const && [a, b] = f();")); 19368 EXPECT_EQ("const auto &[a, b] = f();", 19369 format("const auto & [a, b] = f();")); 19370 EXPECT_EQ("const auto volatile &&[a, b] = f();", 19371 format("const auto volatile &&[a, b] = f();")); 19372 EXPECT_EQ("volatile const auto &&[a, b] = f();", 19373 format("volatile const auto &&[a, b] = f();")); 19374 EXPECT_EQ("const auto &&[a, b] = f();", 19375 format("const auto && [a, b] = f();")); 19376 19377 // Make sure we don't mistake structured bindings for lambdas. 19378 FormatStyle PointerMiddle = getLLVMStyle(); 19379 PointerMiddle.PointerAlignment = FormatStyle::PAS_Middle; 19380 verifyFormat("auto [a1, b]{A * i};", getGoogleStyle()); 19381 verifyFormat("auto [a2, b]{A * i};", getLLVMStyle()); 19382 verifyFormat("auto [a3, b]{A * i};", PointerMiddle); 19383 verifyFormat("auto const [a1, b]{A * i};", getGoogleStyle()); 19384 verifyFormat("auto const [a2, b]{A * i};", getLLVMStyle()); 19385 verifyFormat("auto const [a3, b]{A * i};", PointerMiddle); 19386 verifyFormat("auto const& [a1, b]{A * i};", getGoogleStyle()); 19387 verifyFormat("auto const &[a2, b]{A * i};", getLLVMStyle()); 19388 verifyFormat("auto const & [a3, b]{A * i};", PointerMiddle); 19389 verifyFormat("auto const&& [a1, b]{A * i};", getGoogleStyle()); 19390 verifyFormat("auto const &&[a2, b]{A * i};", getLLVMStyle()); 19391 verifyFormat("auto const && [a3, b]{A * i};", PointerMiddle); 19392 19393 EXPECT_EQ("for (const auto &&[a, b] : some_range) {\n}", 19394 format("for (const auto && [a, b] : some_range) {\n}")); 19395 EXPECT_EQ("for (const auto &[a, b] : some_range) {\n}", 19396 format("for (const auto & [a, b] : some_range) {\n}")); 19397 EXPECT_EQ("for (const auto [a, b] : some_range) {\n}", 19398 format("for (const auto[a, b] : some_range) {\n}")); 19399 EXPECT_EQ("auto [x, y](expr);", format("auto[x,y] (expr);")); 19400 EXPECT_EQ("auto &[x, y](expr);", format("auto & [x,y] (expr);")); 19401 EXPECT_EQ("auto &&[x, y](expr);", format("auto && [x,y] (expr);")); 19402 EXPECT_EQ("auto const &[x, y](expr);", 19403 format("auto const & [x,y] (expr);")); 19404 EXPECT_EQ("auto const &&[x, y](expr);", 19405 format("auto const && [x,y] (expr);")); 19406 EXPECT_EQ("auto [x, y]{expr};", format("auto[x,y] {expr};")); 19407 EXPECT_EQ("auto const &[x, y]{expr};", 19408 format("auto const & [x,y] {expr};")); 19409 EXPECT_EQ("auto const &&[x, y]{expr};", 19410 format("auto const && [x,y] {expr};")); 19411 19412 format::FormatStyle Spaces = format::getLLVMStyle(); 19413 Spaces.SpacesInSquareBrackets = true; 19414 verifyFormat("auto [ a, b ] = f();", Spaces); 19415 verifyFormat("auto &&[ a, b ] = f();", Spaces); 19416 verifyFormat("auto &[ a, b ] = f();", Spaces); 19417 verifyFormat("auto const &&[ a, b ] = f();", Spaces); 19418 verifyFormat("auto const &[ a, b ] = f();", Spaces); 19419 } 19420 19421 TEST_F(FormatTest, FileAndCode) { 19422 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.cc", "")); 19423 EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.m", "")); 19424 EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.mm", "")); 19425 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "")); 19426 EXPECT_EQ(FormatStyle::LK_ObjC, 19427 guessLanguage("foo.h", "@interface Foo\n@end\n")); 19428 EXPECT_EQ( 19429 FormatStyle::LK_ObjC, 19430 guessLanguage("foo.h", "#define TRY(x, y) @try { x; } @finally { y; }")); 19431 EXPECT_EQ(FormatStyle::LK_ObjC, 19432 guessLanguage("foo.h", "#define AVAIL(x) @available(x, *))")); 19433 EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.h", "@class Foo;")); 19434 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo", "")); 19435 EXPECT_EQ(FormatStyle::LK_ObjC, 19436 guessLanguage("foo", "@interface Foo\n@end\n")); 19437 EXPECT_EQ(FormatStyle::LK_ObjC, 19438 guessLanguage("foo.h", "int DoStuff(CGRect rect);\n")); 19439 EXPECT_EQ( 19440 FormatStyle::LK_ObjC, 19441 guessLanguage("foo.h", 19442 "#define MY_POINT_MAKE(x, y) CGPointMake((x), (y));\n")); 19443 EXPECT_EQ( 19444 FormatStyle::LK_Cpp, 19445 guessLanguage("foo.h", "#define FOO(...) auto bar = [] __VA_ARGS__;")); 19446 } 19447 19448 TEST_F(FormatTest, GuessLanguageWithCpp11AttributeSpecifiers) { 19449 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "[[noreturn]];")); 19450 EXPECT_EQ(FormatStyle::LK_ObjC, 19451 guessLanguage("foo.h", "array[[calculator getIndex]];")); 19452 EXPECT_EQ(FormatStyle::LK_Cpp, 19453 guessLanguage("foo.h", "[[noreturn, deprecated(\"so sorry\")]];")); 19454 EXPECT_EQ( 19455 FormatStyle::LK_Cpp, 19456 guessLanguage("foo.h", "[[noreturn, deprecated(\"gone, sorry\")]];")); 19457 EXPECT_EQ(FormatStyle::LK_ObjC, 19458 guessLanguage("foo.h", "[[noreturn foo] bar];")); 19459 EXPECT_EQ(FormatStyle::LK_Cpp, 19460 guessLanguage("foo.h", "[[clang::fallthrough]];")); 19461 EXPECT_EQ(FormatStyle::LK_ObjC, 19462 guessLanguage("foo.h", "[[clang:fallthrough] foo];")); 19463 EXPECT_EQ(FormatStyle::LK_Cpp, 19464 guessLanguage("foo.h", "[[gsl::suppress(\"type\")]];")); 19465 EXPECT_EQ(FormatStyle::LK_Cpp, 19466 guessLanguage("foo.h", "[[using clang: fallthrough]];")); 19467 EXPECT_EQ(FormatStyle::LK_ObjC, 19468 guessLanguage("foo.h", "[[abusing clang:fallthrough] bar];")); 19469 EXPECT_EQ(FormatStyle::LK_Cpp, 19470 guessLanguage("foo.h", "[[using gsl: suppress(\"type\")]];")); 19471 EXPECT_EQ( 19472 FormatStyle::LK_Cpp, 19473 guessLanguage("foo.h", "for (auto &&[endpoint, stream] : streams_)")); 19474 EXPECT_EQ( 19475 FormatStyle::LK_Cpp, 19476 guessLanguage("foo.h", 19477 "[[clang::callable_when(\"unconsumed\", \"unknown\")]]")); 19478 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "[[foo::bar, ...]]")); 19479 } 19480 19481 TEST_F(FormatTest, GuessLanguageWithCaret) { 19482 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "FOO(^);")); 19483 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "FOO(^, Bar);")); 19484 EXPECT_EQ(FormatStyle::LK_ObjC, 19485 guessLanguage("foo.h", "int(^)(char, float);")); 19486 EXPECT_EQ(FormatStyle::LK_ObjC, 19487 guessLanguage("foo.h", "int(^foo)(char, float);")); 19488 EXPECT_EQ(FormatStyle::LK_ObjC, 19489 guessLanguage("foo.h", "int(^foo[10])(char, float);")); 19490 EXPECT_EQ(FormatStyle::LK_ObjC, 19491 guessLanguage("foo.h", "int(^foo[kNumEntries])(char, float);")); 19492 EXPECT_EQ( 19493 FormatStyle::LK_ObjC, 19494 guessLanguage("foo.h", "int(^foo[(kNumEntries + 10)])(char, float);")); 19495 } 19496 19497 TEST_F(FormatTest, GuessLanguageWithPragmas) { 19498 EXPECT_EQ(FormatStyle::LK_Cpp, 19499 guessLanguage("foo.h", "__pragma(warning(disable:))")); 19500 EXPECT_EQ(FormatStyle::LK_Cpp, 19501 guessLanguage("foo.h", "#pragma(warning(disable:))")); 19502 EXPECT_EQ(FormatStyle::LK_Cpp, 19503 guessLanguage("foo.h", "_Pragma(warning(disable:))")); 19504 } 19505 19506 TEST_F(FormatTest, FormatsInlineAsmSymbolicNames) { 19507 // ASM symbolic names are identifiers that must be surrounded by [] without 19508 // space in between: 19509 // https://gcc.gnu.org/onlinedocs/gcc/Extended-Asm.html#InputOperands 19510 19511 // Example from https://bugs.llvm.org/show_bug.cgi?id=45108. 19512 verifyFormat(R"(// 19513 asm volatile("mrs %x[result], FPCR" : [result] "=r"(result)); 19514 )"); 19515 19516 // A list of several ASM symbolic names. 19517 verifyFormat(R"(asm("mov %[e], %[d]" : [d] "=rm"(d), [e] "rm"(*e));)"); 19518 19519 // ASM symbolic names in inline ASM with inputs and outputs. 19520 verifyFormat(R"(// 19521 asm("cmoveq %1, %2, %[result]" 19522 : [result] "=r"(result) 19523 : "r"(test), "r"(new), "[result]"(old)); 19524 )"); 19525 19526 // ASM symbolic names in inline ASM with no outputs. 19527 verifyFormat(R"(asm("mov %[e], %[d]" : : [d] "=rm"(d), [e] "rm"(*e));)"); 19528 } 19529 19530 TEST_F(FormatTest, GuessedLanguageWithInlineAsmClobbers) { 19531 EXPECT_EQ(FormatStyle::LK_Cpp, 19532 guessLanguage("foo.h", "void f() {\n" 19533 " asm (\"mov %[e], %[d]\"\n" 19534 " : [d] \"=rm\" (d)\n" 19535 " [e] \"rm\" (*e));\n" 19536 "}")); 19537 EXPECT_EQ(FormatStyle::LK_Cpp, 19538 guessLanguage("foo.h", "void f() {\n" 19539 " _asm (\"mov %[e], %[d]\"\n" 19540 " : [d] \"=rm\" (d)\n" 19541 " [e] \"rm\" (*e));\n" 19542 "}")); 19543 EXPECT_EQ(FormatStyle::LK_Cpp, 19544 guessLanguage("foo.h", "void f() {\n" 19545 " __asm (\"mov %[e], %[d]\"\n" 19546 " : [d] \"=rm\" (d)\n" 19547 " [e] \"rm\" (*e));\n" 19548 "}")); 19549 EXPECT_EQ(FormatStyle::LK_Cpp, 19550 guessLanguage("foo.h", "void f() {\n" 19551 " __asm__ (\"mov %[e], %[d]\"\n" 19552 " : [d] \"=rm\" (d)\n" 19553 " [e] \"rm\" (*e));\n" 19554 "}")); 19555 EXPECT_EQ(FormatStyle::LK_Cpp, 19556 guessLanguage("foo.h", "void f() {\n" 19557 " asm (\"mov %[e], %[d]\"\n" 19558 " : [d] \"=rm\" (d),\n" 19559 " [e] \"rm\" (*e));\n" 19560 "}")); 19561 EXPECT_EQ(FormatStyle::LK_Cpp, 19562 guessLanguage("foo.h", "void f() {\n" 19563 " asm volatile (\"mov %[e], %[d]\"\n" 19564 " : [d] \"=rm\" (d)\n" 19565 " [e] \"rm\" (*e));\n" 19566 "}")); 19567 } 19568 19569 TEST_F(FormatTest, GuessLanguageWithChildLines) { 19570 EXPECT_EQ(FormatStyle::LK_Cpp, 19571 guessLanguage("foo.h", "#define FOO ({ std::string s; })")); 19572 EXPECT_EQ(FormatStyle::LK_ObjC, 19573 guessLanguage("foo.h", "#define FOO ({ NSString *s; })")); 19574 EXPECT_EQ( 19575 FormatStyle::LK_Cpp, 19576 guessLanguage("foo.h", "#define FOO ({ foo(); ({ std::string s; }) })")); 19577 EXPECT_EQ( 19578 FormatStyle::LK_ObjC, 19579 guessLanguage("foo.h", "#define FOO ({ foo(); ({ NSString *s; }) })")); 19580 } 19581 19582 TEST_F(FormatTest, TypenameMacros) { 19583 std::vector<std::string> TypenameMacros = {"STACK_OF", "LIST", "TAILQ_ENTRY"}; 19584 19585 // Test case reported in https://bugs.llvm.org/show_bug.cgi?id=30353 19586 FormatStyle Google = getGoogleStyleWithColumns(0); 19587 Google.TypenameMacros = TypenameMacros; 19588 verifyFormat("struct foo {\n" 19589 " int bar;\n" 19590 " TAILQ_ENTRY(a) bleh;\n" 19591 "};", 19592 Google); 19593 19594 FormatStyle Macros = getLLVMStyle(); 19595 Macros.TypenameMacros = TypenameMacros; 19596 19597 verifyFormat("STACK_OF(int) a;", Macros); 19598 verifyFormat("STACK_OF(int) *a;", Macros); 19599 verifyFormat("STACK_OF(int const *) *a;", Macros); 19600 verifyFormat("STACK_OF(int *const) *a;", Macros); 19601 verifyFormat("STACK_OF(int, string) a;", Macros); 19602 verifyFormat("STACK_OF(LIST(int)) a;", Macros); 19603 verifyFormat("STACK_OF(LIST(int)) a, b;", Macros); 19604 verifyFormat("for (LIST(int) *a = NULL; a;) {\n}", Macros); 19605 verifyFormat("STACK_OF(int) f(LIST(int) *arg);", Macros); 19606 verifyFormat("vector<LIST(uint64_t) *attr> x;", Macros); 19607 verifyFormat("vector<LIST(uint64_t) *const> f(LIST(uint64_t) *arg);", Macros); 19608 19609 Macros.PointerAlignment = FormatStyle::PAS_Left; 19610 verifyFormat("STACK_OF(int)* a;", Macros); 19611 verifyFormat("STACK_OF(int*)* a;", Macros); 19612 verifyFormat("x = (STACK_OF(uint64_t))*a;", Macros); 19613 verifyFormat("x = (STACK_OF(uint64_t))&a;", Macros); 19614 verifyFormat("vector<STACK_OF(uint64_t)* attr> x;", Macros); 19615 } 19616 19617 TEST_F(FormatTest, AtomicQualifier) { 19618 // Check that we treate _Atomic as a type and not a function call 19619 FormatStyle Google = getGoogleStyleWithColumns(0); 19620 verifyFormat("struct foo {\n" 19621 " int a1;\n" 19622 " _Atomic(a) a2;\n" 19623 " _Atomic(_Atomic(int) *const) a3;\n" 19624 "};", 19625 Google); 19626 verifyFormat("_Atomic(uint64_t) a;"); 19627 verifyFormat("_Atomic(uint64_t) *a;"); 19628 verifyFormat("_Atomic(uint64_t const *) *a;"); 19629 verifyFormat("_Atomic(uint64_t *const) *a;"); 19630 verifyFormat("_Atomic(const uint64_t *) *a;"); 19631 verifyFormat("_Atomic(uint64_t) a;"); 19632 verifyFormat("_Atomic(_Atomic(uint64_t)) a;"); 19633 verifyFormat("_Atomic(_Atomic(uint64_t)) a, b;"); 19634 verifyFormat("for (_Atomic(uint64_t) *a = NULL; a;) {\n}"); 19635 verifyFormat("_Atomic(uint64_t) f(_Atomic(uint64_t) *arg);"); 19636 19637 verifyFormat("_Atomic(uint64_t) *s(InitValue);"); 19638 verifyFormat("_Atomic(uint64_t) *s{InitValue};"); 19639 FormatStyle Style = getLLVMStyle(); 19640 Style.PointerAlignment = FormatStyle::PAS_Left; 19641 verifyFormat("_Atomic(uint64_t)* s(InitValue);", Style); 19642 verifyFormat("_Atomic(uint64_t)* s{InitValue};", Style); 19643 verifyFormat("_Atomic(int)* a;", Style); 19644 verifyFormat("_Atomic(int*)* a;", Style); 19645 verifyFormat("vector<_Atomic(uint64_t)* attr> x;", Style); 19646 19647 Style.SpacesInCStyleCastParentheses = true; 19648 Style.SpacesInParentheses = false; 19649 verifyFormat("x = ( _Atomic(uint64_t) )*a;", Style); 19650 Style.SpacesInCStyleCastParentheses = false; 19651 Style.SpacesInParentheses = true; 19652 verifyFormat("x = (_Atomic( uint64_t ))*a;", Style); 19653 verifyFormat("x = (_Atomic( uint64_t ))&a;", Style); 19654 } 19655 19656 TEST_F(FormatTest, AmbersandInLamda) { 19657 // Test case reported in https://bugs.llvm.org/show_bug.cgi?id=41899 19658 FormatStyle AlignStyle = getLLVMStyle(); 19659 AlignStyle.PointerAlignment = FormatStyle::PAS_Left; 19660 verifyFormat("auto lambda = [&a = a]() { a = 2; };", AlignStyle); 19661 AlignStyle.PointerAlignment = FormatStyle::PAS_Right; 19662 verifyFormat("auto lambda = [&a = a]() { a = 2; };", AlignStyle); 19663 } 19664 19665 TEST_F(FormatTest, SpacesInConditionalStatement) { 19666 FormatStyle Spaces = getLLVMStyle(); 19667 Spaces.SpacesInConditionalStatement = true; 19668 verifyFormat("for ( int i = 0; i; i++ )\n continue;", Spaces); 19669 verifyFormat("if ( !a )\n return;", Spaces); 19670 verifyFormat("if ( a )\n return;", Spaces); 19671 verifyFormat("if constexpr ( a )\n return;", Spaces); 19672 verifyFormat("switch ( a )\ncase 1:\n return;", Spaces); 19673 verifyFormat("while ( a )\n return;", Spaces); 19674 verifyFormat("while ( (a && b) )\n return;", Spaces); 19675 verifyFormat("do {\n} while ( 1 != 0 );", Spaces); 19676 verifyFormat("try {\n} catch ( const std::exception & ) {\n}", Spaces); 19677 // Check that space on the left of "::" is inserted as expected at beginning 19678 // of condition. 19679 verifyFormat("while ( ::func() )\n return;", Spaces); 19680 } 19681 19682 TEST_F(FormatTest, AlternativeOperators) { 19683 // Test case for ensuring alternate operators are not 19684 // combined with their right most neighbour. 19685 verifyFormat("int a and b;"); 19686 verifyFormat("int a and_eq b;"); 19687 verifyFormat("int a bitand b;"); 19688 verifyFormat("int a bitor b;"); 19689 verifyFormat("int a compl b;"); 19690 verifyFormat("int a not b;"); 19691 verifyFormat("int a not_eq b;"); 19692 verifyFormat("int a or b;"); 19693 verifyFormat("int a xor b;"); 19694 verifyFormat("int a xor_eq b;"); 19695 verifyFormat("return this not_eq bitand other;"); 19696 verifyFormat("bool operator not_eq(const X bitand other)"); 19697 19698 verifyFormat("int a and 5;"); 19699 verifyFormat("int a and_eq 5;"); 19700 verifyFormat("int a bitand 5;"); 19701 verifyFormat("int a bitor 5;"); 19702 verifyFormat("int a compl 5;"); 19703 verifyFormat("int a not 5;"); 19704 verifyFormat("int a not_eq 5;"); 19705 verifyFormat("int a or 5;"); 19706 verifyFormat("int a xor 5;"); 19707 verifyFormat("int a xor_eq 5;"); 19708 19709 verifyFormat("int a compl(5);"); 19710 verifyFormat("int a not(5);"); 19711 19712 /* FIXME handle alternate tokens 19713 * https://en.cppreference.com/w/cpp/language/operator_alternative 19714 // alternative tokens 19715 verifyFormat("compl foo();"); // ~foo(); 19716 verifyFormat("foo() <%%>;"); // foo(); 19717 verifyFormat("void foo() <%%>;"); // void foo(){} 19718 verifyFormat("int a <:1:>;"); // int a[1];[ 19719 verifyFormat("%:define ABC abc"); // #define ABC abc 19720 verifyFormat("%:%:"); // ## 19721 */ 19722 } 19723 19724 TEST_F(FormatTest, STLWhileNotDefineChed) { 19725 verifyFormat("#if defined(while)\n" 19726 "#define while EMIT WARNING C4005\n" 19727 "#endif // while"); 19728 } 19729 19730 TEST_F(FormatTest, OperatorSpacing) { 19731 FormatStyle Style = getLLVMStyle(); 19732 Style.PointerAlignment = FormatStyle::PAS_Right; 19733 verifyFormat("Foo::operator*();", Style); 19734 verifyFormat("Foo::operator void *();", Style); 19735 verifyFormat("Foo::operator void **();", Style); 19736 verifyFormat("Foo::operator void *&();", Style); 19737 verifyFormat("Foo::operator void *&&();", Style); 19738 verifyFormat("Foo::operator void const *();", Style); 19739 verifyFormat("Foo::operator void const **();", Style); 19740 verifyFormat("Foo::operator void const *&();", Style); 19741 verifyFormat("Foo::operator void const *&&();", Style); 19742 verifyFormat("Foo::operator()(void *);", Style); 19743 verifyFormat("Foo::operator*(void *);", Style); 19744 verifyFormat("Foo::operator*();", Style); 19745 verifyFormat("Foo::operator**();", Style); 19746 verifyFormat("Foo::operator&();", Style); 19747 verifyFormat("Foo::operator<int> *();", Style); 19748 verifyFormat("Foo::operator<Foo> *();", Style); 19749 verifyFormat("Foo::operator<int> **();", Style); 19750 verifyFormat("Foo::operator<Foo> **();", Style); 19751 verifyFormat("Foo::operator<int> &();", Style); 19752 verifyFormat("Foo::operator<Foo> &();", Style); 19753 verifyFormat("Foo::operator<int> &&();", Style); 19754 verifyFormat("Foo::operator<Foo> &&();", Style); 19755 verifyFormat("Foo::operator<int> *&();", Style); 19756 verifyFormat("Foo::operator<Foo> *&();", Style); 19757 verifyFormat("Foo::operator<int> *&&();", Style); 19758 verifyFormat("Foo::operator<Foo> *&&();", Style); 19759 verifyFormat("operator*(int (*)(), class Foo);", Style); 19760 19761 verifyFormat("Foo::operator&();", Style); 19762 verifyFormat("Foo::operator void &();", Style); 19763 verifyFormat("Foo::operator void const &();", Style); 19764 verifyFormat("Foo::operator()(void &);", Style); 19765 verifyFormat("Foo::operator&(void &);", Style); 19766 verifyFormat("Foo::operator&();", Style); 19767 verifyFormat("operator&(int (&)(), class Foo);", Style); 19768 19769 verifyFormat("Foo::operator&&();", Style); 19770 verifyFormat("Foo::operator**();", Style); 19771 verifyFormat("Foo::operator void &&();", Style); 19772 verifyFormat("Foo::operator void const &&();", Style); 19773 verifyFormat("Foo::operator()(void &&);", Style); 19774 verifyFormat("Foo::operator&&(void &&);", Style); 19775 verifyFormat("Foo::operator&&();", Style); 19776 verifyFormat("operator&&(int(&&)(), class Foo);", Style); 19777 verifyFormat("operator const nsTArrayRight<E> &()", Style); 19778 verifyFormat("[[nodiscard]] operator const nsTArrayRight<E, Allocator> &()", 19779 Style); 19780 verifyFormat("operator void **()", Style); 19781 verifyFormat("operator const FooRight<Object> &()", Style); 19782 verifyFormat("operator const FooRight<Object> *()", Style); 19783 verifyFormat("operator const FooRight<Object> **()", Style); 19784 verifyFormat("operator const FooRight<Object> *&()", Style); 19785 verifyFormat("operator const FooRight<Object> *&&()", Style); 19786 19787 Style.PointerAlignment = FormatStyle::PAS_Left; 19788 verifyFormat("Foo::operator*();", Style); 19789 verifyFormat("Foo::operator**();", Style); 19790 verifyFormat("Foo::operator void*();", Style); 19791 verifyFormat("Foo::operator void**();", Style); 19792 verifyFormat("Foo::operator void*&();", Style); 19793 verifyFormat("Foo::operator void*&&();", Style); 19794 verifyFormat("Foo::operator void const*();", Style); 19795 verifyFormat("Foo::operator void const**();", Style); 19796 verifyFormat("Foo::operator void const*&();", Style); 19797 verifyFormat("Foo::operator void const*&&();", Style); 19798 verifyFormat("Foo::operator/*comment*/ void*();", Style); 19799 verifyFormat("Foo::operator/*a*/ const /*b*/ void*();", Style); 19800 verifyFormat("Foo::operator/*a*/ volatile /*b*/ void*();", Style); 19801 verifyFormat("Foo::operator()(void*);", Style); 19802 verifyFormat("Foo::operator*(void*);", Style); 19803 verifyFormat("Foo::operator*();", Style); 19804 verifyFormat("Foo::operator<int>*();", Style); 19805 verifyFormat("Foo::operator<Foo>*();", Style); 19806 verifyFormat("Foo::operator<int>**();", Style); 19807 verifyFormat("Foo::operator<Foo>**();", Style); 19808 verifyFormat("Foo::operator<Foo>*&();", Style); 19809 verifyFormat("Foo::operator<int>&();", Style); 19810 verifyFormat("Foo::operator<Foo>&();", Style); 19811 verifyFormat("Foo::operator<int>&&();", Style); 19812 verifyFormat("Foo::operator<Foo>&&();", Style); 19813 verifyFormat("Foo::operator<int>*&();", Style); 19814 verifyFormat("Foo::operator<Foo>*&();", Style); 19815 verifyFormat("operator*(int (*)(), class Foo);", Style); 19816 19817 verifyFormat("Foo::operator&();", Style); 19818 verifyFormat("Foo::operator void&();", Style); 19819 verifyFormat("Foo::operator void const&();", Style); 19820 verifyFormat("Foo::operator/*comment*/ void&();", Style); 19821 verifyFormat("Foo::operator/*a*/ const /*b*/ void&();", Style); 19822 verifyFormat("Foo::operator/*a*/ volatile /*b*/ void&();", Style); 19823 verifyFormat("Foo::operator()(void&);", Style); 19824 verifyFormat("Foo::operator&(void&);", Style); 19825 verifyFormat("Foo::operator&();", Style); 19826 verifyFormat("operator&(int (&)(), class Foo);", Style); 19827 19828 verifyFormat("Foo::operator&&();", Style); 19829 verifyFormat("Foo::operator void&&();", Style); 19830 verifyFormat("Foo::operator void const&&();", Style); 19831 verifyFormat("Foo::operator/*comment*/ void&&();", Style); 19832 verifyFormat("Foo::operator/*a*/ const /*b*/ void&&();", Style); 19833 verifyFormat("Foo::operator/*a*/ volatile /*b*/ void&&();", Style); 19834 verifyFormat("Foo::operator()(void&&);", Style); 19835 verifyFormat("Foo::operator&&(void&&);", Style); 19836 verifyFormat("Foo::operator&&();", Style); 19837 verifyFormat("operator&&(int(&&)(), class Foo);", Style); 19838 verifyFormat("operator const nsTArrayLeft<E>&()", Style); 19839 verifyFormat("[[nodiscard]] operator const nsTArrayLeft<E, Allocator>&()", 19840 Style); 19841 verifyFormat("operator void**()", Style); 19842 verifyFormat("operator const FooLeft<Object>&()", Style); 19843 verifyFormat("operator const FooLeft<Object>*()", Style); 19844 verifyFormat("operator const FooLeft<Object>**()", Style); 19845 verifyFormat("operator const FooLeft<Object>*&()", Style); 19846 verifyFormat("operator const FooLeft<Object>*&&()", Style); 19847 19848 // PR45107 19849 verifyFormat("operator Vector<String>&();", Style); 19850 verifyFormat("operator const Vector<String>&();", Style); 19851 verifyFormat("operator foo::Bar*();", Style); 19852 verifyFormat("operator const Foo<X>::Bar<Y>*();", Style); 19853 verifyFormat("operator/*a*/ const /*b*/ Foo /*c*/<X> /*d*/ ::Bar<Y>*();", 19854 Style); 19855 19856 Style.PointerAlignment = FormatStyle::PAS_Middle; 19857 verifyFormat("Foo::operator*();", Style); 19858 verifyFormat("Foo::operator void *();", Style); 19859 verifyFormat("Foo::operator()(void *);", Style); 19860 verifyFormat("Foo::operator*(void *);", Style); 19861 verifyFormat("Foo::operator*();", Style); 19862 verifyFormat("operator*(int (*)(), class Foo);", Style); 19863 19864 verifyFormat("Foo::operator&();", Style); 19865 verifyFormat("Foo::operator void &();", Style); 19866 verifyFormat("Foo::operator void const &();", Style); 19867 verifyFormat("Foo::operator()(void &);", Style); 19868 verifyFormat("Foo::operator&(void &);", Style); 19869 verifyFormat("Foo::operator&();", Style); 19870 verifyFormat("operator&(int (&)(), class Foo);", Style); 19871 19872 verifyFormat("Foo::operator&&();", Style); 19873 verifyFormat("Foo::operator void &&();", Style); 19874 verifyFormat("Foo::operator void const &&();", Style); 19875 verifyFormat("Foo::operator()(void &&);", Style); 19876 verifyFormat("Foo::operator&&(void &&);", Style); 19877 verifyFormat("Foo::operator&&();", Style); 19878 verifyFormat("operator&&(int(&&)(), class Foo);", Style); 19879 } 19880 19881 TEST_F(FormatTest, OperatorPassedAsAFunctionPtr) { 19882 FormatStyle Style = getLLVMStyle(); 19883 // PR46157 19884 verifyFormat("foo(operator+, -42);", Style); 19885 verifyFormat("foo(operator++, -42);", Style); 19886 verifyFormat("foo(operator--, -42);", Style); 19887 verifyFormat("foo(-42, operator--);", Style); 19888 verifyFormat("foo(-42, operator, );", Style); 19889 verifyFormat("foo(operator, , -42);", Style); 19890 } 19891 19892 TEST_F(FormatTest, WhitespaceSensitiveMacros) { 19893 FormatStyle Style = getLLVMStyle(); 19894 Style.WhitespaceSensitiveMacros.push_back("FOO"); 19895 19896 // Don't use the helpers here, since 'mess up' will change the whitespace 19897 // and these are all whitespace sensitive by definition 19898 EXPECT_EQ("FOO(String-ized&Messy+But(: :Still)=Intentional);", 19899 format("FOO(String-ized&Messy+But(: :Still)=Intentional);", Style)); 19900 EXPECT_EQ( 19901 "FOO(String-ized&Messy+But\\(: :Still)=Intentional);", 19902 format("FOO(String-ized&Messy+But\\(: :Still)=Intentional);", Style)); 19903 EXPECT_EQ("FOO(String-ized&Messy+But,: :Still=Intentional);", 19904 format("FOO(String-ized&Messy+But,: :Still=Intentional);", Style)); 19905 EXPECT_EQ("FOO(String-ized&Messy+But,: :\n" 19906 " Still=Intentional);", 19907 format("FOO(String-ized&Messy+But,: :\n" 19908 " Still=Intentional);", 19909 Style)); 19910 Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive; 19911 EXPECT_EQ("FOO(String-ized=&Messy+But,: :\n" 19912 " Still=Intentional);", 19913 format("FOO(String-ized=&Messy+But,: :\n" 19914 " Still=Intentional);", 19915 Style)); 19916 19917 Style.ColumnLimit = 21; 19918 EXPECT_EQ("FOO(String-ized&Messy+But: :Still=Intentional);", 19919 format("FOO(String-ized&Messy+But: :Still=Intentional);", Style)); 19920 } 19921 19922 TEST_F(FormatTest, VeryLongNamespaceCommentSplit) { 19923 // These tests are not in NamespaceFixer because that doesn't 19924 // test its interaction with line wrapping 19925 FormatStyle Style = getLLVMStyle(); 19926 Style.ColumnLimit = 80; 19927 verifyFormat("namespace {\n" 19928 "int i;\n" 19929 "int j;\n" 19930 "} // namespace", 19931 Style); 19932 19933 verifyFormat("namespace AAA {\n" 19934 "int i;\n" 19935 "int j;\n" 19936 "} // namespace AAA", 19937 Style); 19938 19939 EXPECT_EQ("namespace Averyveryveryverylongnamespace {\n" 19940 "int i;\n" 19941 "int j;\n" 19942 "} // namespace Averyveryveryverylongnamespace", 19943 format("namespace Averyveryveryverylongnamespace {\n" 19944 "int i;\n" 19945 "int j;\n" 19946 "}", 19947 Style)); 19948 19949 EXPECT_EQ( 19950 "namespace " 19951 "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::\n" 19952 " went::mad::now {\n" 19953 "int i;\n" 19954 "int j;\n" 19955 "} // namespace\n" 19956 " // " 19957 "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::" 19958 "went::mad::now", 19959 format("namespace " 19960 "would::it::save::you::a::lot::of::time::if_::i::" 19961 "just::gave::up::and_::went::mad::now {\n" 19962 "int i;\n" 19963 "int j;\n" 19964 "}", 19965 Style)); 19966 19967 // This used to duplicate the comment again and again on subsequent runs 19968 EXPECT_EQ( 19969 "namespace " 19970 "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::\n" 19971 " went::mad::now {\n" 19972 "int i;\n" 19973 "int j;\n" 19974 "} // namespace\n" 19975 " // " 19976 "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::" 19977 "went::mad::now", 19978 format("namespace " 19979 "would::it::save::you::a::lot::of::time::if_::i::" 19980 "just::gave::up::and_::went::mad::now {\n" 19981 "int i;\n" 19982 "int j;\n" 19983 "} // namespace\n" 19984 " // " 19985 "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::" 19986 "and_::went::mad::now", 19987 Style)); 19988 } 19989 19990 TEST_F(FormatTest, LikelyUnlikely) { 19991 FormatStyle Style = getLLVMStyle(); 19992 19993 verifyFormat("if (argc > 5) [[unlikely]] {\n" 19994 " return 29;\n" 19995 "}", 19996 Style); 19997 19998 verifyFormat("if (argc > 5) [[likely]] {\n" 19999 " return 29;\n" 20000 "}", 20001 Style); 20002 20003 verifyFormat("if (argc > 5) [[unlikely]] {\n" 20004 " return 29;\n" 20005 "} else [[likely]] {\n" 20006 " return 42;\n" 20007 "}\n", 20008 Style); 20009 20010 verifyFormat("if (argc > 5) [[unlikely]] {\n" 20011 " return 29;\n" 20012 "} else if (argc > 10) [[likely]] {\n" 20013 " return 99;\n" 20014 "} else {\n" 20015 " return 42;\n" 20016 "}\n", 20017 Style); 20018 20019 verifyFormat("if (argc > 5) [[gnu::unused]] {\n" 20020 " return 29;\n" 20021 "}", 20022 Style); 20023 } 20024 20025 TEST_F(FormatTest, PenaltyIndentedWhitespace) { 20026 verifyFormat("Constructor()\n" 20027 " : aaaaaa(aaaaaa), aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 20028 " aaaa(aaaaaaaaaaaaaaaaaa, " 20029 "aaaaaaaaaaaaaaaaaat))"); 20030 verifyFormat("Constructor()\n" 20031 " : aaaaaaaaaaaaa(aaaaaa), " 20032 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaa)"); 20033 20034 FormatStyle StyleWithWhitespacePenalty = getLLVMStyle(); 20035 StyleWithWhitespacePenalty.PenaltyIndentedWhitespace = 5; 20036 verifyFormat("Constructor()\n" 20037 " : aaaaaa(aaaaaa),\n" 20038 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 20039 " aaaa(aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaat))", 20040 StyleWithWhitespacePenalty); 20041 verifyFormat("Constructor()\n" 20042 " : aaaaaaaaaaaaa(aaaaaa), " 20043 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaa)", 20044 StyleWithWhitespacePenalty); 20045 } 20046 20047 TEST_F(FormatTest, LLVMDefaultStyle) { 20048 FormatStyle Style = getLLVMStyle(); 20049 verifyFormat("extern \"C\" {\n" 20050 "int foo();\n" 20051 "}", 20052 Style); 20053 } 20054 TEST_F(FormatTest, GNUDefaultStyle) { 20055 FormatStyle Style = getGNUStyle(); 20056 verifyFormat("extern \"C\"\n" 20057 "{\n" 20058 " int foo ();\n" 20059 "}", 20060 Style); 20061 } 20062 TEST_F(FormatTest, MozillaDefaultStyle) { 20063 FormatStyle Style = getMozillaStyle(); 20064 verifyFormat("extern \"C\"\n" 20065 "{\n" 20066 " int foo();\n" 20067 "}", 20068 Style); 20069 } 20070 TEST_F(FormatTest, GoogleDefaultStyle) { 20071 FormatStyle Style = getGoogleStyle(); 20072 verifyFormat("extern \"C\" {\n" 20073 "int foo();\n" 20074 "}", 20075 Style); 20076 } 20077 TEST_F(FormatTest, ChromiumDefaultStyle) { 20078 FormatStyle Style = getChromiumStyle(FormatStyle::LanguageKind::LK_Cpp); 20079 verifyFormat("extern \"C\" {\n" 20080 "int foo();\n" 20081 "}", 20082 Style); 20083 } 20084 TEST_F(FormatTest, MicrosoftDefaultStyle) { 20085 FormatStyle Style = getMicrosoftStyle(FormatStyle::LanguageKind::LK_Cpp); 20086 verifyFormat("extern \"C\"\n" 20087 "{\n" 20088 " int foo();\n" 20089 "}", 20090 Style); 20091 } 20092 TEST_F(FormatTest, WebKitDefaultStyle) { 20093 FormatStyle Style = getWebKitStyle(); 20094 verifyFormat("extern \"C\" {\n" 20095 "int foo();\n" 20096 "}", 20097 Style); 20098 } 20099 20100 TEST_F(FormatTest, ConceptsAndRequires) { 20101 FormatStyle Style = getLLVMStyle(); 20102 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 20103 20104 verifyFormat("template <typename T>\n" 20105 "concept Hashable = requires(T a) {\n" 20106 " { std::hash<T>{}(a) } -> std::convertible_to<std::size_t>;\n" 20107 "};", 20108 Style); 20109 verifyFormat("template <typename T>\n" 20110 "concept EqualityComparable = requires(T a, T b) {\n" 20111 " { a == b } -> bool;\n" 20112 "};", 20113 Style); 20114 verifyFormat("template <typename T>\n" 20115 "concept EqualityComparable = requires(T a, T b) {\n" 20116 " { a == b } -> bool;\n" 20117 " { a != b } -> bool;\n" 20118 "};", 20119 Style); 20120 verifyFormat("template <typename T>\n" 20121 "concept EqualityComparable = requires(T a, T b) {\n" 20122 " { a == b } -> bool;\n" 20123 " { a != b } -> bool;\n" 20124 "};", 20125 Style); 20126 20127 verifyFormat("template <typename It>\n" 20128 "requires Iterator<It>\n" 20129 "void sort(It begin, It end) {\n" 20130 " //....\n" 20131 "}", 20132 Style); 20133 20134 verifyFormat("template <typename T>\n" 20135 "concept Large = sizeof(T) > 10;", 20136 Style); 20137 20138 verifyFormat("template <typename T, typename U>\n" 20139 "concept FooableWith = requires(T t, U u) {\n" 20140 " typename T::foo_type;\n" 20141 " { t.foo(u) } -> typename T::foo_type;\n" 20142 " t++;\n" 20143 "};\n" 20144 "void doFoo(FooableWith<int> auto t) {\n" 20145 " t.foo(3);\n" 20146 "}", 20147 Style); 20148 verifyFormat("template <typename T>\n" 20149 "concept Context = sizeof(T) == 1;", 20150 Style); 20151 verifyFormat("template <typename T>\n" 20152 "concept Context = is_specialization_of_v<context, T>;", 20153 Style); 20154 verifyFormat("template <typename T>\n" 20155 "concept Node = std::is_object_v<T>;", 20156 Style); 20157 verifyFormat("template <typename T>\n" 20158 "concept Tree = true;", 20159 Style); 20160 20161 verifyFormat("template <typename T> int g(T i) requires Concept1<I> {\n" 20162 " //...\n" 20163 "}", 20164 Style); 20165 20166 verifyFormat( 20167 "template <typename T> int g(T i) requires Concept1<I> && Concept2<I> {\n" 20168 " //...\n" 20169 "}", 20170 Style); 20171 20172 verifyFormat( 20173 "template <typename T> int g(T i) requires Concept1<I> || Concept2<I> {\n" 20174 " //...\n" 20175 "}", 20176 Style); 20177 20178 verifyFormat("template <typename T>\n" 20179 "veryveryvery_long_return_type g(T i) requires Concept1<I> || " 20180 "Concept2<I> {\n" 20181 " //...\n" 20182 "}", 20183 Style); 20184 20185 verifyFormat("template <typename T>\n" 20186 "veryveryvery_long_return_type g(T i) requires Concept1<I> && " 20187 "Concept2<I> {\n" 20188 " //...\n" 20189 "}", 20190 Style); 20191 20192 verifyFormat( 20193 "template <typename T>\n" 20194 "veryveryvery_long_return_type g(T i) requires Concept1 && Concept2 {\n" 20195 " //...\n" 20196 "}", 20197 Style); 20198 20199 verifyFormat( 20200 "template <typename T>\n" 20201 "veryveryvery_long_return_type g(T i) requires Concept1 || Concept2 {\n" 20202 " //...\n" 20203 "}", 20204 Style); 20205 20206 verifyFormat("template <typename It>\n" 20207 "requires Foo<It>() && Bar<It> {\n" 20208 " //....\n" 20209 "}", 20210 Style); 20211 20212 verifyFormat("template <typename It>\n" 20213 "requires Foo<Bar<It>>() && Bar<Foo<It, It>> {\n" 20214 " //....\n" 20215 "}", 20216 Style); 20217 20218 verifyFormat("template <typename It>\n" 20219 "requires Foo<Bar<It, It>>() && Bar<Foo<It, It>> {\n" 20220 " //....\n" 20221 "}", 20222 Style); 20223 20224 verifyFormat( 20225 "template <typename It>\n" 20226 "requires Foo<Bar<It>, Baz<It>>() && Bar<Foo<It>, Baz<It, It>> {\n" 20227 " //....\n" 20228 "}", 20229 Style); 20230 20231 Style.IndentRequires = true; 20232 verifyFormat("template <typename It>\n" 20233 " requires Iterator<It>\n" 20234 "void sort(It begin, It end) {\n" 20235 " //....\n" 20236 "}", 20237 Style); 20238 verifyFormat("template <std::size index_>\n" 20239 " requires(index_ < sizeof...(Children_))\n" 20240 "Tree auto &child() {\n" 20241 " // ...\n" 20242 "}", 20243 Style); 20244 20245 Style.SpaceBeforeParens = FormatStyle::SBPO_Always; 20246 verifyFormat("template <typename T>\n" 20247 "concept Hashable = requires (T a) {\n" 20248 " { std::hash<T>{}(a) } -> std::convertible_to<std::size_t>;\n" 20249 "};", 20250 Style); 20251 20252 verifyFormat("template <class T = void>\n" 20253 " requires EqualityComparable<T> || Same<T, void>\n" 20254 "struct equal_to;", 20255 Style); 20256 20257 verifyFormat("template <class T>\n" 20258 " requires requires {\n" 20259 " T{};\n" 20260 " T (int);\n" 20261 " }\n", 20262 Style); 20263 20264 Style.ColumnLimit = 78; 20265 verifyFormat("template <typename T>\n" 20266 "concept Context = Traits<typename T::traits_type> and\n" 20267 " Interface<typename T::interface_type> and\n" 20268 " Request<typename T::request_type> and\n" 20269 " Response<typename T::response_type> and\n" 20270 " ContextExtension<typename T::extension_type> and\n" 20271 " ::std::is_copy_constructable<T> and " 20272 "::std::is_move_constructable<T> and\n" 20273 " requires (T c) {\n" 20274 " { c.response; } -> Response;\n" 20275 "} and requires (T c) {\n" 20276 " { c.request; } -> Request;\n" 20277 "}\n", 20278 Style); 20279 20280 verifyFormat("template <typename T>\n" 20281 "concept Context = Traits<typename T::traits_type> or\n" 20282 " Interface<typename T::interface_type> or\n" 20283 " Request<typename T::request_type> or\n" 20284 " Response<typename T::response_type> or\n" 20285 " ContextExtension<typename T::extension_type> or\n" 20286 " ::std::is_copy_constructable<T> or " 20287 "::std::is_move_constructable<T> or\n" 20288 " requires (T c) {\n" 20289 " { c.response; } -> Response;\n" 20290 "} or requires (T c) {\n" 20291 " { c.request; } -> Request;\n" 20292 "}\n", 20293 Style); 20294 20295 verifyFormat("template <typename T>\n" 20296 "concept Context = Traits<typename T::traits_type> &&\n" 20297 " Interface<typename T::interface_type> &&\n" 20298 " Request<typename T::request_type> &&\n" 20299 " Response<typename T::response_type> &&\n" 20300 " ContextExtension<typename T::extension_type> &&\n" 20301 " ::std::is_copy_constructable<T> && " 20302 "::std::is_move_constructable<T> &&\n" 20303 " requires (T c) {\n" 20304 " { c.response; } -> Response;\n" 20305 "} && requires (T c) {\n" 20306 " { c.request; } -> Request;\n" 20307 "}\n", 20308 Style); 20309 20310 verifyFormat("template <typename T>\nconcept someConcept = Constraint1<T> && " 20311 "Constraint2<T>;"); 20312 20313 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 20314 Style.BraceWrapping.AfterFunction = true; 20315 Style.BraceWrapping.AfterClass = true; 20316 Style.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes; 20317 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon; 20318 verifyFormat("void Foo () requires (std::copyable<T>)\n" 20319 "{\n" 20320 " return\n" 20321 "}\n", 20322 Style); 20323 20324 verifyFormat("void Foo () requires std::copyable<T>\n" 20325 "{\n" 20326 " return\n" 20327 "}\n", 20328 Style); 20329 20330 verifyFormat("template <std::semiregular F, std::semiregular... Args>\n" 20331 " requires (std::invocable<F, std::invoke_result_t<Args>...>)\n" 20332 "struct constant;", 20333 Style); 20334 20335 verifyFormat("template <std::semiregular F, std::semiregular... Args>\n" 20336 " requires std::invocable<F, std::invoke_result_t<Args>...>\n" 20337 "struct constant;", 20338 Style); 20339 20340 verifyFormat("template <class T>\n" 20341 "class plane_with_very_very_very_long_name\n" 20342 "{\n" 20343 " constexpr plane_with_very_very_very_long_name () requires " 20344 "std::copyable<T>\n" 20345 " : plane_with_very_very_very_long_name (1)\n" 20346 " {\n" 20347 " }\n" 20348 "}\n", 20349 Style); 20350 20351 verifyFormat("template <class T>\n" 20352 "class plane_with_long_name\n" 20353 "{\n" 20354 " constexpr plane_with_long_name () requires std::copyable<T>\n" 20355 " : plane_with_long_name (1)\n" 20356 " {\n" 20357 " }\n" 20358 "}\n", 20359 Style); 20360 20361 Style.BreakBeforeConceptDeclarations = false; 20362 verifyFormat("template <typename T> concept Tree = true;", Style); 20363 20364 Style.IndentRequires = false; 20365 verifyFormat("template <std::semiregular F, std::semiregular... Args>\n" 20366 "requires (std::invocable<F, std::invoke_result_t<Args>...>) " 20367 "struct constant;", 20368 Style); 20369 } 20370 20371 TEST_F(FormatTest, StatementAttributeLikeMacros) { 20372 FormatStyle Style = getLLVMStyle(); 20373 StringRef Source = "void Foo::slot() {\n" 20374 " unsigned char MyChar = 'x';\n" 20375 " emit signal(MyChar);\n" 20376 " Q_EMIT signal(MyChar);\n" 20377 "}"; 20378 20379 EXPECT_EQ(Source, format(Source, Style)); 20380 20381 Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 20382 EXPECT_EQ("void Foo::slot() {\n" 20383 " unsigned char MyChar = 'x';\n" 20384 " emit signal(MyChar);\n" 20385 " Q_EMIT signal(MyChar);\n" 20386 "}", 20387 format(Source, Style)); 20388 20389 Style.StatementAttributeLikeMacros.push_back("emit"); 20390 EXPECT_EQ(Source, format(Source, Style)); 20391 20392 Style.StatementAttributeLikeMacros = {}; 20393 EXPECT_EQ("void Foo::slot() {\n" 20394 " unsigned char MyChar = 'x';\n" 20395 " emit signal(MyChar);\n" 20396 " Q_EMIT signal(MyChar);\n" 20397 "}", 20398 format(Source, Style)); 20399 } 20400 20401 TEST_F(FormatTest, IndentAccessModifiers) { 20402 FormatStyle Style = getLLVMStyle(); 20403 Style.IndentAccessModifiers = true; 20404 // Members are *two* levels below the record; 20405 // Style.IndentWidth == 2, thus yielding a 4 spaces wide indentation. 20406 verifyFormat("class C {\n" 20407 " int i;\n" 20408 "};\n", 20409 Style); 20410 verifyFormat("union C {\n" 20411 " int i;\n" 20412 " unsigned u;\n" 20413 "};\n", 20414 Style); 20415 // Access modifiers should be indented one level below the record. 20416 verifyFormat("class C {\n" 20417 " public:\n" 20418 " int i;\n" 20419 "};\n", 20420 Style); 20421 verifyFormat("struct S {\n" 20422 " private:\n" 20423 " class C {\n" 20424 " int j;\n" 20425 "\n" 20426 " public:\n" 20427 " C();\n" 20428 " };\n" 20429 "\n" 20430 " public:\n" 20431 " int i;\n" 20432 "};\n", 20433 Style); 20434 // Enumerations are not records and should be unaffected. 20435 Style.AllowShortEnumsOnASingleLine = false; 20436 verifyFormat("enum class E\n" 20437 "{\n" 20438 " A,\n" 20439 " B\n" 20440 "};\n", 20441 Style); 20442 // Test with a different indentation width; 20443 // also proves that the result is Style.AccessModifierOffset agnostic. 20444 Style.IndentWidth = 3; 20445 verifyFormat("class C {\n" 20446 " public:\n" 20447 " int i;\n" 20448 "};\n", 20449 Style); 20450 } 20451 20452 TEST_F(FormatTest, LimitlessStringsAndComments) { 20453 auto Style = getLLVMStyleWithColumns(0); 20454 constexpr StringRef Code = 20455 "/**\n" 20456 " * This is a multiline comment with quite some long lines, at least for " 20457 "the LLVM Style.\n" 20458 " * We will redo this with strings and line comments. Just to check if " 20459 "everything is working.\n" 20460 " */\n" 20461 "bool foo() {\n" 20462 " /* Single line multi line comment. */\n" 20463 " const std::string String = \"This is a multiline string with quite " 20464 "some long lines, at least for the LLVM Style.\"\n" 20465 " \"We already did it with multi line " 20466 "comments, and we will do it with line comments. Just to check if " 20467 "everything is working.\";\n" 20468 " // This is a line comment (block) with quite some long lines, at " 20469 "least for the LLVM Style.\n" 20470 " // We already did this with multi line comments and strings. Just to " 20471 "check if everything is working.\n" 20472 " const std::string SmallString = \"Hello World\";\n" 20473 " // Small line comment\n" 20474 " return String.size() > SmallString.size();\n" 20475 "}"; 20476 EXPECT_EQ(Code, format(Code, Style)); 20477 } 20478 } // namespace 20479 } // namespace format 20480 } // namespace clang 20481