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 "clang/Frontend/TextDiagnosticPrinter.h" 15 #include "llvm/Support/Debug.h" 16 #include "llvm/Support/MemoryBuffer.h" 17 #include "gtest/gtest.h" 18 19 #define DEBUG_TYPE "format-test" 20 21 using clang::tooling::ReplacementTest; 22 using clang::tooling::toReplacements; 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(llvm::StringRef Expected, llvm::StringRef Code, 69 const FormatStyle &Style = getLLVMStyle()) { 70 EXPECT_EQ(Expected.str(), format(Expected, Style)) 71 << "Expected code is not stable"; 72 EXPECT_EQ(Expected.str(), format(Code, Style)); 73 if (Style.Language == FormatStyle::LK_Cpp) { 74 // Objective-C++ is a superset of C++, so everything checked for C++ 75 // needs to be checked for Objective-C++ as well. 76 FormatStyle ObjCStyle = Style; 77 ObjCStyle.Language = FormatStyle::LK_ObjC; 78 EXPECT_EQ(Expected.str(), format(test::messUp(Code), ObjCStyle)); 79 } 80 } 81 82 void verifyFormat(llvm::StringRef Code, 83 const FormatStyle &Style = getLLVMStyle()) { 84 verifyFormat(Code, test::messUp(Code), Style); 85 } 86 87 void verifyIncompleteFormat(llvm::StringRef Code, 88 const FormatStyle &Style = getLLVMStyle()) { 89 EXPECT_EQ(Code.str(), 90 format(test::messUp(Code), Style, SC_ExpectIncomplete)); 91 } 92 93 void verifyGoogleFormat(llvm::StringRef Code) { 94 verifyFormat(Code, getGoogleStyle()); 95 } 96 97 void verifyIndependentOfContext(llvm::StringRef text) { 98 verifyFormat(text); 99 verifyFormat(llvm::Twine("void f() { " + text + " }").str()); 100 } 101 102 /// \brief Verify that clang-format does not crash on the given input. 103 void verifyNoCrash(llvm::StringRef Code, 104 const FormatStyle &Style = getLLVMStyle()) { 105 format(Code, Style, SC_DoNotCheck); 106 } 107 108 int ReplacementCount; 109 }; 110 111 TEST_F(FormatTest, MessUp) { 112 EXPECT_EQ("1 2 3", test::messUp("1 2 3")); 113 EXPECT_EQ("1 2 3\n", test::messUp("1\n2\n3\n")); 114 EXPECT_EQ("a\n//b\nc", test::messUp("a\n//b\nc")); 115 EXPECT_EQ("a\n#b\nc", test::messUp("a\n#b\nc")); 116 EXPECT_EQ("a\n#b c d\ne", test::messUp("a\n#b\\\nc\\\nd\ne")); 117 } 118 119 TEST_F(FormatTest, DefaultLLVMStyleIsCpp) { 120 EXPECT_EQ(FormatStyle::LK_Cpp, getLLVMStyle().Language); 121 } 122 123 TEST_F(FormatTest, LLVMStyleOverride) { 124 EXPECT_EQ(FormatStyle::LK_Proto, 125 getLLVMStyle(FormatStyle::LK_Proto).Language); 126 } 127 128 //===----------------------------------------------------------------------===// 129 // Basic function tests. 130 //===----------------------------------------------------------------------===// 131 132 TEST_F(FormatTest, DoesNotChangeCorrectlyFormattedCode) { 133 EXPECT_EQ(";", format(";")); 134 } 135 136 TEST_F(FormatTest, FormatsGlobalStatementsAt0) { 137 EXPECT_EQ("int i;", format(" int i;")); 138 EXPECT_EQ("\nint i;", format(" \n\t \v \f int i;")); 139 EXPECT_EQ("int i;\nint j;", format(" int i; int j;")); 140 EXPECT_EQ("int i;\nint j;", format(" int i;\n int j;")); 141 } 142 143 TEST_F(FormatTest, FormatsUnwrappedLinesAtFirstFormat) { 144 EXPECT_EQ("int i;", format("int\ni;")); 145 } 146 147 TEST_F(FormatTest, FormatsNestedBlockStatements) { 148 EXPECT_EQ("{\n {\n {}\n }\n}", format("{{{}}}")); 149 } 150 151 TEST_F(FormatTest, FormatsNestedCall) { 152 verifyFormat("Method(f1, f2(f3));"); 153 verifyFormat("Method(f1(f2, f3()));"); 154 verifyFormat("Method(f1(f2, (f3())));"); 155 } 156 157 TEST_F(FormatTest, NestedNameSpecifiers) { 158 verifyFormat("vector<::Type> v;"); 159 verifyFormat("::ns::SomeFunction(::ns::SomeOtherFunction())"); 160 verifyFormat("static constexpr bool Bar = decltype(bar())::value;"); 161 verifyFormat("bool a = 2 < ::SomeFunction();"); 162 verifyFormat("ALWAYS_INLINE ::std::string getName();"); 163 verifyFormat("some::string getName();"); 164 } 165 166 TEST_F(FormatTest, OnlyGeneratesNecessaryReplacements) { 167 EXPECT_EQ("if (a) {\n" 168 " f();\n" 169 "}", 170 format("if(a){f();}")); 171 EXPECT_EQ(4, ReplacementCount); 172 EXPECT_EQ("if (a) {\n" 173 " f();\n" 174 "}", 175 format("if (a) {\n" 176 " f();\n" 177 "}")); 178 EXPECT_EQ(0, ReplacementCount); 179 EXPECT_EQ("/*\r\n" 180 "\r\n" 181 "*/\r\n", 182 format("/*\r\n" 183 "\r\n" 184 "*/\r\n")); 185 EXPECT_EQ(0, ReplacementCount); 186 } 187 188 TEST_F(FormatTest, RemovesEmptyLines) { 189 EXPECT_EQ("class C {\n" 190 " int i;\n" 191 "};", 192 format("class C {\n" 193 " int i;\n" 194 "\n" 195 "};")); 196 197 // Don't remove empty lines at the start of namespaces or extern "C" blocks. 198 EXPECT_EQ("namespace N {\n" 199 "\n" 200 "int i;\n" 201 "}", 202 format("namespace N {\n" 203 "\n" 204 "int i;\n" 205 "}", 206 getGoogleStyle())); 207 EXPECT_EQ("/* something */ namespace N {\n" 208 "\n" 209 "int i;\n" 210 "}", 211 format("/* something */ namespace N {\n" 212 "\n" 213 "int i;\n" 214 "}", 215 getGoogleStyle())); 216 EXPECT_EQ("inline namespace N {\n" 217 "\n" 218 "int i;\n" 219 "}", 220 format("inline namespace N {\n" 221 "\n" 222 "int i;\n" 223 "}", 224 getGoogleStyle())); 225 EXPECT_EQ("/* something */ inline namespace N {\n" 226 "\n" 227 "int i;\n" 228 "}", 229 format("/* something */ inline namespace N {\n" 230 "\n" 231 "int i;\n" 232 "}", 233 getGoogleStyle())); 234 EXPECT_EQ("export namespace N {\n" 235 "\n" 236 "int i;\n" 237 "}", 238 format("export namespace N {\n" 239 "\n" 240 "int i;\n" 241 "}", 242 getGoogleStyle())); 243 EXPECT_EQ("extern /**/ \"C\" /**/ {\n" 244 "\n" 245 "int i;\n" 246 "}", 247 format("extern /**/ \"C\" /**/ {\n" 248 "\n" 249 "int i;\n" 250 "}", 251 getGoogleStyle())); 252 253 // ...but do keep inlining and removing empty lines for non-block extern "C" 254 // functions. 255 verifyFormat("extern \"C\" int f() { return 42; }", getGoogleStyle()); 256 EXPECT_EQ("extern \"C\" int f() {\n" 257 " int i = 42;\n" 258 " return i;\n" 259 "}", 260 format("extern \"C\" int f() {\n" 261 "\n" 262 " int i = 42;\n" 263 " return i;\n" 264 "}", 265 getGoogleStyle())); 266 267 // Remove empty lines at the beginning and end of blocks. 268 EXPECT_EQ("void f() {\n" 269 "\n" 270 " if (a) {\n" 271 "\n" 272 " f();\n" 273 " }\n" 274 "}", 275 format("void f() {\n" 276 "\n" 277 " if (a) {\n" 278 "\n" 279 " f();\n" 280 "\n" 281 " }\n" 282 "\n" 283 "}", 284 getLLVMStyle())); 285 EXPECT_EQ("void f() {\n" 286 " if (a) {\n" 287 " f();\n" 288 " }\n" 289 "}", 290 format("void f() {\n" 291 "\n" 292 " if (a) {\n" 293 "\n" 294 " f();\n" 295 "\n" 296 " }\n" 297 "\n" 298 "}", 299 getGoogleStyle())); 300 301 // Don't remove empty lines in more complex control statements. 302 EXPECT_EQ("void f() {\n" 303 " if (a) {\n" 304 " f();\n" 305 "\n" 306 " } else if (b) {\n" 307 " f();\n" 308 " }\n" 309 "}", 310 format("void f() {\n" 311 " if (a) {\n" 312 " f();\n" 313 "\n" 314 " } else if (b) {\n" 315 " f();\n" 316 "\n" 317 " }\n" 318 "\n" 319 "}")); 320 321 // Don't remove empty lines before namespace endings. 322 FormatStyle LLVMWithNoNamespaceFix = getLLVMStyle(); 323 LLVMWithNoNamespaceFix.FixNamespaceComments = false; 324 EXPECT_EQ("namespace {\n" 325 "int i;\n" 326 "\n" 327 "}", 328 format("namespace {\n" 329 "int i;\n" 330 "\n" 331 "}", 332 LLVMWithNoNamespaceFix)); 333 EXPECT_EQ("namespace {\n" 334 "int i;\n" 335 "}", 336 format("namespace {\n" 337 "int i;\n" 338 "}", 339 LLVMWithNoNamespaceFix)); 340 EXPECT_EQ("namespace {\n" 341 "int i;\n" 342 "\n" 343 "};", 344 format("namespace {\n" 345 "int i;\n" 346 "\n" 347 "};", 348 LLVMWithNoNamespaceFix)); 349 EXPECT_EQ("namespace {\n" 350 "int i;\n" 351 "};", 352 format("namespace {\n" 353 "int i;\n" 354 "};", 355 LLVMWithNoNamespaceFix)); 356 EXPECT_EQ("namespace {\n" 357 "int i;\n" 358 "\n" 359 "}", 360 format("namespace {\n" 361 "int i;\n" 362 "\n" 363 "}")); 364 EXPECT_EQ("namespace {\n" 365 "int i;\n" 366 "\n" 367 "} // namespace", 368 format("namespace {\n" 369 "int i;\n" 370 "\n" 371 "} // namespace")); 372 373 FormatStyle Style = getLLVMStyle(); 374 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All; 375 Style.MaxEmptyLinesToKeep = 2; 376 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 377 Style.BraceWrapping.AfterClass = true; 378 Style.BraceWrapping.AfterFunction = true; 379 Style.KeepEmptyLinesAtTheStartOfBlocks = false; 380 381 EXPECT_EQ("class Foo\n" 382 "{\n" 383 " Foo() {}\n" 384 "\n" 385 " void funk() {}\n" 386 "};", 387 format("class Foo\n" 388 "{\n" 389 " Foo()\n" 390 " {\n" 391 " }\n" 392 "\n" 393 " void funk() {}\n" 394 "};", 395 Style)); 396 } 397 398 TEST_F(FormatTest, RecognizesBinaryOperatorKeywords) { 399 verifyFormat("x = (a) and (b);"); 400 verifyFormat("x = (a) or (b);"); 401 verifyFormat("x = (a) bitand (b);"); 402 verifyFormat("x = (a) bitor (b);"); 403 verifyFormat("x = (a) not_eq (b);"); 404 verifyFormat("x = (a) and_eq (b);"); 405 verifyFormat("x = (a) or_eq (b);"); 406 verifyFormat("x = (a) xor (b);"); 407 } 408 409 TEST_F(FormatTest, RecognizesUnaryOperatorKeywords) { 410 verifyFormat("x = compl(a);"); 411 verifyFormat("x = not(a);"); 412 verifyFormat("x = bitand(a);"); 413 // Unary operator must not be merged with the next identifier 414 verifyFormat("x = compl a;"); 415 verifyFormat("x = not a;"); 416 verifyFormat("x = bitand a;"); 417 } 418 419 //===----------------------------------------------------------------------===// 420 // Tests for control statements. 421 //===----------------------------------------------------------------------===// 422 423 TEST_F(FormatTest, FormatIfWithoutCompoundStatement) { 424 verifyFormat("if (true)\n f();\ng();"); 425 verifyFormat("if (a)\n if (b)\n if (c)\n g();\nh();"); 426 verifyFormat("if (a)\n if (b) {\n f();\n }\ng();"); 427 verifyFormat("if constexpr (true)\n" 428 " f();\ng();"); 429 verifyFormat("if CONSTEXPR (true)\n" 430 " f();\ng();"); 431 verifyFormat("if constexpr (a)\n" 432 " if constexpr (b)\n" 433 " if constexpr (c)\n" 434 " g();\n" 435 "h();"); 436 verifyFormat("if CONSTEXPR (a)\n" 437 " if CONSTEXPR (b)\n" 438 " if CONSTEXPR (c)\n" 439 " g();\n" 440 "h();"); 441 verifyFormat("if constexpr (a)\n" 442 " if constexpr (b) {\n" 443 " f();\n" 444 " }\n" 445 "g();"); 446 verifyFormat("if CONSTEXPR (a)\n" 447 " if CONSTEXPR (b) {\n" 448 " f();\n" 449 " }\n" 450 "g();"); 451 452 FormatStyle AllowsMergedIf = getLLVMStyle(); 453 AllowsMergedIf.AlignEscapedNewlines = FormatStyle::ENAS_Left; 454 AllowsMergedIf.AllowShortIfStatementsOnASingleLine = 455 FormatStyle::SIS_WithoutElse; 456 verifyFormat("if (a)\n" 457 " // comment\n" 458 " f();", 459 AllowsMergedIf); 460 verifyFormat("{\n" 461 " if (a)\n" 462 " label:\n" 463 " f();\n" 464 "}", 465 AllowsMergedIf); 466 verifyFormat("#define A \\\n" 467 " if (a) \\\n" 468 " label: \\\n" 469 " f()", 470 AllowsMergedIf); 471 verifyFormat("if (a)\n" 472 " ;", 473 AllowsMergedIf); 474 verifyFormat("if (a)\n" 475 " if (b) return;", 476 AllowsMergedIf); 477 478 verifyFormat("if (a) // Can't merge this\n" 479 " f();\n", 480 AllowsMergedIf); 481 verifyFormat("if (a) /* still don't merge */\n" 482 " f();", 483 AllowsMergedIf); 484 verifyFormat("if (a) { // Never merge this\n" 485 " f();\n" 486 "}", 487 AllowsMergedIf); 488 verifyFormat("if (a) { /* Never merge this */\n" 489 " f();\n" 490 "}", 491 AllowsMergedIf); 492 493 AllowsMergedIf.ColumnLimit = 14; 494 verifyFormat("if (a) return;", AllowsMergedIf); 495 verifyFormat("if (aaaaaaaaa)\n" 496 " return;", 497 AllowsMergedIf); 498 499 AllowsMergedIf.ColumnLimit = 13; 500 verifyFormat("if (a)\n return;", AllowsMergedIf); 501 } 502 503 TEST_F(FormatTest, FormatIfWithoutCompoundStatementButElseWith) { 504 FormatStyle AllowsMergedIf = getLLVMStyle(); 505 AllowsMergedIf.AlignEscapedNewlines = FormatStyle::ENAS_Left; 506 AllowsMergedIf.AllowShortIfStatementsOnASingleLine = 507 FormatStyle::SIS_WithoutElse; 508 verifyFormat("if (a)\n" 509 " f();\n" 510 "else {\n" 511 " g();\n" 512 "}", 513 AllowsMergedIf); 514 verifyFormat("if (a)\n" 515 " f();\n" 516 "else\n" 517 " g();\n", 518 AllowsMergedIf); 519 520 AllowsMergedIf.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_Always; 521 522 verifyFormat("if (a) f();\n" 523 "else {\n" 524 " g();\n" 525 "}", 526 AllowsMergedIf); 527 verifyFormat("if (a) f();\n" 528 "else {\n" 529 " if (a) f();\n" 530 " else {\n" 531 " g();\n" 532 " }\n" 533 " g();\n" 534 "}", 535 AllowsMergedIf); 536 } 537 538 TEST_F(FormatTest, FormatLoopsWithoutCompoundStatement) { 539 FormatStyle AllowsMergedLoops = getLLVMStyle(); 540 AllowsMergedLoops.AllowShortLoopsOnASingleLine = true; 541 verifyFormat("while (true) continue;", AllowsMergedLoops); 542 verifyFormat("for (;;) continue;", AllowsMergedLoops); 543 verifyFormat("for (int &v : vec) v *= 2;", AllowsMergedLoops); 544 verifyFormat("while (true)\n" 545 " ;", 546 AllowsMergedLoops); 547 verifyFormat("for (;;)\n" 548 " ;", 549 AllowsMergedLoops); 550 verifyFormat("for (;;)\n" 551 " for (;;) continue;", 552 AllowsMergedLoops); 553 verifyFormat("for (;;) // Can't merge this\n" 554 " continue;", 555 AllowsMergedLoops); 556 verifyFormat("for (;;) /* still don't merge */\n" 557 " continue;", 558 AllowsMergedLoops); 559 verifyFormat("do a++;\n" 560 "while (true);", 561 AllowsMergedLoops); 562 verifyFormat("do /* Don't merge */\n" 563 " a++;\n" 564 "while (true);", 565 AllowsMergedLoops); 566 verifyFormat("do // Don't merge\n" 567 " a++;\n" 568 "while (true);", 569 AllowsMergedLoops); 570 verifyFormat("do\n" 571 " // Don't merge\n" 572 " a++;\n" 573 "while (true);", 574 AllowsMergedLoops); 575 // Without braces labels are interpreted differently. 576 verifyFormat("{\n" 577 " do\n" 578 " label:\n" 579 " a++;\n" 580 " while (true);\n" 581 "}", 582 AllowsMergedLoops); 583 } 584 585 TEST_F(FormatTest, FormatShortBracedStatements) { 586 FormatStyle AllowSimpleBracedStatements = getLLVMStyle(); 587 AllowSimpleBracedStatements.ColumnLimit = 40; 588 AllowSimpleBracedStatements.AllowShortBlocksOnASingleLine = 589 FormatStyle::SBS_Always; 590 591 AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine = 592 FormatStyle::SIS_WithoutElse; 593 AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = true; 594 595 AllowSimpleBracedStatements.BreakBeforeBraces = FormatStyle::BS_Custom; 596 AllowSimpleBracedStatements.BraceWrapping.AfterFunction = true; 597 AllowSimpleBracedStatements.BraceWrapping.SplitEmptyRecord = false; 598 599 verifyFormat("if (true) {}", AllowSimpleBracedStatements); 600 verifyFormat("if constexpr (true) {}", AllowSimpleBracedStatements); 601 verifyFormat("if CONSTEXPR (true) {}", AllowSimpleBracedStatements); 602 verifyFormat("while (true) {}", AllowSimpleBracedStatements); 603 verifyFormat("for (;;) {}", AllowSimpleBracedStatements); 604 verifyFormat("if (true) { f(); }", AllowSimpleBracedStatements); 605 verifyFormat("if constexpr (true) { f(); }", AllowSimpleBracedStatements); 606 verifyFormat("if CONSTEXPR (true) { f(); }", AllowSimpleBracedStatements); 607 verifyFormat("while (true) { f(); }", AllowSimpleBracedStatements); 608 verifyFormat("for (;;) { f(); }", AllowSimpleBracedStatements); 609 verifyFormat("if (true) {\n" 610 " ffffffffffffffffffffffffffffffffffffffffffffffffffffff();\n" 611 "}", 612 AllowSimpleBracedStatements); 613 verifyFormat("if (true) { //\n" 614 " f();\n" 615 "}", 616 AllowSimpleBracedStatements); 617 verifyFormat("if (true) {\n" 618 " f();\n" 619 " f();\n" 620 "}", 621 AllowSimpleBracedStatements); 622 verifyFormat("if (true) {\n" 623 " f();\n" 624 "} else {\n" 625 " f();\n" 626 "}", 627 AllowSimpleBracedStatements); 628 629 verifyFormat("struct A2 {\n" 630 " int X;\n" 631 "};", 632 AllowSimpleBracedStatements); 633 verifyFormat("typedef struct A2 {\n" 634 " int X;\n" 635 "} A2_t;", 636 AllowSimpleBracedStatements); 637 verifyFormat("template <int> struct A2 {\n" 638 " struct B {};\n" 639 "};", 640 AllowSimpleBracedStatements); 641 642 AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine = 643 FormatStyle::SIS_Never; 644 verifyFormat("if (true) {}", AllowSimpleBracedStatements); 645 verifyFormat("if (true) {\n" 646 " f();\n" 647 "}", 648 AllowSimpleBracedStatements); 649 verifyFormat("if (true) {\n" 650 " f();\n" 651 "} else {\n" 652 " f();\n" 653 "}", 654 AllowSimpleBracedStatements); 655 656 AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = false; 657 verifyFormat("while (true) {}", AllowSimpleBracedStatements); 658 verifyFormat("while (true) {\n" 659 " f();\n" 660 "}", 661 AllowSimpleBracedStatements); 662 verifyFormat("for (;;) {}", AllowSimpleBracedStatements); 663 verifyFormat("for (;;) {\n" 664 " f();\n" 665 "}", 666 AllowSimpleBracedStatements); 667 668 AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine = 669 FormatStyle::SIS_WithoutElse; 670 AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = true; 671 AllowSimpleBracedStatements.BraceWrapping.AfterControlStatement = 672 FormatStyle::BWACS_Always; 673 674 verifyFormat("if (true) {}", AllowSimpleBracedStatements); 675 verifyFormat("if constexpr (true) {}", AllowSimpleBracedStatements); 676 verifyFormat("if CONSTEXPR (true) {}", AllowSimpleBracedStatements); 677 verifyFormat("while (true) {}", AllowSimpleBracedStatements); 678 verifyFormat("for (;;) {}", AllowSimpleBracedStatements); 679 verifyFormat("if (true) { f(); }", AllowSimpleBracedStatements); 680 verifyFormat("if constexpr (true) { f(); }", AllowSimpleBracedStatements); 681 verifyFormat("if CONSTEXPR (true) { f(); }", AllowSimpleBracedStatements); 682 verifyFormat("while (true) { f(); }", AllowSimpleBracedStatements); 683 verifyFormat("for (;;) { f(); }", AllowSimpleBracedStatements); 684 verifyFormat("if (true)\n" 685 "{\n" 686 " ffffffffffffffffffffffffffffffffffffffffffffffffffffff();\n" 687 "}", 688 AllowSimpleBracedStatements); 689 verifyFormat("if (true)\n" 690 "{ //\n" 691 " f();\n" 692 "}", 693 AllowSimpleBracedStatements); 694 verifyFormat("if (true)\n" 695 "{\n" 696 " f();\n" 697 " f();\n" 698 "}", 699 AllowSimpleBracedStatements); 700 verifyFormat("if (true)\n" 701 "{\n" 702 " f();\n" 703 "} else\n" 704 "{\n" 705 " f();\n" 706 "}", 707 AllowSimpleBracedStatements); 708 709 AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine = 710 FormatStyle::SIS_Never; 711 verifyFormat("if (true) {}", AllowSimpleBracedStatements); 712 verifyFormat("if (true)\n" 713 "{\n" 714 " f();\n" 715 "}", 716 AllowSimpleBracedStatements); 717 verifyFormat("if (true)\n" 718 "{\n" 719 " f();\n" 720 "} else\n" 721 "{\n" 722 " f();\n" 723 "}", 724 AllowSimpleBracedStatements); 725 726 AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = false; 727 verifyFormat("while (true) {}", AllowSimpleBracedStatements); 728 verifyFormat("while (true)\n" 729 "{\n" 730 " f();\n" 731 "}", 732 AllowSimpleBracedStatements); 733 verifyFormat("for (;;) {}", AllowSimpleBracedStatements); 734 verifyFormat("for (;;)\n" 735 "{\n" 736 " f();\n" 737 "}", 738 AllowSimpleBracedStatements); 739 } 740 741 TEST_F(FormatTest, ShortBlocksInMacrosDontMergeWithCodeAfterMacro) { 742 FormatStyle Style = getLLVMStyleWithColumns(60); 743 Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always; 744 Style.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_WithoutElse; 745 Style.BreakBeforeBraces = FormatStyle::BS_Allman; 746 EXPECT_EQ("#define A \\\n" 747 " if (HANDLEwernufrnuLwrmviferuvnierv) \\\n" 748 " { RET_ERR1_ANUIREUINERUIFNIOAerwfwrvnuier; }\n" 749 "X;", 750 format("#define A \\\n" 751 " if (HANDLEwernufrnuLwrmviferuvnierv) { \\\n" 752 " RET_ERR1_ANUIREUINERUIFNIOAerwfwrvnuier; \\\n" 753 " }\n" 754 "X;", 755 Style)); 756 } 757 758 TEST_F(FormatTest, ParseIfElse) { 759 verifyFormat("if (true)\n" 760 " if (true)\n" 761 " if (true)\n" 762 " f();\n" 763 " else\n" 764 " g();\n" 765 " else\n" 766 " h();\n" 767 "else\n" 768 " i();"); 769 verifyFormat("if (true)\n" 770 " if (true)\n" 771 " if (true) {\n" 772 " if (true)\n" 773 " f();\n" 774 " } else {\n" 775 " g();\n" 776 " }\n" 777 " else\n" 778 " h();\n" 779 "else {\n" 780 " i();\n" 781 "}"); 782 verifyFormat("if (true)\n" 783 " if constexpr (true)\n" 784 " if (true) {\n" 785 " if constexpr (true)\n" 786 " f();\n" 787 " } else {\n" 788 " g();\n" 789 " }\n" 790 " else\n" 791 " h();\n" 792 "else {\n" 793 " i();\n" 794 "}"); 795 verifyFormat("if (true)\n" 796 " if CONSTEXPR (true)\n" 797 " if (true) {\n" 798 " if CONSTEXPR (true)\n" 799 " f();\n" 800 " } else {\n" 801 " g();\n" 802 " }\n" 803 " else\n" 804 " h();\n" 805 "else {\n" 806 " i();\n" 807 "}"); 808 verifyFormat("void f() {\n" 809 " if (a) {\n" 810 " } else {\n" 811 " }\n" 812 "}"); 813 } 814 815 TEST_F(FormatTest, ElseIf) { 816 verifyFormat("if (a) {\n} else if (b) {\n}"); 817 verifyFormat("if (a)\n" 818 " f();\n" 819 "else if (b)\n" 820 " g();\n" 821 "else\n" 822 " h();"); 823 verifyFormat("if constexpr (a)\n" 824 " f();\n" 825 "else if constexpr (b)\n" 826 " g();\n" 827 "else\n" 828 " h();"); 829 verifyFormat("if CONSTEXPR (a)\n" 830 " f();\n" 831 "else if CONSTEXPR (b)\n" 832 " g();\n" 833 "else\n" 834 " h();"); 835 verifyFormat("if (a) {\n" 836 " f();\n" 837 "}\n" 838 "// or else ..\n" 839 "else {\n" 840 " g()\n" 841 "}"); 842 843 verifyFormat("if (a) {\n" 844 "} else if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 845 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n" 846 "}"); 847 verifyFormat("if (a) {\n" 848 "} else if constexpr (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 849 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n" 850 "}"); 851 verifyFormat("if (a) {\n" 852 "} else if CONSTEXPR (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 853 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n" 854 "}"); 855 verifyFormat("if (a) {\n" 856 "} else if (\n" 857 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n" 858 "}", 859 getLLVMStyleWithColumns(62)); 860 verifyFormat("if (a) {\n" 861 "} else if constexpr (\n" 862 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n" 863 "}", 864 getLLVMStyleWithColumns(62)); 865 verifyFormat("if (a) {\n" 866 "} else if CONSTEXPR (\n" 867 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n" 868 "}", 869 getLLVMStyleWithColumns(62)); 870 } 871 872 TEST_F(FormatTest, FormatsForLoop) { 873 verifyFormat( 874 "for (int VeryVeryLongLoopVariable = 0; VeryVeryLongLoopVariable < 10;\n" 875 " ++VeryVeryLongLoopVariable)\n" 876 " ;"); 877 verifyFormat("for (;;)\n" 878 " f();"); 879 verifyFormat("for (;;) {\n}"); 880 verifyFormat("for (;;) {\n" 881 " f();\n" 882 "}"); 883 verifyFormat("for (int i = 0; (i < 10); ++i) {\n}"); 884 885 verifyFormat( 886 "for (std::vector<UnwrappedLine>::iterator I = UnwrappedLines.begin(),\n" 887 " E = UnwrappedLines.end();\n" 888 " I != E; ++I) {\n}"); 889 890 verifyFormat( 891 "for (MachineFun::iterator IIII = PrevIt, EEEE = F.end(); IIII != EEEE;\n" 892 " ++IIIII) {\n}"); 893 verifyFormat("for (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaa =\n" 894 " aaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa;\n" 895 " aaaaaaaaaaa != aaaaaaaaaaaaaaaaaaa; ++aaaaaaaaaaa) {\n}"); 896 verifyFormat("for (llvm::ArrayRef<NamedDecl *>::iterator\n" 897 " I = FD->getDeclsInPrototypeScope().begin(),\n" 898 " E = FD->getDeclsInPrototypeScope().end();\n" 899 " I != E; ++I) {\n}"); 900 verifyFormat("for (SmallVectorImpl<TemplateIdAnnotationn *>::iterator\n" 901 " I = Container.begin(),\n" 902 " E = Container.end();\n" 903 " I != E; ++I) {\n}", 904 getLLVMStyleWithColumns(76)); 905 906 verifyFormat( 907 "for (aaaaaaaaaaaaaaaaa aaaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;\n" 908 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa !=\n" 909 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 910 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n" 911 " ++aaaaaaaaaaa) {\n}"); 912 verifyFormat("for (int i = 0; i < aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n" 913 " bbbbbbbbbbbbbbbbbbbb < ccccccccccccccc;\n" 914 " ++i) {\n}"); 915 verifyFormat("for (int aaaaaaaaaaa = 1; aaaaaaaaaaa <= bbbbbbbbbbbbbbb;\n" 916 " aaaaaaaaaaa++, bbbbbbbbbbbbbbbbb++) {\n" 917 "}"); 918 verifyFormat("for (some_namespace::SomeIterator iter( // force break\n" 919 " aaaaaaaaaa);\n" 920 " iter; ++iter) {\n" 921 "}"); 922 verifyFormat("for (auto aaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 923 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n" 924 " aaaaaaaaaaaaaaaaaaaaaaaaaaa != bbbbbbbbbbbbbbbbbbbbbbb;\n" 925 " ++aaaaaaaaaaaaaaaaaaaaaaaaaaa) {"); 926 927 // These should not be formatted as Objective-C for-in loops. 928 verifyFormat("for (Foo *x = 0; x != in; x++) {\n}"); 929 verifyFormat("Foo *x;\nfor (x = 0; x != in; x++) {\n}"); 930 verifyFormat("Foo *x;\nfor (x in y) {\n}"); 931 verifyFormat( 932 "for (const Foo<Bar> &baz = in.value(); !baz.at_end(); ++baz) {\n}"); 933 934 FormatStyle NoBinPacking = getLLVMStyle(); 935 NoBinPacking.BinPackParameters = false; 936 verifyFormat("for (int aaaaaaaaaaa = 1;\n" 937 " aaaaaaaaaaa <= aaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaa,\n" 938 " aaaaaaaaaaaaaaaa,\n" 939 " aaaaaaaaaaaaaaaa,\n" 940 " aaaaaaaaaaaaaaaa);\n" 941 " aaaaaaaaaaa++, bbbbbbbbbbbbbbbbb++) {\n" 942 "}", 943 NoBinPacking); 944 verifyFormat( 945 "for (std::vector<UnwrappedLine>::iterator I = UnwrappedLines.begin(),\n" 946 " E = UnwrappedLines.end();\n" 947 " I != E;\n" 948 " ++I) {\n}", 949 NoBinPacking); 950 951 FormatStyle AlignLeft = getLLVMStyle(); 952 AlignLeft.PointerAlignment = FormatStyle::PAS_Left; 953 verifyFormat("for (A* a = start; a < end; ++a, ++value) {\n}", AlignLeft); 954 } 955 956 TEST_F(FormatTest, RangeBasedForLoops) { 957 verifyFormat("for (auto aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n" 958 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}"); 959 verifyFormat("for (auto aaaaaaaaaaaaaaaaaaaaa :\n" 960 " aaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaa, aaaaaaaaaaaaa)) {\n}"); 961 verifyFormat("for (const aaaaaaaaaaaaaaaaaaaaa &aaaaaaaaa :\n" 962 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}"); 963 verifyFormat("for (aaaaaaaaa aaaaaaaaaaaaaaaaaaaaa :\n" 964 " aaaaaaaaaaaa.aaaaaaaaaaaa().aaaaaaaaa().a()) {\n}"); 965 } 966 967 TEST_F(FormatTest, ForEachLoops) { 968 verifyFormat("void f() {\n" 969 " foreach (Item *item, itemlist) {}\n" 970 " Q_FOREACH (Item *item, itemlist) {}\n" 971 " BOOST_FOREACH (Item *item, itemlist) {}\n" 972 " UNKNOWN_FORACH(Item * item, itemlist) {}\n" 973 "}"); 974 975 FormatStyle Style = getLLVMStyle(); 976 Style.SpaceBeforeParens = 977 FormatStyle::SBPO_ControlStatementsExceptForEachMacros; 978 verifyFormat("void f() {\n" 979 " foreach(Item *item, itemlist) {}\n" 980 " Q_FOREACH(Item *item, itemlist) {}\n" 981 " BOOST_FOREACH(Item *item, itemlist) {}\n" 982 " UNKNOWN_FORACH(Item * item, itemlist) {}\n" 983 "}", 984 Style); 985 986 // As function-like macros. 987 verifyFormat("#define foreach(x, y)\n" 988 "#define Q_FOREACH(x, y)\n" 989 "#define BOOST_FOREACH(x, y)\n" 990 "#define UNKNOWN_FOREACH(x, y)\n"); 991 992 // Not as function-like macros. 993 verifyFormat("#define foreach (x, y)\n" 994 "#define Q_FOREACH (x, y)\n" 995 "#define BOOST_FOREACH (x, y)\n" 996 "#define UNKNOWN_FOREACH (x, y)\n"); 997 } 998 999 TEST_F(FormatTest, FormatsWhileLoop) { 1000 verifyFormat("while (true) {\n}"); 1001 verifyFormat("while (true)\n" 1002 " f();"); 1003 verifyFormat("while () {\n}"); 1004 verifyFormat("while () {\n" 1005 " f();\n" 1006 "}"); 1007 } 1008 1009 TEST_F(FormatTest, FormatsDoWhile) { 1010 verifyFormat("do {\n" 1011 " do_something();\n" 1012 "} while (something());"); 1013 verifyFormat("do\n" 1014 " do_something();\n" 1015 "while (something());"); 1016 } 1017 1018 TEST_F(FormatTest, FormatsSwitchStatement) { 1019 verifyFormat("switch (x) {\n" 1020 "case 1:\n" 1021 " f();\n" 1022 " break;\n" 1023 "case kFoo:\n" 1024 "case ns::kBar:\n" 1025 "case kBaz:\n" 1026 " break;\n" 1027 "default:\n" 1028 " g();\n" 1029 " break;\n" 1030 "}"); 1031 verifyFormat("switch (x) {\n" 1032 "case 1: {\n" 1033 " f();\n" 1034 " break;\n" 1035 "}\n" 1036 "case 2: {\n" 1037 " break;\n" 1038 "}\n" 1039 "}"); 1040 verifyFormat("switch (x) {\n" 1041 "case 1: {\n" 1042 " f();\n" 1043 " {\n" 1044 " g();\n" 1045 " h();\n" 1046 " }\n" 1047 " break;\n" 1048 "}\n" 1049 "}"); 1050 verifyFormat("switch (x) {\n" 1051 "case 1: {\n" 1052 " f();\n" 1053 " if (foo) {\n" 1054 " g();\n" 1055 " h();\n" 1056 " }\n" 1057 " break;\n" 1058 "}\n" 1059 "}"); 1060 verifyFormat("switch (x) {\n" 1061 "case 1: {\n" 1062 " f();\n" 1063 " g();\n" 1064 "} break;\n" 1065 "}"); 1066 verifyFormat("switch (test)\n" 1067 " ;"); 1068 verifyFormat("switch (x) {\n" 1069 "default: {\n" 1070 " // Do nothing.\n" 1071 "}\n" 1072 "}"); 1073 verifyFormat("switch (x) {\n" 1074 "// comment\n" 1075 "// if 1, do f()\n" 1076 "case 1:\n" 1077 " f();\n" 1078 "}"); 1079 verifyFormat("switch (x) {\n" 1080 "case 1:\n" 1081 " // Do amazing stuff\n" 1082 " {\n" 1083 " f();\n" 1084 " g();\n" 1085 " }\n" 1086 " break;\n" 1087 "}"); 1088 verifyFormat("#define A \\\n" 1089 " switch (x) { \\\n" 1090 " case a: \\\n" 1091 " foo = b; \\\n" 1092 " }", 1093 getLLVMStyleWithColumns(20)); 1094 verifyFormat("#define OPERATION_CASE(name) \\\n" 1095 " case OP_name: \\\n" 1096 " return operations::Operation##name\n", 1097 getLLVMStyleWithColumns(40)); 1098 verifyFormat("switch (x) {\n" 1099 "case 1:;\n" 1100 "default:;\n" 1101 " int i;\n" 1102 "}"); 1103 1104 verifyGoogleFormat("switch (x) {\n" 1105 " case 1:\n" 1106 " f();\n" 1107 " break;\n" 1108 " case kFoo:\n" 1109 " case ns::kBar:\n" 1110 " case kBaz:\n" 1111 " break;\n" 1112 " default:\n" 1113 " g();\n" 1114 " break;\n" 1115 "}"); 1116 verifyGoogleFormat("switch (x) {\n" 1117 " case 1: {\n" 1118 " f();\n" 1119 " break;\n" 1120 " }\n" 1121 "}"); 1122 verifyGoogleFormat("switch (test)\n" 1123 " ;"); 1124 1125 verifyGoogleFormat("#define OPERATION_CASE(name) \\\n" 1126 " case OP_name: \\\n" 1127 " return operations::Operation##name\n"); 1128 verifyGoogleFormat("Operation codeToOperation(OperationCode OpCode) {\n" 1129 " // Get the correction operation class.\n" 1130 " switch (OpCode) {\n" 1131 " CASE(Add);\n" 1132 " CASE(Subtract);\n" 1133 " default:\n" 1134 " return operations::Unknown;\n" 1135 " }\n" 1136 "#undef OPERATION_CASE\n" 1137 "}"); 1138 verifyFormat("DEBUG({\n" 1139 " switch (x) {\n" 1140 " case A:\n" 1141 " f();\n" 1142 " break;\n" 1143 " // fallthrough\n" 1144 " case B:\n" 1145 " g();\n" 1146 " break;\n" 1147 " }\n" 1148 "});"); 1149 EXPECT_EQ("DEBUG({\n" 1150 " switch (x) {\n" 1151 " case A:\n" 1152 " f();\n" 1153 " break;\n" 1154 " // On B:\n" 1155 " case B:\n" 1156 " g();\n" 1157 " break;\n" 1158 " }\n" 1159 "});", 1160 format("DEBUG({\n" 1161 " switch (x) {\n" 1162 " case A:\n" 1163 " f();\n" 1164 " break;\n" 1165 " // On B:\n" 1166 " case B:\n" 1167 " g();\n" 1168 " break;\n" 1169 " }\n" 1170 "});", 1171 getLLVMStyle())); 1172 EXPECT_EQ("switch (n) {\n" 1173 "case 0: {\n" 1174 " return false;\n" 1175 "}\n" 1176 "default: {\n" 1177 " return true;\n" 1178 "}\n" 1179 "}", 1180 format("switch (n)\n" 1181 "{\n" 1182 "case 0: {\n" 1183 " return false;\n" 1184 "}\n" 1185 "default: {\n" 1186 " return true;\n" 1187 "}\n" 1188 "}", 1189 getLLVMStyle())); 1190 verifyFormat("switch (a) {\n" 1191 "case (b):\n" 1192 " return;\n" 1193 "}"); 1194 1195 verifyFormat("switch (a) {\n" 1196 "case some_namespace::\n" 1197 " some_constant:\n" 1198 " return;\n" 1199 "}", 1200 getLLVMStyleWithColumns(34)); 1201 1202 FormatStyle Style = getLLVMStyle(); 1203 Style.IndentCaseLabels = true; 1204 Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Never; 1205 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 1206 Style.BraceWrapping.AfterCaseLabel = true; 1207 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always; 1208 EXPECT_EQ("switch (n)\n" 1209 "{\n" 1210 " case 0:\n" 1211 " {\n" 1212 " return false;\n" 1213 " }\n" 1214 " default:\n" 1215 " {\n" 1216 " return true;\n" 1217 " }\n" 1218 "}", 1219 format("switch (n) {\n" 1220 " case 0: {\n" 1221 " return false;\n" 1222 " }\n" 1223 " default: {\n" 1224 " return true;\n" 1225 " }\n" 1226 "}", 1227 Style)); 1228 Style.BraceWrapping.AfterCaseLabel = false; 1229 EXPECT_EQ("switch (n)\n" 1230 "{\n" 1231 " case 0: {\n" 1232 " return false;\n" 1233 " }\n" 1234 " default: {\n" 1235 " return true;\n" 1236 " }\n" 1237 "}", 1238 format("switch (n) {\n" 1239 " case 0:\n" 1240 " {\n" 1241 " return false;\n" 1242 " }\n" 1243 " default:\n" 1244 " {\n" 1245 " return true;\n" 1246 " }\n" 1247 "}", 1248 Style)); 1249 Style.IndentCaseLabels = false; 1250 Style.IndentCaseBlocks = true; 1251 EXPECT_EQ("switch (n)\n" 1252 "{\n" 1253 "case 0:\n" 1254 " {\n" 1255 " return false;\n" 1256 " }\n" 1257 "case 1:\n" 1258 " break;\n" 1259 "default:\n" 1260 " {\n" 1261 " return true;\n" 1262 " }\n" 1263 "}", 1264 format("switch (n) {\n" 1265 "case 0: {\n" 1266 " return false;\n" 1267 "}\n" 1268 "case 1:\n" 1269 " break;\n" 1270 "default: {\n" 1271 " return true;\n" 1272 "}\n" 1273 "}", 1274 Style)); 1275 Style.IndentCaseLabels = true; 1276 Style.IndentCaseBlocks = true; 1277 EXPECT_EQ("switch (n)\n" 1278 "{\n" 1279 " case 0:\n" 1280 " {\n" 1281 " return false;\n" 1282 " }\n" 1283 " case 1:\n" 1284 " break;\n" 1285 " default:\n" 1286 " {\n" 1287 " return true;\n" 1288 " }\n" 1289 "}", 1290 format("switch (n) {\n" 1291 "case 0: {\n" 1292 " return false;\n" 1293 "}\n" 1294 "case 1:\n" 1295 " break;\n" 1296 "default: {\n" 1297 " return true;\n" 1298 "}\n" 1299 "}", 1300 Style)); 1301 } 1302 1303 TEST_F(FormatTest, CaseRanges) { 1304 verifyFormat("switch (x) {\n" 1305 "case 'A' ... 'Z':\n" 1306 "case 1 ... 5:\n" 1307 "case a ... b:\n" 1308 " break;\n" 1309 "}"); 1310 } 1311 1312 TEST_F(FormatTest, ShortEnums) { 1313 FormatStyle Style = getLLVMStyle(); 1314 Style.AllowShortEnumsOnASingleLine = true; 1315 verifyFormat("enum { A, B, C } ShortEnum1, ShortEnum2;", Style); 1316 Style.AllowShortEnumsOnASingleLine = false; 1317 verifyFormat("enum\n" 1318 "{\n" 1319 " A,\n" 1320 " B,\n" 1321 " C\n" 1322 "} ShortEnum1, ShortEnum2;", 1323 Style); 1324 } 1325 1326 TEST_F(FormatTest, ShortCaseLabels) { 1327 FormatStyle Style = getLLVMStyle(); 1328 Style.AllowShortCaseLabelsOnASingleLine = true; 1329 verifyFormat("switch (a) {\n" 1330 "case 1: x = 1; break;\n" 1331 "case 2: return;\n" 1332 "case 3:\n" 1333 "case 4:\n" 1334 "case 5: return;\n" 1335 "case 6: // comment\n" 1336 " return;\n" 1337 "case 7:\n" 1338 " // comment\n" 1339 " return;\n" 1340 "case 8:\n" 1341 " x = 8; // comment\n" 1342 " break;\n" 1343 "default: y = 1; break;\n" 1344 "}", 1345 Style); 1346 verifyFormat("switch (a) {\n" 1347 "case 0: return; // comment\n" 1348 "case 1: break; // comment\n" 1349 "case 2: return;\n" 1350 "// comment\n" 1351 "case 3: return;\n" 1352 "// comment 1\n" 1353 "// comment 2\n" 1354 "// comment 3\n" 1355 "case 4: break; /* comment */\n" 1356 "case 5:\n" 1357 " // comment\n" 1358 " break;\n" 1359 "case 6: /* comment */ x = 1; break;\n" 1360 "case 7: x = /* comment */ 1; break;\n" 1361 "case 8:\n" 1362 " x = 1; /* comment */\n" 1363 " break;\n" 1364 "case 9:\n" 1365 " break; // comment line 1\n" 1366 " // comment line 2\n" 1367 "}", 1368 Style); 1369 EXPECT_EQ("switch (a) {\n" 1370 "case 1:\n" 1371 " x = 8;\n" 1372 " // fall through\n" 1373 "case 2: x = 8;\n" 1374 "// comment\n" 1375 "case 3:\n" 1376 " return; /* comment line 1\n" 1377 " * comment line 2 */\n" 1378 "case 4: i = 8;\n" 1379 "// something else\n" 1380 "#if FOO\n" 1381 "case 5: break;\n" 1382 "#endif\n" 1383 "}", 1384 format("switch (a) {\n" 1385 "case 1: x = 8;\n" 1386 " // fall through\n" 1387 "case 2:\n" 1388 " x = 8;\n" 1389 "// comment\n" 1390 "case 3:\n" 1391 " return; /* comment line 1\n" 1392 " * comment line 2 */\n" 1393 "case 4:\n" 1394 " i = 8;\n" 1395 "// something else\n" 1396 "#if FOO\n" 1397 "case 5: break;\n" 1398 "#endif\n" 1399 "}", 1400 Style)); 1401 EXPECT_EQ("switch (a) {\n" 1402 "case 0:\n" 1403 " return; // long long long long long long long long long long " 1404 "long long comment\n" 1405 " // line\n" 1406 "}", 1407 format("switch (a) {\n" 1408 "case 0: return; // long long long long long long long long " 1409 "long long long long comment line\n" 1410 "}", 1411 Style)); 1412 EXPECT_EQ("switch (a) {\n" 1413 "case 0:\n" 1414 " return; /* long long long long long long long long long long " 1415 "long long comment\n" 1416 " line */\n" 1417 "}", 1418 format("switch (a) {\n" 1419 "case 0: return; /* long long long long long long long long " 1420 "long long long long comment line */\n" 1421 "}", 1422 Style)); 1423 verifyFormat("switch (a) {\n" 1424 "#if FOO\n" 1425 "case 0: return 0;\n" 1426 "#endif\n" 1427 "}", 1428 Style); 1429 verifyFormat("switch (a) {\n" 1430 "case 1: {\n" 1431 "}\n" 1432 "case 2: {\n" 1433 " return;\n" 1434 "}\n" 1435 "case 3: {\n" 1436 " x = 1;\n" 1437 " return;\n" 1438 "}\n" 1439 "case 4:\n" 1440 " if (x)\n" 1441 " return;\n" 1442 "}", 1443 Style); 1444 Style.ColumnLimit = 21; 1445 verifyFormat("switch (a) {\n" 1446 "case 1: x = 1; break;\n" 1447 "case 2: return;\n" 1448 "case 3:\n" 1449 "case 4:\n" 1450 "case 5: return;\n" 1451 "default:\n" 1452 " y = 1;\n" 1453 " break;\n" 1454 "}", 1455 Style); 1456 Style.ColumnLimit = 80; 1457 Style.AllowShortCaseLabelsOnASingleLine = false; 1458 Style.IndentCaseLabels = true; 1459 EXPECT_EQ("switch (n) {\n" 1460 " default /*comments*/:\n" 1461 " return true;\n" 1462 " case 0:\n" 1463 " return false;\n" 1464 "}", 1465 format("switch (n) {\n" 1466 "default/*comments*/:\n" 1467 " return true;\n" 1468 "case 0:\n" 1469 " return false;\n" 1470 "}", 1471 Style)); 1472 Style.AllowShortCaseLabelsOnASingleLine = true; 1473 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 1474 Style.BraceWrapping.AfterCaseLabel = true; 1475 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always; 1476 EXPECT_EQ("switch (n)\n" 1477 "{\n" 1478 " case 0:\n" 1479 " {\n" 1480 " return false;\n" 1481 " }\n" 1482 " default:\n" 1483 " {\n" 1484 " return true;\n" 1485 " }\n" 1486 "}", 1487 format("switch (n) {\n" 1488 " case 0: {\n" 1489 " return false;\n" 1490 " }\n" 1491 " default:\n" 1492 " {\n" 1493 " return true;\n" 1494 " }\n" 1495 "}", 1496 Style)); 1497 } 1498 1499 TEST_F(FormatTest, FormatsLabels) { 1500 verifyFormat("void f() {\n" 1501 " some_code();\n" 1502 "test_label:\n" 1503 " some_other_code();\n" 1504 " {\n" 1505 " some_more_code();\n" 1506 " another_label:\n" 1507 " some_more_code();\n" 1508 " }\n" 1509 "}"); 1510 verifyFormat("{\n" 1511 " some_code();\n" 1512 "test_label:\n" 1513 " some_other_code();\n" 1514 "}"); 1515 verifyFormat("{\n" 1516 " some_code();\n" 1517 "test_label:;\n" 1518 " int i = 0;\n" 1519 "}"); 1520 FormatStyle Style = getLLVMStyle(); 1521 Style.IndentGotoLabels = false; 1522 verifyFormat("void f() {\n" 1523 " some_code();\n" 1524 "test_label:\n" 1525 " some_other_code();\n" 1526 " {\n" 1527 " some_more_code();\n" 1528 "another_label:\n" 1529 " some_more_code();\n" 1530 " }\n" 1531 "}", 1532 Style); 1533 verifyFormat("{\n" 1534 " some_code();\n" 1535 "test_label:\n" 1536 " some_other_code();\n" 1537 "}", 1538 Style); 1539 verifyFormat("{\n" 1540 " some_code();\n" 1541 "test_label:;\n" 1542 " int i = 0;\n" 1543 "}"); 1544 } 1545 1546 TEST_F(FormatTest, MultiLineControlStatements) { 1547 FormatStyle Style = getLLVMStyle(); 1548 Style.BreakBeforeBraces = FormatStyle::BraceBreakingStyle::BS_Custom; 1549 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_MultiLine; 1550 Style.ColumnLimit = 20; 1551 // Short lines should keep opening brace on same line. 1552 EXPECT_EQ("if (foo) {\n" 1553 " bar();\n" 1554 "}", 1555 format("if(foo){bar();}", Style)); 1556 EXPECT_EQ("if (foo) {\n" 1557 " bar();\n" 1558 "} else {\n" 1559 " baz();\n" 1560 "}", 1561 format("if(foo){bar();}else{baz();}", Style)); 1562 EXPECT_EQ("if (foo && bar) {\n" 1563 " baz();\n" 1564 "}", 1565 format("if(foo&&bar){baz();}", Style)); 1566 EXPECT_EQ("if (foo) {\n" 1567 " bar();\n" 1568 "} else if (baz) {\n" 1569 " quux();\n" 1570 "}", 1571 format("if(foo){bar();}else if(baz){quux();}", Style)); 1572 EXPECT_EQ( 1573 "if (foo) {\n" 1574 " bar();\n" 1575 "} else if (baz) {\n" 1576 " quux();\n" 1577 "} else {\n" 1578 " foobar();\n" 1579 "}", 1580 format("if(foo){bar();}else if(baz){quux();}else{foobar();}", Style)); 1581 EXPECT_EQ("for (;;) {\n" 1582 " foo();\n" 1583 "}", 1584 format("for(;;){foo();}")); 1585 EXPECT_EQ("while (1) {\n" 1586 " foo();\n" 1587 "}", 1588 format("while(1){foo();}", Style)); 1589 EXPECT_EQ("switch (foo) {\n" 1590 "case bar:\n" 1591 " return;\n" 1592 "}", 1593 format("switch(foo){case bar:return;}", Style)); 1594 EXPECT_EQ("try {\n" 1595 " foo();\n" 1596 "} catch (...) {\n" 1597 " bar();\n" 1598 "}", 1599 format("try{foo();}catch(...){bar();}", Style)); 1600 EXPECT_EQ("do {\n" 1601 " foo();\n" 1602 "} while (bar &&\n" 1603 " baz);", 1604 format("do{foo();}while(bar&&baz);", Style)); 1605 // Long lines should put opening brace on new line. 1606 EXPECT_EQ("if (foo && bar &&\n" 1607 " baz)\n" 1608 "{\n" 1609 " quux();\n" 1610 "}", 1611 format("if(foo&&bar&&baz){quux();}", Style)); 1612 EXPECT_EQ("if (foo && bar &&\n" 1613 " baz)\n" 1614 "{\n" 1615 " quux();\n" 1616 "}", 1617 format("if (foo && bar &&\n" 1618 " baz) {\n" 1619 " quux();\n" 1620 "}", 1621 Style)); 1622 EXPECT_EQ("if (foo) {\n" 1623 " bar();\n" 1624 "} else if (baz ||\n" 1625 " quux)\n" 1626 "{\n" 1627 " foobar();\n" 1628 "}", 1629 format("if(foo){bar();}else if(baz||quux){foobar();}", Style)); 1630 EXPECT_EQ( 1631 "if (foo) {\n" 1632 " bar();\n" 1633 "} else if (baz ||\n" 1634 " quux)\n" 1635 "{\n" 1636 " foobar();\n" 1637 "} else {\n" 1638 " barbaz();\n" 1639 "}", 1640 format("if(foo){bar();}else if(baz||quux){foobar();}else{barbaz();}", 1641 Style)); 1642 EXPECT_EQ("for (int i = 0;\n" 1643 " i < 10; ++i)\n" 1644 "{\n" 1645 " foo();\n" 1646 "}", 1647 format("for(int i=0;i<10;++i){foo();}", Style)); 1648 EXPECT_EQ("while (foo || bar ||\n" 1649 " baz)\n" 1650 "{\n" 1651 " quux();\n" 1652 "}", 1653 format("while(foo||bar||baz){quux();}", Style)); 1654 EXPECT_EQ("switch (\n" 1655 " foo = barbaz)\n" 1656 "{\n" 1657 "case quux:\n" 1658 " return;\n" 1659 "}", 1660 format("switch(foo=barbaz){case quux:return;}", Style)); 1661 EXPECT_EQ("try {\n" 1662 " foo();\n" 1663 "} catch (\n" 1664 " Exception &bar)\n" 1665 "{\n" 1666 " baz();\n" 1667 "}", 1668 format("try{foo();}catch(Exception&bar){baz();}", Style)); 1669 Style.ColumnLimit = 1670 40; // to concentrate at brace wrapping, not line wrap due to column limit 1671 EXPECT_EQ("try {\n" 1672 " foo();\n" 1673 "} catch (Exception &bar) {\n" 1674 " baz();\n" 1675 "}", 1676 format("try{foo();}catch(Exception&bar){baz();}", Style)); 1677 Style.ColumnLimit = 1678 20; // to concentrate at brace wrapping, not line wrap due to column limit 1679 1680 Style.BraceWrapping.BeforeElse = true; 1681 EXPECT_EQ( 1682 "if (foo) {\n" 1683 " bar();\n" 1684 "}\n" 1685 "else if (baz ||\n" 1686 " quux)\n" 1687 "{\n" 1688 " foobar();\n" 1689 "}\n" 1690 "else {\n" 1691 " barbaz();\n" 1692 "}", 1693 format("if(foo){bar();}else if(baz||quux){foobar();}else{barbaz();}", 1694 Style)); 1695 1696 Style.BraceWrapping.BeforeCatch = true; 1697 EXPECT_EQ("try {\n" 1698 " foo();\n" 1699 "}\n" 1700 "catch (...) {\n" 1701 " baz();\n" 1702 "}", 1703 format("try{foo();}catch(...){baz();}", Style)); 1704 } 1705 1706 //===----------------------------------------------------------------------===// 1707 // Tests for classes, namespaces, etc. 1708 //===----------------------------------------------------------------------===// 1709 1710 TEST_F(FormatTest, DoesNotBreakSemiAfterClassDecl) { 1711 verifyFormat("class A {};"); 1712 } 1713 1714 TEST_F(FormatTest, UnderstandsAccessSpecifiers) { 1715 verifyFormat("class A {\n" 1716 "public:\n" 1717 "public: // comment\n" 1718 "protected:\n" 1719 "private:\n" 1720 " void f() {}\n" 1721 "};"); 1722 verifyFormat("export class A {\n" 1723 "public:\n" 1724 "public: // comment\n" 1725 "protected:\n" 1726 "private:\n" 1727 " void f() {}\n" 1728 "};"); 1729 verifyGoogleFormat("class A {\n" 1730 " public:\n" 1731 " protected:\n" 1732 " private:\n" 1733 " void f() {}\n" 1734 "};"); 1735 verifyGoogleFormat("export class A {\n" 1736 " public:\n" 1737 " protected:\n" 1738 " private:\n" 1739 " void f() {}\n" 1740 "};"); 1741 verifyFormat("class A {\n" 1742 "public slots:\n" 1743 " void f1() {}\n" 1744 "public Q_SLOTS:\n" 1745 " void f2() {}\n" 1746 "protected slots:\n" 1747 " void f3() {}\n" 1748 "protected Q_SLOTS:\n" 1749 " void f4() {}\n" 1750 "private slots:\n" 1751 " void f5() {}\n" 1752 "private Q_SLOTS:\n" 1753 " void f6() {}\n" 1754 "signals:\n" 1755 " void g1();\n" 1756 "Q_SIGNALS:\n" 1757 " void g2();\n" 1758 "};"); 1759 1760 // Don't interpret 'signals' the wrong way. 1761 verifyFormat("signals.set();"); 1762 verifyFormat("for (Signals signals : f()) {\n}"); 1763 verifyFormat("{\n" 1764 " signals.set(); // This needs indentation.\n" 1765 "}"); 1766 verifyFormat("void f() {\n" 1767 "label:\n" 1768 " signals.baz();\n" 1769 "}"); 1770 } 1771 1772 TEST_F(FormatTest, SeparatesLogicalBlocks) { 1773 EXPECT_EQ("class A {\n" 1774 "public:\n" 1775 " void f();\n" 1776 "\n" 1777 "private:\n" 1778 " void g() {}\n" 1779 " // test\n" 1780 "protected:\n" 1781 " int h;\n" 1782 "};", 1783 format("class A {\n" 1784 "public:\n" 1785 "void f();\n" 1786 "private:\n" 1787 "void g() {}\n" 1788 "// test\n" 1789 "protected:\n" 1790 "int h;\n" 1791 "};")); 1792 EXPECT_EQ("class A {\n" 1793 "protected:\n" 1794 "public:\n" 1795 " void f();\n" 1796 "};", 1797 format("class A {\n" 1798 "protected:\n" 1799 "\n" 1800 "public:\n" 1801 "\n" 1802 " void f();\n" 1803 "};")); 1804 1805 // Even ensure proper spacing inside macros. 1806 EXPECT_EQ("#define B \\\n" 1807 " class A { \\\n" 1808 " protected: \\\n" 1809 " public: \\\n" 1810 " void f(); \\\n" 1811 " };", 1812 format("#define B \\\n" 1813 " class A { \\\n" 1814 " protected: \\\n" 1815 " \\\n" 1816 " public: \\\n" 1817 " \\\n" 1818 " void f(); \\\n" 1819 " };", 1820 getGoogleStyle())); 1821 // But don't remove empty lines after macros ending in access specifiers. 1822 EXPECT_EQ("#define A private:\n" 1823 "\n" 1824 "int i;", 1825 format("#define A private:\n" 1826 "\n" 1827 "int i;")); 1828 } 1829 1830 TEST_F(FormatTest, FormatsClasses) { 1831 verifyFormat("class A : public B {};"); 1832 verifyFormat("class A : public ::B {};"); 1833 1834 verifyFormat( 1835 "class AAAAAAAAAAAAAAAAAAAA : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n" 1836 " public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};"); 1837 verifyFormat("class AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\n" 1838 " : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n" 1839 " public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};"); 1840 verifyFormat( 1841 "class A : public B, public C, public D, public E, public F {};"); 1842 verifyFormat("class AAAAAAAAAAAA : public B,\n" 1843 " public C,\n" 1844 " public D,\n" 1845 " public E,\n" 1846 " public F,\n" 1847 " public G {};"); 1848 1849 verifyFormat("class\n" 1850 " ReallyReallyLongClassName {\n" 1851 " int i;\n" 1852 "};", 1853 getLLVMStyleWithColumns(32)); 1854 verifyFormat("struct aaaaaaaaaaaaa : public aaaaaaaaaaaaaaaaaaa< // break\n" 1855 " aaaaaaaaaaaaaaaa> {};"); 1856 verifyFormat("struct aaaaaaaaaaaaaaaaaaaa\n" 1857 " : public aaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaa,\n" 1858 " aaaaaaaaaaaaaaaaaaaaaa> {};"); 1859 verifyFormat("template <class R, class C>\n" 1860 "struct Aaaaaaaaaaaaaaaaa<R (C::*)(int) const>\n" 1861 " : Aaaaaaaaaaaaaaaaa<R (C::*)(int)> {};"); 1862 verifyFormat("class ::A::B {};"); 1863 } 1864 1865 TEST_F(FormatTest, BreakInheritanceStyle) { 1866 FormatStyle StyleWithInheritanceBreakBeforeComma = getLLVMStyle(); 1867 StyleWithInheritanceBreakBeforeComma.BreakInheritanceList = 1868 FormatStyle::BILS_BeforeComma; 1869 verifyFormat("class MyClass : public X {};", 1870 StyleWithInheritanceBreakBeforeComma); 1871 verifyFormat("class MyClass\n" 1872 " : public X\n" 1873 " , public Y {};", 1874 StyleWithInheritanceBreakBeforeComma); 1875 verifyFormat("class AAAAAAAAAAAAAAAAAAAAAA\n" 1876 " : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB\n" 1877 " , public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};", 1878 StyleWithInheritanceBreakBeforeComma); 1879 verifyFormat("struct aaaaaaaaaaaaa\n" 1880 " : public aaaaaaaaaaaaaaaaaaa< // break\n" 1881 " aaaaaaaaaaaaaaaa> {};", 1882 StyleWithInheritanceBreakBeforeComma); 1883 1884 FormatStyle StyleWithInheritanceBreakAfterColon = getLLVMStyle(); 1885 StyleWithInheritanceBreakAfterColon.BreakInheritanceList = 1886 FormatStyle::BILS_AfterColon; 1887 verifyFormat("class MyClass : public X {};", 1888 StyleWithInheritanceBreakAfterColon); 1889 verifyFormat("class MyClass : public X, public Y {};", 1890 StyleWithInheritanceBreakAfterColon); 1891 verifyFormat("class AAAAAAAAAAAAAAAAAAAAAA :\n" 1892 " public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n" 1893 " public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};", 1894 StyleWithInheritanceBreakAfterColon); 1895 verifyFormat("struct aaaaaaaaaaaaa :\n" 1896 " public aaaaaaaaaaaaaaaaaaa< // break\n" 1897 " aaaaaaaaaaaaaaaa> {};", 1898 StyleWithInheritanceBreakAfterColon); 1899 } 1900 1901 TEST_F(FormatTest, FormatsVariableDeclarationsAfterStructOrClass) { 1902 verifyFormat("class A {\n} a, b;"); 1903 verifyFormat("struct A {\n} a, b;"); 1904 verifyFormat("union A {\n} a;"); 1905 } 1906 1907 TEST_F(FormatTest, FormatsEnum) { 1908 verifyFormat("enum {\n" 1909 " Zero,\n" 1910 " One = 1,\n" 1911 " Two = One + 1,\n" 1912 " Three = (One + Two),\n" 1913 " Four = (Zero && (One ^ Two)) | (One << Two),\n" 1914 " Five = (One, Two, Three, Four, 5)\n" 1915 "};"); 1916 verifyGoogleFormat("enum {\n" 1917 " Zero,\n" 1918 " One = 1,\n" 1919 " Two = One + 1,\n" 1920 " Three = (One + Two),\n" 1921 " Four = (Zero && (One ^ Two)) | (One << Two),\n" 1922 " Five = (One, Two, Three, Four, 5)\n" 1923 "};"); 1924 verifyFormat("enum Enum {};"); 1925 verifyFormat("enum {};"); 1926 verifyFormat("enum X E {} d;"); 1927 verifyFormat("enum __attribute__((...)) E {} d;"); 1928 verifyFormat("enum __declspec__((...)) E {} d;"); 1929 verifyFormat("enum {\n" 1930 " Bar = Foo<int, int>::value\n" 1931 "};", 1932 getLLVMStyleWithColumns(30)); 1933 1934 verifyFormat("enum ShortEnum { A, B, C };"); 1935 verifyGoogleFormat("enum ShortEnum { A, B, C };"); 1936 1937 EXPECT_EQ("enum KeepEmptyLines {\n" 1938 " ONE,\n" 1939 "\n" 1940 " TWO,\n" 1941 "\n" 1942 " THREE\n" 1943 "}", 1944 format("enum KeepEmptyLines {\n" 1945 " ONE,\n" 1946 "\n" 1947 " TWO,\n" 1948 "\n" 1949 "\n" 1950 " THREE\n" 1951 "}")); 1952 verifyFormat("enum E { // comment\n" 1953 " ONE,\n" 1954 " TWO\n" 1955 "};\n" 1956 "int i;"); 1957 1958 FormatStyle EightIndent = getLLVMStyle(); 1959 EightIndent.IndentWidth = 8; 1960 verifyFormat("enum {\n" 1961 " VOID,\n" 1962 " CHAR,\n" 1963 " SHORT,\n" 1964 " INT,\n" 1965 " LONG,\n" 1966 " SIGNED,\n" 1967 " UNSIGNED,\n" 1968 " BOOL,\n" 1969 " FLOAT,\n" 1970 " DOUBLE,\n" 1971 " COMPLEX\n" 1972 "};", 1973 EightIndent); 1974 1975 // Not enums. 1976 verifyFormat("enum X f() {\n" 1977 " a();\n" 1978 " return 42;\n" 1979 "}"); 1980 verifyFormat("enum X Type::f() {\n" 1981 " a();\n" 1982 " return 42;\n" 1983 "}"); 1984 verifyFormat("enum ::X f() {\n" 1985 " a();\n" 1986 " return 42;\n" 1987 "}"); 1988 verifyFormat("enum ns::X f() {\n" 1989 " a();\n" 1990 " return 42;\n" 1991 "}"); 1992 } 1993 1994 TEST_F(FormatTest, FormatsEnumsWithErrors) { 1995 verifyFormat("enum Type {\n" 1996 " One = 0; // These semicolons should be commas.\n" 1997 " Two = 1;\n" 1998 "};"); 1999 verifyFormat("namespace n {\n" 2000 "enum Type {\n" 2001 " One,\n" 2002 " Two, // missing };\n" 2003 " int i;\n" 2004 "}\n" 2005 "void g() {}"); 2006 } 2007 2008 TEST_F(FormatTest, FormatsEnumStruct) { 2009 verifyFormat("enum struct {\n" 2010 " Zero,\n" 2011 " One = 1,\n" 2012 " Two = One + 1,\n" 2013 " Three = (One + Two),\n" 2014 " Four = (Zero && (One ^ Two)) | (One << Two),\n" 2015 " Five = (One, Two, Three, Four, 5)\n" 2016 "};"); 2017 verifyFormat("enum struct Enum {};"); 2018 verifyFormat("enum struct {};"); 2019 verifyFormat("enum struct X E {} d;"); 2020 verifyFormat("enum struct __attribute__((...)) E {} d;"); 2021 verifyFormat("enum struct __declspec__((...)) E {} d;"); 2022 verifyFormat("enum struct X f() {\n a();\n return 42;\n}"); 2023 } 2024 2025 TEST_F(FormatTest, FormatsEnumClass) { 2026 verifyFormat("enum class {\n" 2027 " Zero,\n" 2028 " One = 1,\n" 2029 " Two = One + 1,\n" 2030 " Three = (One + Two),\n" 2031 " Four = (Zero && (One ^ Two)) | (One << Two),\n" 2032 " Five = (One, Two, Three, Four, 5)\n" 2033 "};"); 2034 verifyFormat("enum class Enum {};"); 2035 verifyFormat("enum class {};"); 2036 verifyFormat("enum class X E {} d;"); 2037 verifyFormat("enum class __attribute__((...)) E {} d;"); 2038 verifyFormat("enum class __declspec__((...)) E {} d;"); 2039 verifyFormat("enum class X f() {\n a();\n return 42;\n}"); 2040 } 2041 2042 TEST_F(FormatTest, FormatsEnumTypes) { 2043 verifyFormat("enum X : int {\n" 2044 " A, // Force multiple lines.\n" 2045 " B\n" 2046 "};"); 2047 verifyFormat("enum X : int { A, B };"); 2048 verifyFormat("enum X : std::uint32_t { A, B };"); 2049 } 2050 2051 TEST_F(FormatTest, FormatsTypedefEnum) { 2052 FormatStyle Style = getLLVMStyle(); 2053 Style.ColumnLimit = 40; 2054 verifyFormat("typedef enum {} EmptyEnum;"); 2055 verifyFormat("typedef enum { A, B, C } ShortEnum;"); 2056 verifyFormat("typedef enum {\n" 2057 " ZERO = 0,\n" 2058 " ONE = 1,\n" 2059 " TWO = 2,\n" 2060 " THREE = 3\n" 2061 "} LongEnum;", 2062 Style); 2063 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 2064 Style.BraceWrapping.AfterEnum = true; 2065 verifyFormat("typedef enum {} EmptyEnum;"); 2066 verifyFormat("typedef enum { A, B, C } ShortEnum;"); 2067 verifyFormat("typedef enum\n" 2068 "{\n" 2069 " ZERO = 0,\n" 2070 " ONE = 1,\n" 2071 " TWO = 2,\n" 2072 " THREE = 3\n" 2073 "} LongEnum;", 2074 Style); 2075 } 2076 2077 TEST_F(FormatTest, FormatsNSEnums) { 2078 verifyGoogleFormat("typedef NS_ENUM(NSInteger, SomeName) { AAA, BBB }"); 2079 verifyGoogleFormat( 2080 "typedef NS_CLOSED_ENUM(NSInteger, SomeName) { AAA, BBB }"); 2081 verifyGoogleFormat("typedef NS_ENUM(NSInteger, MyType) {\n" 2082 " // Information about someDecentlyLongValue.\n" 2083 " someDecentlyLongValue,\n" 2084 " // Information about anotherDecentlyLongValue.\n" 2085 " anotherDecentlyLongValue,\n" 2086 " // Information about aThirdDecentlyLongValue.\n" 2087 " aThirdDecentlyLongValue\n" 2088 "};"); 2089 verifyGoogleFormat("typedef NS_CLOSED_ENUM(NSInteger, MyType) {\n" 2090 " // Information about someDecentlyLongValue.\n" 2091 " someDecentlyLongValue,\n" 2092 " // Information about anotherDecentlyLongValue.\n" 2093 " anotherDecentlyLongValue,\n" 2094 " // Information about aThirdDecentlyLongValue.\n" 2095 " aThirdDecentlyLongValue\n" 2096 "};"); 2097 verifyGoogleFormat("typedef NS_OPTIONS(NSInteger, MyType) {\n" 2098 " a = 1,\n" 2099 " b = 2,\n" 2100 " c = 3,\n" 2101 "};"); 2102 verifyGoogleFormat("typedef CF_ENUM(NSInteger, MyType) {\n" 2103 " a = 1,\n" 2104 " b = 2,\n" 2105 " c = 3,\n" 2106 "};"); 2107 verifyGoogleFormat("typedef CF_CLOSED_ENUM(NSInteger, MyType) {\n" 2108 " a = 1,\n" 2109 " b = 2,\n" 2110 " c = 3,\n" 2111 "};"); 2112 verifyGoogleFormat("typedef CF_OPTIONS(NSInteger, MyType) {\n" 2113 " a = 1,\n" 2114 " b = 2,\n" 2115 " c = 3,\n" 2116 "};"); 2117 } 2118 2119 TEST_F(FormatTest, FormatsBitfields) { 2120 verifyFormat("struct Bitfields {\n" 2121 " unsigned sClass : 8;\n" 2122 " unsigned ValueKind : 2;\n" 2123 "};"); 2124 verifyFormat("struct A {\n" 2125 " int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa : 1,\n" 2126 " bbbbbbbbbbbbbbbbbbbbbbbbb;\n" 2127 "};"); 2128 verifyFormat("struct MyStruct {\n" 2129 " uchar data;\n" 2130 " uchar : 8;\n" 2131 " uchar : 8;\n" 2132 " uchar other;\n" 2133 "};"); 2134 } 2135 2136 TEST_F(FormatTest, FormatsNamespaces) { 2137 FormatStyle LLVMWithNoNamespaceFix = getLLVMStyle(); 2138 LLVMWithNoNamespaceFix.FixNamespaceComments = false; 2139 2140 verifyFormat("namespace some_namespace {\n" 2141 "class A {};\n" 2142 "void f() { f(); }\n" 2143 "}", 2144 LLVMWithNoNamespaceFix); 2145 verifyFormat("namespace N::inline D {\n" 2146 "class A {};\n" 2147 "void f() { f(); }\n" 2148 "}", 2149 LLVMWithNoNamespaceFix); 2150 verifyFormat("namespace N::inline D::E {\n" 2151 "class A {};\n" 2152 "void f() { f(); }\n" 2153 "}", 2154 LLVMWithNoNamespaceFix); 2155 verifyFormat("namespace [[deprecated(\"foo[bar\")]] some_namespace {\n" 2156 "class A {};\n" 2157 "void f() { f(); }\n" 2158 "}", 2159 LLVMWithNoNamespaceFix); 2160 verifyFormat("/* something */ namespace some_namespace {\n" 2161 "class A {};\n" 2162 "void f() { f(); }\n" 2163 "}", 2164 LLVMWithNoNamespaceFix); 2165 verifyFormat("namespace {\n" 2166 "class A {};\n" 2167 "void f() { f(); }\n" 2168 "}", 2169 LLVMWithNoNamespaceFix); 2170 verifyFormat("/* something */ namespace {\n" 2171 "class A {};\n" 2172 "void f() { f(); }\n" 2173 "}", 2174 LLVMWithNoNamespaceFix); 2175 verifyFormat("inline namespace X {\n" 2176 "class A {};\n" 2177 "void f() { f(); }\n" 2178 "}", 2179 LLVMWithNoNamespaceFix); 2180 verifyFormat("/* something */ inline namespace X {\n" 2181 "class A {};\n" 2182 "void f() { f(); }\n" 2183 "}", 2184 LLVMWithNoNamespaceFix); 2185 verifyFormat("export namespace X {\n" 2186 "class A {};\n" 2187 "void f() { f(); }\n" 2188 "}", 2189 LLVMWithNoNamespaceFix); 2190 verifyFormat("using namespace some_namespace;\n" 2191 "class A {};\n" 2192 "void f() { f(); }", 2193 LLVMWithNoNamespaceFix); 2194 2195 // This code is more common than we thought; if we 2196 // layout this correctly the semicolon will go into 2197 // its own line, which is undesirable. 2198 verifyFormat("namespace {};", LLVMWithNoNamespaceFix); 2199 verifyFormat("namespace {\n" 2200 "class A {};\n" 2201 "};", 2202 LLVMWithNoNamespaceFix); 2203 2204 verifyFormat("namespace {\n" 2205 "int SomeVariable = 0; // comment\n" 2206 "} // namespace", 2207 LLVMWithNoNamespaceFix); 2208 EXPECT_EQ("#ifndef HEADER_GUARD\n" 2209 "#define HEADER_GUARD\n" 2210 "namespace my_namespace {\n" 2211 "int i;\n" 2212 "} // my_namespace\n" 2213 "#endif // HEADER_GUARD", 2214 format("#ifndef HEADER_GUARD\n" 2215 " #define HEADER_GUARD\n" 2216 " namespace my_namespace {\n" 2217 "int i;\n" 2218 "} // my_namespace\n" 2219 "#endif // HEADER_GUARD", 2220 LLVMWithNoNamespaceFix)); 2221 2222 EXPECT_EQ("namespace A::B {\n" 2223 "class C {};\n" 2224 "}", 2225 format("namespace A::B {\n" 2226 "class C {};\n" 2227 "}", 2228 LLVMWithNoNamespaceFix)); 2229 2230 FormatStyle Style = getLLVMStyle(); 2231 Style.NamespaceIndentation = FormatStyle::NI_All; 2232 EXPECT_EQ("namespace out {\n" 2233 " int i;\n" 2234 " namespace in {\n" 2235 " int i;\n" 2236 " } // namespace in\n" 2237 "} // namespace out", 2238 format("namespace out {\n" 2239 "int i;\n" 2240 "namespace in {\n" 2241 "int i;\n" 2242 "} // namespace in\n" 2243 "} // namespace out", 2244 Style)); 2245 2246 Style.NamespaceIndentation = FormatStyle::NI_Inner; 2247 EXPECT_EQ("namespace out {\n" 2248 "int i;\n" 2249 "namespace in {\n" 2250 " int i;\n" 2251 "} // namespace in\n" 2252 "} // namespace out", 2253 format("namespace out {\n" 2254 "int i;\n" 2255 "namespace in {\n" 2256 "int i;\n" 2257 "} // namespace in\n" 2258 "} // namespace out", 2259 Style)); 2260 } 2261 2262 TEST_F(FormatTest, NamespaceMacros) { 2263 FormatStyle Style = getLLVMStyle(); 2264 Style.NamespaceMacros.push_back("TESTSUITE"); 2265 2266 verifyFormat("TESTSUITE(A) {\n" 2267 "int foo();\n" 2268 "} // TESTSUITE(A)", 2269 Style); 2270 2271 verifyFormat("TESTSUITE(A, B) {\n" 2272 "int foo();\n" 2273 "} // TESTSUITE(A)", 2274 Style); 2275 2276 // Properly indent according to NamespaceIndentation style 2277 Style.NamespaceIndentation = FormatStyle::NI_All; 2278 verifyFormat("TESTSUITE(A) {\n" 2279 " int foo();\n" 2280 "} // TESTSUITE(A)", 2281 Style); 2282 verifyFormat("TESTSUITE(A) {\n" 2283 " namespace B {\n" 2284 " int foo();\n" 2285 " } // namespace B\n" 2286 "} // TESTSUITE(A)", 2287 Style); 2288 verifyFormat("namespace A {\n" 2289 " TESTSUITE(B) {\n" 2290 " int foo();\n" 2291 " } // TESTSUITE(B)\n" 2292 "} // namespace A", 2293 Style); 2294 2295 Style.NamespaceIndentation = FormatStyle::NI_Inner; 2296 verifyFormat("TESTSUITE(A) {\n" 2297 "TESTSUITE(B) {\n" 2298 " int foo();\n" 2299 "} // TESTSUITE(B)\n" 2300 "} // TESTSUITE(A)", 2301 Style); 2302 verifyFormat("TESTSUITE(A) {\n" 2303 "namespace B {\n" 2304 " int foo();\n" 2305 "} // namespace B\n" 2306 "} // TESTSUITE(A)", 2307 Style); 2308 verifyFormat("namespace A {\n" 2309 "TESTSUITE(B) {\n" 2310 " int foo();\n" 2311 "} // TESTSUITE(B)\n" 2312 "} // namespace A", 2313 Style); 2314 2315 // Properly merge namespace-macros blocks in CompactNamespaces mode 2316 Style.NamespaceIndentation = FormatStyle::NI_None; 2317 Style.CompactNamespaces = true; 2318 verifyFormat("TESTSUITE(A) { TESTSUITE(B) {\n" 2319 "}} // TESTSUITE(A::B)", 2320 Style); 2321 2322 EXPECT_EQ("TESTSUITE(out) { TESTSUITE(in) {\n" 2323 "}} // TESTSUITE(out::in)", 2324 format("TESTSUITE(out) {\n" 2325 "TESTSUITE(in) {\n" 2326 "} // TESTSUITE(in)\n" 2327 "} // TESTSUITE(out)", 2328 Style)); 2329 2330 EXPECT_EQ("TESTSUITE(out) { TESTSUITE(in) {\n" 2331 "}} // TESTSUITE(out::in)", 2332 format("TESTSUITE(out) {\n" 2333 "TESTSUITE(in) {\n" 2334 "} // TESTSUITE(in)\n" 2335 "} // TESTSUITE(out)", 2336 Style)); 2337 2338 // Do not merge different namespaces/macros 2339 EXPECT_EQ("namespace out {\n" 2340 "TESTSUITE(in) {\n" 2341 "} // TESTSUITE(in)\n" 2342 "} // namespace out", 2343 format("namespace out {\n" 2344 "TESTSUITE(in) {\n" 2345 "} // TESTSUITE(in)\n" 2346 "} // namespace out", 2347 Style)); 2348 EXPECT_EQ("TESTSUITE(out) {\n" 2349 "namespace in {\n" 2350 "} // namespace in\n" 2351 "} // TESTSUITE(out)", 2352 format("TESTSUITE(out) {\n" 2353 "namespace in {\n" 2354 "} // namespace in\n" 2355 "} // TESTSUITE(out)", 2356 Style)); 2357 Style.NamespaceMacros.push_back("FOOBAR"); 2358 EXPECT_EQ("TESTSUITE(out) {\n" 2359 "FOOBAR(in) {\n" 2360 "} // FOOBAR(in)\n" 2361 "} // TESTSUITE(out)", 2362 format("TESTSUITE(out) {\n" 2363 "FOOBAR(in) {\n" 2364 "} // FOOBAR(in)\n" 2365 "} // TESTSUITE(out)", 2366 Style)); 2367 } 2368 2369 TEST_F(FormatTest, FormatsCompactNamespaces) { 2370 FormatStyle Style = getLLVMStyle(); 2371 Style.CompactNamespaces = true; 2372 Style.NamespaceMacros.push_back("TESTSUITE"); 2373 2374 verifyFormat("namespace A { namespace B {\n" 2375 "}} // namespace A::B", 2376 Style); 2377 2378 EXPECT_EQ("namespace out { namespace in {\n" 2379 "}} // namespace out::in", 2380 format("namespace out {\n" 2381 "namespace in {\n" 2382 "} // namespace in\n" 2383 "} // namespace out", 2384 Style)); 2385 2386 // Only namespaces which have both consecutive opening and end get compacted 2387 EXPECT_EQ("namespace out {\n" 2388 "namespace in1 {\n" 2389 "} // namespace in1\n" 2390 "namespace in2 {\n" 2391 "} // namespace in2\n" 2392 "} // namespace out", 2393 format("namespace out {\n" 2394 "namespace in1 {\n" 2395 "} // namespace in1\n" 2396 "namespace in2 {\n" 2397 "} // namespace in2\n" 2398 "} // namespace out", 2399 Style)); 2400 2401 EXPECT_EQ("namespace out {\n" 2402 "int i;\n" 2403 "namespace in {\n" 2404 "int j;\n" 2405 "} // namespace in\n" 2406 "int k;\n" 2407 "} // namespace out", 2408 format("namespace out { int i;\n" 2409 "namespace in { int j; } // namespace in\n" 2410 "int k; } // namespace out", 2411 Style)); 2412 2413 EXPECT_EQ("namespace A { namespace B { namespace C {\n" 2414 "}}} // namespace A::B::C\n", 2415 format("namespace A { namespace B {\n" 2416 "namespace C {\n" 2417 "}} // namespace B::C\n" 2418 "} // namespace A\n", 2419 Style)); 2420 2421 Style.ColumnLimit = 40; 2422 EXPECT_EQ("namespace aaaaaaaaaa {\n" 2423 "namespace bbbbbbbbbb {\n" 2424 "}} // namespace aaaaaaaaaa::bbbbbbbbbb", 2425 format("namespace aaaaaaaaaa {\n" 2426 "namespace bbbbbbbbbb {\n" 2427 "} // namespace bbbbbbbbbb\n" 2428 "} // namespace aaaaaaaaaa", 2429 Style)); 2430 2431 EXPECT_EQ("namespace aaaaaa { namespace bbbbbb {\n" 2432 "namespace cccccc {\n" 2433 "}}} // namespace aaaaaa::bbbbbb::cccccc", 2434 format("namespace aaaaaa {\n" 2435 "namespace bbbbbb {\n" 2436 "namespace cccccc {\n" 2437 "} // namespace cccccc\n" 2438 "} // namespace bbbbbb\n" 2439 "} // namespace aaaaaa", 2440 Style)); 2441 Style.ColumnLimit = 80; 2442 2443 // Extra semicolon after 'inner' closing brace prevents merging 2444 EXPECT_EQ("namespace out { namespace in {\n" 2445 "}; } // namespace out::in", 2446 format("namespace out {\n" 2447 "namespace in {\n" 2448 "}; // namespace in\n" 2449 "} // namespace out", 2450 Style)); 2451 2452 // Extra semicolon after 'outer' closing brace is conserved 2453 EXPECT_EQ("namespace out { namespace in {\n" 2454 "}}; // namespace out::in", 2455 format("namespace out {\n" 2456 "namespace in {\n" 2457 "} // namespace in\n" 2458 "}; // namespace out", 2459 Style)); 2460 2461 Style.NamespaceIndentation = FormatStyle::NI_All; 2462 EXPECT_EQ("namespace out { namespace in {\n" 2463 " int i;\n" 2464 "}} // namespace out::in", 2465 format("namespace out {\n" 2466 "namespace in {\n" 2467 "int i;\n" 2468 "} // namespace in\n" 2469 "} // namespace out", 2470 Style)); 2471 EXPECT_EQ("namespace out { namespace mid {\n" 2472 " namespace in {\n" 2473 " int j;\n" 2474 " } // namespace in\n" 2475 " int k;\n" 2476 "}} // namespace out::mid", 2477 format("namespace out { namespace mid {\n" 2478 "namespace in { int j; } // namespace in\n" 2479 "int k; }} // namespace out::mid", 2480 Style)); 2481 2482 Style.NamespaceIndentation = FormatStyle::NI_Inner; 2483 EXPECT_EQ("namespace out { namespace in {\n" 2484 " int i;\n" 2485 "}} // namespace out::in", 2486 format("namespace out {\n" 2487 "namespace in {\n" 2488 "int i;\n" 2489 "} // namespace in\n" 2490 "} // namespace out", 2491 Style)); 2492 EXPECT_EQ("namespace out { namespace mid { namespace in {\n" 2493 " int i;\n" 2494 "}}} // namespace out::mid::in", 2495 format("namespace out {\n" 2496 "namespace mid {\n" 2497 "namespace in {\n" 2498 "int i;\n" 2499 "} // namespace in\n" 2500 "} // namespace mid\n" 2501 "} // namespace out", 2502 Style)); 2503 } 2504 2505 TEST_F(FormatTest, FormatsExternC) { 2506 verifyFormat("extern \"C\" {\nint a;"); 2507 verifyFormat("extern \"C\" {}"); 2508 verifyFormat("extern \"C\" {\n" 2509 "int foo();\n" 2510 "}"); 2511 verifyFormat("extern \"C\" int foo() {}"); 2512 verifyFormat("extern \"C\" int foo();"); 2513 verifyFormat("extern \"C\" int foo() {\n" 2514 " int i = 42;\n" 2515 " return i;\n" 2516 "}"); 2517 2518 FormatStyle Style = getLLVMStyle(); 2519 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 2520 Style.BraceWrapping.AfterFunction = true; 2521 verifyFormat("extern \"C\" int foo() {}", Style); 2522 verifyFormat("extern \"C\" int foo();", Style); 2523 verifyFormat("extern \"C\" int foo()\n" 2524 "{\n" 2525 " int i = 42;\n" 2526 " return i;\n" 2527 "}", 2528 Style); 2529 2530 Style.BraceWrapping.AfterExternBlock = true; 2531 Style.BraceWrapping.SplitEmptyRecord = false; 2532 verifyFormat("extern \"C\"\n" 2533 "{}", 2534 Style); 2535 verifyFormat("extern \"C\"\n" 2536 "{\n" 2537 " int foo();\n" 2538 "}", 2539 Style); 2540 } 2541 2542 TEST_F(FormatTest, FormatsInlineASM) { 2543 verifyFormat("asm(\"xyz\" : \"=a\"(a), \"=d\"(b) : \"a\"(data));"); 2544 verifyFormat("asm(\"nop\" ::: \"memory\");"); 2545 verifyFormat( 2546 "asm(\"movq\\t%%rbx, %%rsi\\n\\t\"\n" 2547 " \"cpuid\\n\\t\"\n" 2548 " \"xchgq\\t%%rbx, %%rsi\\n\\t\"\n" 2549 " : \"=a\"(*rEAX), \"=S\"(*rEBX), \"=c\"(*rECX), \"=d\"(*rEDX)\n" 2550 " : \"a\"(value));"); 2551 EXPECT_EQ( 2552 "void NS_InvokeByIndex(void *that, unsigned int methodIndex) {\n" 2553 " __asm {\n" 2554 " mov edx,[that] // vtable in edx\n" 2555 " mov eax,methodIndex\n" 2556 " call [edx][eax*4] // stdcall\n" 2557 " }\n" 2558 "}", 2559 format("void NS_InvokeByIndex(void *that, unsigned int methodIndex) {\n" 2560 " __asm {\n" 2561 " mov edx,[that] // vtable in edx\n" 2562 " mov eax,methodIndex\n" 2563 " call [edx][eax*4] // stdcall\n" 2564 " }\n" 2565 "}")); 2566 EXPECT_EQ("_asm {\n" 2567 " xor eax, eax;\n" 2568 " cpuid;\n" 2569 "}", 2570 format("_asm {\n" 2571 " xor eax, eax;\n" 2572 " cpuid;\n" 2573 "}")); 2574 verifyFormat("void function() {\n" 2575 " // comment\n" 2576 " asm(\"\");\n" 2577 "}"); 2578 EXPECT_EQ("__asm {\n" 2579 "}\n" 2580 "int i;", 2581 format("__asm {\n" 2582 "}\n" 2583 "int i;")); 2584 } 2585 2586 TEST_F(FormatTest, FormatTryCatch) { 2587 verifyFormat("try {\n" 2588 " throw a * b;\n" 2589 "} catch (int a) {\n" 2590 " // Do nothing.\n" 2591 "} catch (...) {\n" 2592 " exit(42);\n" 2593 "}"); 2594 2595 // Function-level try statements. 2596 verifyFormat("int f() try { return 4; } catch (...) {\n" 2597 " return 5;\n" 2598 "}"); 2599 verifyFormat("class A {\n" 2600 " int a;\n" 2601 " A() try : a(0) {\n" 2602 " } catch (...) {\n" 2603 " throw;\n" 2604 " }\n" 2605 "};\n"); 2606 2607 // Incomplete try-catch blocks. 2608 verifyIncompleteFormat("try {} catch ("); 2609 } 2610 2611 TEST_F(FormatTest, FormatSEHTryCatch) { 2612 verifyFormat("__try {\n" 2613 " int a = b * c;\n" 2614 "} __except (EXCEPTION_EXECUTE_HANDLER) {\n" 2615 " // Do nothing.\n" 2616 "}"); 2617 2618 verifyFormat("__try {\n" 2619 " int a = b * c;\n" 2620 "} __finally {\n" 2621 " // Do nothing.\n" 2622 "}"); 2623 2624 verifyFormat("DEBUG({\n" 2625 " __try {\n" 2626 " } __finally {\n" 2627 " }\n" 2628 "});\n"); 2629 } 2630 2631 TEST_F(FormatTest, IncompleteTryCatchBlocks) { 2632 verifyFormat("try {\n" 2633 " f();\n" 2634 "} catch {\n" 2635 " g();\n" 2636 "}"); 2637 verifyFormat("try {\n" 2638 " f();\n" 2639 "} catch (A a) MACRO(x) {\n" 2640 " g();\n" 2641 "} catch (B b) MACRO(x) {\n" 2642 " g();\n" 2643 "}"); 2644 } 2645 2646 TEST_F(FormatTest, FormatTryCatchBraceStyles) { 2647 FormatStyle Style = getLLVMStyle(); 2648 for (auto BraceStyle : {FormatStyle::BS_Attach, FormatStyle::BS_Mozilla, 2649 FormatStyle::BS_WebKit}) { 2650 Style.BreakBeforeBraces = BraceStyle; 2651 verifyFormat("try {\n" 2652 " // something\n" 2653 "} catch (...) {\n" 2654 " // something\n" 2655 "}", 2656 Style); 2657 } 2658 Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup; 2659 verifyFormat("try {\n" 2660 " // something\n" 2661 "}\n" 2662 "catch (...) {\n" 2663 " // something\n" 2664 "}", 2665 Style); 2666 verifyFormat("__try {\n" 2667 " // something\n" 2668 "}\n" 2669 "__finally {\n" 2670 " // something\n" 2671 "}", 2672 Style); 2673 verifyFormat("@try {\n" 2674 " // something\n" 2675 "}\n" 2676 "@finally {\n" 2677 " // something\n" 2678 "}", 2679 Style); 2680 Style.BreakBeforeBraces = FormatStyle::BS_Allman; 2681 verifyFormat("try\n" 2682 "{\n" 2683 " // something\n" 2684 "}\n" 2685 "catch (...)\n" 2686 "{\n" 2687 " // something\n" 2688 "}", 2689 Style); 2690 Style.BreakBeforeBraces = FormatStyle::BS_Whitesmiths; 2691 verifyFormat("try\n" 2692 " {\n" 2693 " // something white\n" 2694 " }\n" 2695 "catch (...)\n" 2696 " {\n" 2697 " // something white\n" 2698 " }", 2699 Style); 2700 Style.BreakBeforeBraces = FormatStyle::BS_GNU; 2701 verifyFormat("try\n" 2702 " {\n" 2703 " // something\n" 2704 " }\n" 2705 "catch (...)\n" 2706 " {\n" 2707 " // something\n" 2708 " }", 2709 Style); 2710 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 2711 Style.BraceWrapping.BeforeCatch = true; 2712 verifyFormat("try {\n" 2713 " // something\n" 2714 "}\n" 2715 "catch (...) {\n" 2716 " // something\n" 2717 "}", 2718 Style); 2719 } 2720 2721 TEST_F(FormatTest, StaticInitializers) { 2722 verifyFormat("static SomeClass SC = {1, 'a'};"); 2723 2724 verifyFormat("static SomeClass WithALoooooooooooooooooooongName = {\n" 2725 " 100000000, " 2726 "\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"};"); 2727 2728 // Here, everything other than the "}" would fit on a line. 2729 verifyFormat("static int LooooooooooooooooooooooooongVariable[1] = {\n" 2730 " 10000000000000000000000000};"); 2731 EXPECT_EQ("S s = {a,\n" 2732 "\n" 2733 " b};", 2734 format("S s = {\n" 2735 " a,\n" 2736 "\n" 2737 " b\n" 2738 "};")); 2739 2740 // FIXME: This would fit into the column limit if we'd fit "{ {" on the first 2741 // line. However, the formatting looks a bit off and this probably doesn't 2742 // happen often in practice. 2743 verifyFormat("static int Variable[1] = {\n" 2744 " {1000000000000000000000000000000000000}};", 2745 getLLVMStyleWithColumns(40)); 2746 } 2747 2748 TEST_F(FormatTest, DesignatedInitializers) { 2749 verifyFormat("const struct A a = {.a = 1, .b = 2};"); 2750 verifyFormat("const struct A a = {.aaaaaaaaaa = 1,\n" 2751 " .bbbbbbbbbb = 2,\n" 2752 " .cccccccccc = 3,\n" 2753 " .dddddddddd = 4,\n" 2754 " .eeeeeeeeee = 5};"); 2755 verifyFormat("const struct Aaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaa = {\n" 2756 " .aaaaaaaaaaaaaaaaaaaaaaaaaaa = 1,\n" 2757 " .bbbbbbbbbbbbbbbbbbbbbbbbbbb = 2,\n" 2758 " .ccccccccccccccccccccccccccc = 3,\n" 2759 " .ddddddddddddddddddddddddddd = 4,\n" 2760 " .eeeeeeeeeeeeeeeeeeeeeeeeeee = 5};"); 2761 2762 verifyGoogleFormat("const struct A a = {.a = 1, .b = 2};"); 2763 2764 verifyFormat("const struct A a = {[0] = 1, [1] = 2};"); 2765 verifyFormat("const struct A a = {[1] = aaaaaaaaaa,\n" 2766 " [2] = bbbbbbbbbb,\n" 2767 " [3] = cccccccccc,\n" 2768 " [4] = dddddddddd,\n" 2769 " [5] = eeeeeeeeee};"); 2770 verifyFormat("const struct Aaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaa = {\n" 2771 " [1] = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 2772 " [2] = bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb,\n" 2773 " [3] = cccccccccccccccccccccccccccccccccccccc,\n" 2774 " [4] = dddddddddddddddddddddddddddddddddddddd,\n" 2775 " [5] = eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee};"); 2776 } 2777 2778 TEST_F(FormatTest, NestedStaticInitializers) { 2779 verifyFormat("static A x = {{{}}};\n"); 2780 verifyFormat("static A x = {{{init1, init2, init3, init4},\n" 2781 " {init1, init2, init3, init4}}};", 2782 getLLVMStyleWithColumns(50)); 2783 2784 verifyFormat("somes Status::global_reps[3] = {\n" 2785 " {kGlobalRef, OK_CODE, NULL, NULL, NULL},\n" 2786 " {kGlobalRef, CANCELLED_CODE, NULL, NULL, NULL},\n" 2787 " {kGlobalRef, UNKNOWN_CODE, NULL, NULL, NULL}};", 2788 getLLVMStyleWithColumns(60)); 2789 verifyGoogleFormat("SomeType Status::global_reps[3] = {\n" 2790 " {kGlobalRef, OK_CODE, NULL, NULL, NULL},\n" 2791 " {kGlobalRef, CANCELLED_CODE, NULL, NULL, NULL},\n" 2792 " {kGlobalRef, UNKNOWN_CODE, NULL, NULL, NULL}};"); 2793 verifyFormat("CGRect cg_rect = {{rect.fLeft, rect.fTop},\n" 2794 " {rect.fRight - rect.fLeft, rect.fBottom - " 2795 "rect.fTop}};"); 2796 2797 verifyFormat( 2798 "SomeArrayOfSomeType a = {\n" 2799 " {{1, 2, 3},\n" 2800 " {1, 2, 3},\n" 2801 " {111111111111111111111111111111, 222222222222222222222222222222,\n" 2802 " 333333333333333333333333333333},\n" 2803 " {1, 2, 3},\n" 2804 " {1, 2, 3}}};"); 2805 verifyFormat( 2806 "SomeArrayOfSomeType a = {\n" 2807 " {{1, 2, 3}},\n" 2808 " {{1, 2, 3}},\n" 2809 " {{111111111111111111111111111111, 222222222222222222222222222222,\n" 2810 " 333333333333333333333333333333}},\n" 2811 " {{1, 2, 3}},\n" 2812 " {{1, 2, 3}}};"); 2813 2814 verifyFormat("struct {\n" 2815 " unsigned bit;\n" 2816 " const char *const name;\n" 2817 "} kBitsToOs[] = {{kOsMac, \"Mac\"},\n" 2818 " {kOsWin, \"Windows\"},\n" 2819 " {kOsLinux, \"Linux\"},\n" 2820 " {kOsCrOS, \"Chrome OS\"}};"); 2821 verifyFormat("struct {\n" 2822 " unsigned bit;\n" 2823 " const char *const name;\n" 2824 "} kBitsToOs[] = {\n" 2825 " {kOsMac, \"Mac\"},\n" 2826 " {kOsWin, \"Windows\"},\n" 2827 " {kOsLinux, \"Linux\"},\n" 2828 " {kOsCrOS, \"Chrome OS\"},\n" 2829 "};"); 2830 } 2831 2832 TEST_F(FormatTest, FormatsSmallMacroDefinitionsInSingleLine) { 2833 verifyFormat("#define ALooooooooooooooooooooooooooooooooooooooongMacro(" 2834 " \\\n" 2835 " aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)"); 2836 } 2837 2838 TEST_F(FormatTest, DoesNotBreakPureVirtualFunctionDefinition) { 2839 verifyFormat("virtual void write(ELFWriter *writerrr,\n" 2840 " OwningPtr<FileOutputBuffer> &buffer) = 0;"); 2841 2842 // Do break defaulted and deleted functions. 2843 verifyFormat("virtual void ~Deeeeeeeestructor() =\n" 2844 " default;", 2845 getLLVMStyleWithColumns(40)); 2846 verifyFormat("virtual void ~Deeeeeeeestructor() =\n" 2847 " delete;", 2848 getLLVMStyleWithColumns(40)); 2849 } 2850 2851 TEST_F(FormatTest, BreaksStringLiteralsOnlyInDefine) { 2852 verifyFormat("# 1111 \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/aaaaaaaa.cpp\" 2 3", 2853 getLLVMStyleWithColumns(40)); 2854 verifyFormat("#line 11111 \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/aaaaaaaa.cpp\"", 2855 getLLVMStyleWithColumns(40)); 2856 EXPECT_EQ("#define Q \\\n" 2857 " \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/\" \\\n" 2858 " \"aaaaaaaa.cpp\"", 2859 format("#define Q \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/aaaaaaaa.cpp\"", 2860 getLLVMStyleWithColumns(40))); 2861 } 2862 2863 TEST_F(FormatTest, UnderstandsLinePPDirective) { 2864 EXPECT_EQ("# 123 \"A string literal\"", 2865 format(" # 123 \"A string literal\"")); 2866 } 2867 2868 TEST_F(FormatTest, LayoutUnknownPPDirective) { 2869 EXPECT_EQ("#;", format("#;")); 2870 verifyFormat("#\n;\n;\n;"); 2871 } 2872 2873 TEST_F(FormatTest, UnescapedEndOfLineEndsPPDirective) { 2874 EXPECT_EQ("#line 42 \"test\"\n", 2875 format("# \\\n line \\\n 42 \\\n \"test\"\n")); 2876 EXPECT_EQ("#define A B\n", format("# \\\n define \\\n A \\\n B\n", 2877 getLLVMStyleWithColumns(12))); 2878 } 2879 2880 TEST_F(FormatTest, EndOfFileEndsPPDirective) { 2881 EXPECT_EQ("#line 42 \"test\"", 2882 format("# \\\n line \\\n 42 \\\n \"test\"")); 2883 EXPECT_EQ("#define A B", format("# \\\n define \\\n A \\\n B")); 2884 } 2885 2886 TEST_F(FormatTest, DoesntRemoveUnknownTokens) { 2887 verifyFormat("#define A \\x20"); 2888 verifyFormat("#define A \\ x20"); 2889 EXPECT_EQ("#define A \\ x20", format("#define A \\ x20")); 2890 verifyFormat("#define A ''"); 2891 verifyFormat("#define A ''qqq"); 2892 verifyFormat("#define A `qqq"); 2893 verifyFormat("f(\"aaaa, bbbb, \"\\\"ccccc\\\"\");"); 2894 EXPECT_EQ("const char *c = STRINGIFY(\n" 2895 "\\na : b);", 2896 format("const char * c = STRINGIFY(\n" 2897 "\\na : b);")); 2898 2899 verifyFormat("a\r\\"); 2900 verifyFormat("a\v\\"); 2901 verifyFormat("a\f\\"); 2902 } 2903 2904 TEST_F(FormatTest, IndentsPPDirectiveInReducedSpace) { 2905 verifyFormat("#define A(BB)", getLLVMStyleWithColumns(13)); 2906 verifyFormat("#define A( \\\n BB)", getLLVMStyleWithColumns(12)); 2907 verifyFormat("#define A( \\\n A, B)", getLLVMStyleWithColumns(12)); 2908 // FIXME: We never break before the macro name. 2909 verifyFormat("#define AA( \\\n B)", getLLVMStyleWithColumns(12)); 2910 2911 verifyFormat("#define A A\n#define A A"); 2912 verifyFormat("#define A(X) A\n#define A A"); 2913 2914 verifyFormat("#define Something Other", getLLVMStyleWithColumns(23)); 2915 verifyFormat("#define Something \\\n Other", getLLVMStyleWithColumns(22)); 2916 } 2917 2918 TEST_F(FormatTest, HandlePreprocessorDirectiveContext) { 2919 EXPECT_EQ("// somecomment\n" 2920 "#include \"a.h\"\n" 2921 "#define A( \\\n" 2922 " A, B)\n" 2923 "#include \"b.h\"\n" 2924 "// somecomment\n", 2925 format(" // somecomment\n" 2926 " #include \"a.h\"\n" 2927 "#define A(A,\\\n" 2928 " B)\n" 2929 " #include \"b.h\"\n" 2930 " // somecomment\n", 2931 getLLVMStyleWithColumns(13))); 2932 } 2933 2934 TEST_F(FormatTest, LayoutSingleHash) { EXPECT_EQ("#\na;", format("#\na;")); } 2935 2936 TEST_F(FormatTest, LayoutCodeInMacroDefinitions) { 2937 EXPECT_EQ("#define A \\\n" 2938 " c; \\\n" 2939 " e;\n" 2940 "f;", 2941 format("#define A c; e;\n" 2942 "f;", 2943 getLLVMStyleWithColumns(14))); 2944 } 2945 2946 TEST_F(FormatTest, LayoutRemainingTokens) { EXPECT_EQ("{}", format("{}")); } 2947 2948 TEST_F(FormatTest, MacroDefinitionInsideStatement) { 2949 EXPECT_EQ("int x,\n" 2950 "#define A\n" 2951 " y;", 2952 format("int x,\n#define A\ny;")); 2953 } 2954 2955 TEST_F(FormatTest, HashInMacroDefinition) { 2956 EXPECT_EQ("#define A(c) L#c", format("#define A(c) L#c", getLLVMStyle())); 2957 verifyFormat("#define A \\\n b #c;", getLLVMStyleWithColumns(11)); 2958 verifyFormat("#define A \\\n" 2959 " { \\\n" 2960 " f(#c); \\\n" 2961 " }", 2962 getLLVMStyleWithColumns(11)); 2963 2964 verifyFormat("#define A(X) \\\n" 2965 " void function##X()", 2966 getLLVMStyleWithColumns(22)); 2967 2968 verifyFormat("#define A(a, b, c) \\\n" 2969 " void a##b##c()", 2970 getLLVMStyleWithColumns(22)); 2971 2972 verifyFormat("#define A void # ## #", getLLVMStyleWithColumns(22)); 2973 } 2974 2975 TEST_F(FormatTest, RespectWhitespaceInMacroDefinitions) { 2976 EXPECT_EQ("#define A (x)", format("#define A (x)")); 2977 EXPECT_EQ("#define A(x)", format("#define A(x)")); 2978 2979 FormatStyle Style = getLLVMStyle(); 2980 Style.SpaceBeforeParens = FormatStyle::SBPO_Never; 2981 verifyFormat("#define true ((foo)1)", Style); 2982 Style.SpaceBeforeParens = FormatStyle::SBPO_Always; 2983 verifyFormat("#define false((foo)0)", Style); 2984 } 2985 2986 TEST_F(FormatTest, EmptyLinesInMacroDefinitions) { 2987 EXPECT_EQ("#define A b;", format("#define A \\\n" 2988 " \\\n" 2989 " b;", 2990 getLLVMStyleWithColumns(25))); 2991 EXPECT_EQ("#define A \\\n" 2992 " \\\n" 2993 " a; \\\n" 2994 " b;", 2995 format("#define A \\\n" 2996 " \\\n" 2997 " a; \\\n" 2998 " b;", 2999 getLLVMStyleWithColumns(11))); 3000 EXPECT_EQ("#define A \\\n" 3001 " a; \\\n" 3002 " \\\n" 3003 " b;", 3004 format("#define A \\\n" 3005 " a; \\\n" 3006 " \\\n" 3007 " b;", 3008 getLLVMStyleWithColumns(11))); 3009 } 3010 3011 TEST_F(FormatTest, MacroDefinitionsWithIncompleteCode) { 3012 verifyIncompleteFormat("#define A :"); 3013 verifyFormat("#define SOMECASES \\\n" 3014 " case 1: \\\n" 3015 " case 2\n", 3016 getLLVMStyleWithColumns(20)); 3017 verifyFormat("#define MACRO(a) \\\n" 3018 " if (a) \\\n" 3019 " f(); \\\n" 3020 " else \\\n" 3021 " g()", 3022 getLLVMStyleWithColumns(18)); 3023 verifyFormat("#define A template <typename T>"); 3024 verifyIncompleteFormat("#define STR(x) #x\n" 3025 "f(STR(this_is_a_string_literal{));"); 3026 verifyFormat("#pragma omp threadprivate( \\\n" 3027 " y)), // expected-warning", 3028 getLLVMStyleWithColumns(28)); 3029 verifyFormat("#d, = };"); 3030 verifyFormat("#if \"a"); 3031 verifyIncompleteFormat("({\n" 3032 "#define b \\\n" 3033 " } \\\n" 3034 " a\n" 3035 "a", 3036 getLLVMStyleWithColumns(15)); 3037 verifyFormat("#define A \\\n" 3038 " { \\\n" 3039 " {\n" 3040 "#define B \\\n" 3041 " } \\\n" 3042 " }", 3043 getLLVMStyleWithColumns(15)); 3044 verifyNoCrash("#if a\na(\n#else\n#endif\n{a"); 3045 verifyNoCrash("a={0,1\n#if a\n#else\n;\n#endif\n}"); 3046 verifyNoCrash("#if a\na(\n#else\n#endif\n) a {a,b,c,d,f,g};"); 3047 verifyNoCrash("#ifdef A\n a(\n #else\n #endif\n) = []() { \n)}"); 3048 } 3049 3050 TEST_F(FormatTest, MacrosWithoutTrailingSemicolon) { 3051 verifyFormat("SOME_TYPE_NAME abc;"); // Gated on the newline. 3052 EXPECT_EQ("class A : public QObject {\n" 3053 " Q_OBJECT\n" 3054 "\n" 3055 " A() {}\n" 3056 "};", 3057 format("class A : public QObject {\n" 3058 " Q_OBJECT\n" 3059 "\n" 3060 " A() {\n}\n" 3061 "} ;")); 3062 EXPECT_EQ("MACRO\n" 3063 "/*static*/ int i;", 3064 format("MACRO\n" 3065 " /*static*/ int i;")); 3066 EXPECT_EQ("SOME_MACRO\n" 3067 "namespace {\n" 3068 "void f();\n" 3069 "} // namespace", 3070 format("SOME_MACRO\n" 3071 " namespace {\n" 3072 "void f( );\n" 3073 "} // namespace")); 3074 // Only if the identifier contains at least 5 characters. 3075 EXPECT_EQ("HTTP f();", format("HTTP\nf();")); 3076 EXPECT_EQ("MACRO\nf();", format("MACRO\nf();")); 3077 // Only if everything is upper case. 3078 EXPECT_EQ("class A : public QObject {\n" 3079 " Q_Object A() {}\n" 3080 "};", 3081 format("class A : public QObject {\n" 3082 " Q_Object\n" 3083 " A() {\n}\n" 3084 "} ;")); 3085 3086 // Only if the next line can actually start an unwrapped line. 3087 EXPECT_EQ("SOME_WEIRD_LOG_MACRO << SomeThing;", 3088 format("SOME_WEIRD_LOG_MACRO\n" 3089 "<< SomeThing;")); 3090 3091 verifyFormat("VISIT_GL_CALL(GenBuffers, void, (GLsizei n, GLuint* buffers), " 3092 "(n, buffers))\n", 3093 getChromiumStyle(FormatStyle::LK_Cpp)); 3094 3095 // See PR41483 3096 EXPECT_EQ("/**/ FOO(a)\n" 3097 "FOO(b)", 3098 format("/**/ FOO(a)\n" 3099 "FOO(b)")); 3100 } 3101 3102 TEST_F(FormatTest, MacroCallsWithoutTrailingSemicolon) { 3103 EXPECT_EQ("INITIALIZE_PASS_BEGIN(ScopDetection, \"polly-detect\")\n" 3104 "INITIALIZE_AG_DEPENDENCY(AliasAnalysis)\n" 3105 "INITIALIZE_PASS_DEPENDENCY(DominatorTree)\n" 3106 "class X {};\n" 3107 "INITIALIZE_PASS_END(ScopDetection, \"polly-detect\")\n" 3108 "int *createScopDetectionPass() { return 0; }", 3109 format(" INITIALIZE_PASS_BEGIN(ScopDetection, \"polly-detect\")\n" 3110 " INITIALIZE_AG_DEPENDENCY(AliasAnalysis)\n" 3111 " INITIALIZE_PASS_DEPENDENCY(DominatorTree)\n" 3112 " class X {};\n" 3113 " INITIALIZE_PASS_END(ScopDetection, \"polly-detect\")\n" 3114 " int *createScopDetectionPass() { return 0; }")); 3115 // FIXME: We could probably treat IPC_BEGIN_MESSAGE_MAP/IPC_END_MESSAGE_MAP as 3116 // braces, so that inner block is indented one level more. 3117 EXPECT_EQ("int q() {\n" 3118 " IPC_BEGIN_MESSAGE_MAP(WebKitTestController, message)\n" 3119 " IPC_MESSAGE_HANDLER(xxx, qqq)\n" 3120 " IPC_END_MESSAGE_MAP()\n" 3121 "}", 3122 format("int q() {\n" 3123 " IPC_BEGIN_MESSAGE_MAP(WebKitTestController, message)\n" 3124 " IPC_MESSAGE_HANDLER(xxx, qqq)\n" 3125 " IPC_END_MESSAGE_MAP()\n" 3126 "}")); 3127 3128 // Same inside macros. 3129 EXPECT_EQ("#define LIST(L) \\\n" 3130 " L(A) \\\n" 3131 " L(B) \\\n" 3132 " L(C)", 3133 format("#define LIST(L) \\\n" 3134 " L(A) \\\n" 3135 " L(B) \\\n" 3136 " L(C)", 3137 getGoogleStyle())); 3138 3139 // These must not be recognized as macros. 3140 EXPECT_EQ("int q() {\n" 3141 " f(x);\n" 3142 " f(x) {}\n" 3143 " f(x)->g();\n" 3144 " f(x)->*g();\n" 3145 " f(x).g();\n" 3146 " f(x) = x;\n" 3147 " f(x) += x;\n" 3148 " f(x) -= x;\n" 3149 " f(x) *= x;\n" 3150 " f(x) /= x;\n" 3151 " f(x) %= x;\n" 3152 " f(x) &= x;\n" 3153 " f(x) |= x;\n" 3154 " f(x) ^= x;\n" 3155 " f(x) >>= x;\n" 3156 " f(x) <<= x;\n" 3157 " f(x)[y].z();\n" 3158 " LOG(INFO) << x;\n" 3159 " ifstream(x) >> x;\n" 3160 "}\n", 3161 format("int q() {\n" 3162 " f(x)\n;\n" 3163 " f(x)\n {}\n" 3164 " f(x)\n->g();\n" 3165 " f(x)\n->*g();\n" 3166 " f(x)\n.g();\n" 3167 " f(x)\n = x;\n" 3168 " f(x)\n += x;\n" 3169 " f(x)\n -= x;\n" 3170 " f(x)\n *= x;\n" 3171 " f(x)\n /= x;\n" 3172 " f(x)\n %= x;\n" 3173 " f(x)\n &= x;\n" 3174 " f(x)\n |= x;\n" 3175 " f(x)\n ^= x;\n" 3176 " f(x)\n >>= x;\n" 3177 " f(x)\n <<= x;\n" 3178 " f(x)\n[y].z();\n" 3179 " LOG(INFO)\n << x;\n" 3180 " ifstream(x)\n >> x;\n" 3181 "}\n")); 3182 EXPECT_EQ("int q() {\n" 3183 " F(x)\n" 3184 " if (1) {\n" 3185 " }\n" 3186 " F(x)\n" 3187 " while (1) {\n" 3188 " }\n" 3189 " F(x)\n" 3190 " G(x);\n" 3191 " F(x)\n" 3192 " try {\n" 3193 " Q();\n" 3194 " } catch (...) {\n" 3195 " }\n" 3196 "}\n", 3197 format("int q() {\n" 3198 "F(x)\n" 3199 "if (1) {}\n" 3200 "F(x)\n" 3201 "while (1) {}\n" 3202 "F(x)\n" 3203 "G(x);\n" 3204 "F(x)\n" 3205 "try { Q(); } catch (...) {}\n" 3206 "}\n")); 3207 EXPECT_EQ("class A {\n" 3208 " A() : t(0) {}\n" 3209 " A(int i) noexcept() : {}\n" 3210 " A(X x)\n" // FIXME: function-level try blocks are broken. 3211 " try : t(0) {\n" 3212 " } catch (...) {\n" 3213 " }\n" 3214 "};", 3215 format("class A {\n" 3216 " A()\n : t(0) {}\n" 3217 " A(int i)\n noexcept() : {}\n" 3218 " A(X x)\n" 3219 " try : t(0) {} catch (...) {}\n" 3220 "};")); 3221 FormatStyle Style = getLLVMStyle(); 3222 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 3223 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always; 3224 Style.BraceWrapping.AfterFunction = true; 3225 EXPECT_EQ("void f()\n" 3226 "try\n" 3227 "{\n" 3228 "}", 3229 format("void f() try {\n" 3230 "}", 3231 Style)); 3232 EXPECT_EQ("class SomeClass {\n" 3233 "public:\n" 3234 " SomeClass() EXCLUSIVE_LOCK_FUNCTION(mu_);\n" 3235 "};", 3236 format("class SomeClass {\n" 3237 "public:\n" 3238 " SomeClass()\n" 3239 " EXCLUSIVE_LOCK_FUNCTION(mu_);\n" 3240 "};")); 3241 EXPECT_EQ("class SomeClass {\n" 3242 "public:\n" 3243 " SomeClass()\n" 3244 " EXCLUSIVE_LOCK_FUNCTION(mu_);\n" 3245 "};", 3246 format("class SomeClass {\n" 3247 "public:\n" 3248 " SomeClass()\n" 3249 " EXCLUSIVE_LOCK_FUNCTION(mu_);\n" 3250 "};", 3251 getLLVMStyleWithColumns(40))); 3252 3253 verifyFormat("MACRO(>)"); 3254 3255 // Some macros contain an implicit semicolon. 3256 Style = getLLVMStyle(); 3257 Style.StatementMacros.push_back("FOO"); 3258 verifyFormat("FOO(a) int b = 0;"); 3259 verifyFormat("FOO(a)\n" 3260 "int b = 0;", 3261 Style); 3262 verifyFormat("FOO(a);\n" 3263 "int b = 0;", 3264 Style); 3265 verifyFormat("FOO(argc, argv, \"4.0.2\")\n" 3266 "int b = 0;", 3267 Style); 3268 verifyFormat("FOO()\n" 3269 "int b = 0;", 3270 Style); 3271 verifyFormat("FOO\n" 3272 "int b = 0;", 3273 Style); 3274 verifyFormat("void f() {\n" 3275 " FOO(a)\n" 3276 " return a;\n" 3277 "}", 3278 Style); 3279 verifyFormat("FOO(a)\n" 3280 "FOO(b)", 3281 Style); 3282 verifyFormat("int a = 0;\n" 3283 "FOO(b)\n" 3284 "int c = 0;", 3285 Style); 3286 verifyFormat("int a = 0;\n" 3287 "int x = FOO(a)\n" 3288 "int b = 0;", 3289 Style); 3290 verifyFormat("void foo(int a) { FOO(a) }\n" 3291 "uint32_t bar() {}", 3292 Style); 3293 } 3294 3295 TEST_F(FormatTest, LayoutMacroDefinitionsStatementsSpanningBlocks) { 3296 verifyFormat("#define A \\\n" 3297 " f({ \\\n" 3298 " g(); \\\n" 3299 " });", 3300 getLLVMStyleWithColumns(11)); 3301 } 3302 3303 TEST_F(FormatTest, IndentPreprocessorDirectives) { 3304 FormatStyle Style = getLLVMStyle(); 3305 Style.IndentPPDirectives = FormatStyle::PPDIS_None; 3306 Style.ColumnLimit = 40; 3307 verifyFormat("#ifdef _WIN32\n" 3308 "#define A 0\n" 3309 "#ifdef VAR2\n" 3310 "#define B 1\n" 3311 "#include <someheader.h>\n" 3312 "#define MACRO \\\n" 3313 " some_very_long_func_aaaaaaaaaa();\n" 3314 "#endif\n" 3315 "#else\n" 3316 "#define A 1\n" 3317 "#endif", 3318 Style); 3319 Style.IndentPPDirectives = FormatStyle::PPDIS_AfterHash; 3320 verifyFormat("#ifdef _WIN32\n" 3321 "# define A 0\n" 3322 "# ifdef VAR2\n" 3323 "# define B 1\n" 3324 "# include <someheader.h>\n" 3325 "# define MACRO \\\n" 3326 " some_very_long_func_aaaaaaaaaa();\n" 3327 "# endif\n" 3328 "#else\n" 3329 "# define A 1\n" 3330 "#endif", 3331 Style); 3332 verifyFormat("#if A\n" 3333 "# define MACRO \\\n" 3334 " void a(int x) { \\\n" 3335 " b(); \\\n" 3336 " c(); \\\n" 3337 " d(); \\\n" 3338 " e(); \\\n" 3339 " f(); \\\n" 3340 " }\n" 3341 "#endif", 3342 Style); 3343 // Comments before include guard. 3344 verifyFormat("// file comment\n" 3345 "// file comment\n" 3346 "#ifndef HEADER_H\n" 3347 "#define HEADER_H\n" 3348 "code();\n" 3349 "#endif", 3350 Style); 3351 // Test with include guards. 3352 verifyFormat("#ifndef HEADER_H\n" 3353 "#define HEADER_H\n" 3354 "code();\n" 3355 "#endif", 3356 Style); 3357 // Include guards must have a #define with the same variable immediately 3358 // after #ifndef. 3359 verifyFormat("#ifndef NOT_GUARD\n" 3360 "# define FOO\n" 3361 "code();\n" 3362 "#endif", 3363 Style); 3364 3365 // Include guards must cover the entire file. 3366 verifyFormat("code();\n" 3367 "code();\n" 3368 "#ifndef NOT_GUARD\n" 3369 "# define NOT_GUARD\n" 3370 "code();\n" 3371 "#endif", 3372 Style); 3373 verifyFormat("#ifndef NOT_GUARD\n" 3374 "# define NOT_GUARD\n" 3375 "code();\n" 3376 "#endif\n" 3377 "code();", 3378 Style); 3379 // Test with trailing blank lines. 3380 verifyFormat("#ifndef HEADER_H\n" 3381 "#define HEADER_H\n" 3382 "code();\n" 3383 "#endif\n", 3384 Style); 3385 // Include guards don't have #else. 3386 verifyFormat("#ifndef NOT_GUARD\n" 3387 "# define NOT_GUARD\n" 3388 "code();\n" 3389 "#else\n" 3390 "#endif", 3391 Style); 3392 verifyFormat("#ifndef NOT_GUARD\n" 3393 "# define NOT_GUARD\n" 3394 "code();\n" 3395 "#elif FOO\n" 3396 "#endif", 3397 Style); 3398 // Non-identifier #define after potential include guard. 3399 verifyFormat("#ifndef FOO\n" 3400 "# define 1\n" 3401 "#endif\n", 3402 Style); 3403 // #if closes past last non-preprocessor line. 3404 verifyFormat("#ifndef FOO\n" 3405 "#define FOO\n" 3406 "#if 1\n" 3407 "int i;\n" 3408 "# define A 0\n" 3409 "#endif\n" 3410 "#endif\n", 3411 Style); 3412 // Don't crash if there is an #elif directive without a condition. 3413 verifyFormat("#if 1\n" 3414 "int x;\n" 3415 "#elif\n" 3416 "int y;\n" 3417 "#else\n" 3418 "int z;\n" 3419 "#endif", 3420 Style); 3421 // FIXME: This doesn't handle the case where there's code between the 3422 // #ifndef and #define but all other conditions hold. This is because when 3423 // the #define line is parsed, UnwrappedLineParser::Lines doesn't hold the 3424 // previous code line yet, so we can't detect it. 3425 EXPECT_EQ("#ifndef NOT_GUARD\n" 3426 "code();\n" 3427 "#define NOT_GUARD\n" 3428 "code();\n" 3429 "#endif", 3430 format("#ifndef NOT_GUARD\n" 3431 "code();\n" 3432 "# define NOT_GUARD\n" 3433 "code();\n" 3434 "#endif", 3435 Style)); 3436 // FIXME: This doesn't handle cases where legitimate preprocessor lines may 3437 // be outside an include guard. Examples are #pragma once and 3438 // #pragma GCC diagnostic, or anything else that does not change the meaning 3439 // of the file if it's included multiple times. 3440 EXPECT_EQ("#ifdef WIN32\n" 3441 "# pragma once\n" 3442 "#endif\n" 3443 "#ifndef HEADER_H\n" 3444 "# define HEADER_H\n" 3445 "code();\n" 3446 "#endif", 3447 format("#ifdef WIN32\n" 3448 "# pragma once\n" 3449 "#endif\n" 3450 "#ifndef HEADER_H\n" 3451 "#define HEADER_H\n" 3452 "code();\n" 3453 "#endif", 3454 Style)); 3455 // FIXME: This does not detect when there is a single non-preprocessor line 3456 // in front of an include-guard-like structure where other conditions hold 3457 // because ScopedLineState hides the line. 3458 EXPECT_EQ("code();\n" 3459 "#ifndef HEADER_H\n" 3460 "#define HEADER_H\n" 3461 "code();\n" 3462 "#endif", 3463 format("code();\n" 3464 "#ifndef HEADER_H\n" 3465 "# define HEADER_H\n" 3466 "code();\n" 3467 "#endif", 3468 Style)); 3469 // Keep comments aligned with #, otherwise indent comments normally. These 3470 // tests cannot use verifyFormat because messUp manipulates leading 3471 // whitespace. 3472 { 3473 const char *Expected = "" 3474 "void f() {\n" 3475 "#if 1\n" 3476 "// Preprocessor aligned.\n" 3477 "# define A 0\n" 3478 " // Code. Separated by blank line.\n" 3479 "\n" 3480 "# define B 0\n" 3481 " // Code. Not aligned with #\n" 3482 "# define C 0\n" 3483 "#endif"; 3484 const char *ToFormat = "" 3485 "void f() {\n" 3486 "#if 1\n" 3487 "// Preprocessor aligned.\n" 3488 "# define A 0\n" 3489 "// Code. Separated by blank line.\n" 3490 "\n" 3491 "# define B 0\n" 3492 " // Code. Not aligned with #\n" 3493 "# define C 0\n" 3494 "#endif"; 3495 EXPECT_EQ(Expected, format(ToFormat, Style)); 3496 EXPECT_EQ(Expected, format(Expected, Style)); 3497 } 3498 // Keep block quotes aligned. 3499 { 3500 const char *Expected = "" 3501 "void f() {\n" 3502 "#if 1\n" 3503 "/* Preprocessor aligned. */\n" 3504 "# define A 0\n" 3505 " /* Code. Separated by blank line. */\n" 3506 "\n" 3507 "# define B 0\n" 3508 " /* Code. Not aligned with # */\n" 3509 "# define C 0\n" 3510 "#endif"; 3511 const char *ToFormat = "" 3512 "void f() {\n" 3513 "#if 1\n" 3514 "/* Preprocessor aligned. */\n" 3515 "# define A 0\n" 3516 "/* Code. Separated by blank line. */\n" 3517 "\n" 3518 "# define B 0\n" 3519 " /* Code. Not aligned with # */\n" 3520 "# define C 0\n" 3521 "#endif"; 3522 EXPECT_EQ(Expected, format(ToFormat, Style)); 3523 EXPECT_EQ(Expected, format(Expected, Style)); 3524 } 3525 // Keep comments aligned with un-indented directives. 3526 { 3527 const char *Expected = "" 3528 "void f() {\n" 3529 "// Preprocessor aligned.\n" 3530 "#define A 0\n" 3531 " // Code. Separated by blank line.\n" 3532 "\n" 3533 "#define B 0\n" 3534 " // Code. Not aligned with #\n" 3535 "#define C 0\n"; 3536 const char *ToFormat = "" 3537 "void f() {\n" 3538 "// Preprocessor aligned.\n" 3539 "#define A 0\n" 3540 "// Code. Separated by blank line.\n" 3541 "\n" 3542 "#define B 0\n" 3543 " // Code. Not aligned with #\n" 3544 "#define C 0\n"; 3545 EXPECT_EQ(Expected, format(ToFormat, Style)); 3546 EXPECT_EQ(Expected, format(Expected, Style)); 3547 } 3548 // Test AfterHash with tabs. 3549 { 3550 FormatStyle Tabbed = Style; 3551 Tabbed.UseTab = FormatStyle::UT_Always; 3552 Tabbed.IndentWidth = 8; 3553 Tabbed.TabWidth = 8; 3554 verifyFormat("#ifdef _WIN32\n" 3555 "#\tdefine A 0\n" 3556 "#\tifdef VAR2\n" 3557 "#\t\tdefine B 1\n" 3558 "#\t\tinclude <someheader.h>\n" 3559 "#\t\tdefine MACRO \\\n" 3560 "\t\t\tsome_very_long_func_aaaaaaaaaa();\n" 3561 "#\tendif\n" 3562 "#else\n" 3563 "#\tdefine A 1\n" 3564 "#endif", 3565 Tabbed); 3566 } 3567 3568 // Regression test: Multiline-macro inside include guards. 3569 verifyFormat("#ifndef HEADER_H\n" 3570 "#define HEADER_H\n" 3571 "#define A() \\\n" 3572 " int i; \\\n" 3573 " int j;\n" 3574 "#endif // HEADER_H", 3575 getLLVMStyleWithColumns(20)); 3576 3577 Style.IndentPPDirectives = FormatStyle::PPDIS_BeforeHash; 3578 // Basic before hash indent tests 3579 verifyFormat("#ifdef _WIN32\n" 3580 " #define A 0\n" 3581 " #ifdef VAR2\n" 3582 " #define B 1\n" 3583 " #include <someheader.h>\n" 3584 " #define MACRO \\\n" 3585 " some_very_long_func_aaaaaaaaaa();\n" 3586 " #endif\n" 3587 "#else\n" 3588 " #define A 1\n" 3589 "#endif", 3590 Style); 3591 verifyFormat("#if A\n" 3592 " #define MACRO \\\n" 3593 " void a(int x) { \\\n" 3594 " b(); \\\n" 3595 " c(); \\\n" 3596 " d(); \\\n" 3597 " e(); \\\n" 3598 " f(); \\\n" 3599 " }\n" 3600 "#endif", 3601 Style); 3602 // Keep comments aligned with indented directives. These 3603 // tests cannot use verifyFormat because messUp manipulates leading 3604 // whitespace. 3605 { 3606 const char *Expected = "void f() {\n" 3607 "// Aligned to preprocessor.\n" 3608 "#if 1\n" 3609 " // Aligned to code.\n" 3610 " int a;\n" 3611 " #if 1\n" 3612 " // Aligned to preprocessor.\n" 3613 " #define A 0\n" 3614 " // Aligned to code.\n" 3615 " int b;\n" 3616 " #endif\n" 3617 "#endif\n" 3618 "}"; 3619 const char *ToFormat = "void f() {\n" 3620 "// Aligned to preprocessor.\n" 3621 "#if 1\n" 3622 "// Aligned to code.\n" 3623 "int a;\n" 3624 "#if 1\n" 3625 "// Aligned to preprocessor.\n" 3626 "#define A 0\n" 3627 "// Aligned to code.\n" 3628 "int b;\n" 3629 "#endif\n" 3630 "#endif\n" 3631 "}"; 3632 EXPECT_EQ(Expected, format(ToFormat, Style)); 3633 EXPECT_EQ(Expected, format(Expected, Style)); 3634 } 3635 { 3636 const char *Expected = "void f() {\n" 3637 "/* Aligned to preprocessor. */\n" 3638 "#if 1\n" 3639 " /* Aligned to code. */\n" 3640 " int a;\n" 3641 " #if 1\n" 3642 " /* Aligned to preprocessor. */\n" 3643 " #define A 0\n" 3644 " /* Aligned to code. */\n" 3645 " int b;\n" 3646 " #endif\n" 3647 "#endif\n" 3648 "}"; 3649 const char *ToFormat = "void f() {\n" 3650 "/* Aligned to preprocessor. */\n" 3651 "#if 1\n" 3652 "/* Aligned to code. */\n" 3653 "int a;\n" 3654 "#if 1\n" 3655 "/* Aligned to preprocessor. */\n" 3656 "#define A 0\n" 3657 "/* Aligned to code. */\n" 3658 "int b;\n" 3659 "#endif\n" 3660 "#endif\n" 3661 "}"; 3662 EXPECT_EQ(Expected, format(ToFormat, Style)); 3663 EXPECT_EQ(Expected, format(Expected, Style)); 3664 } 3665 3666 // Test single comment before preprocessor 3667 verifyFormat("// Comment\n" 3668 "\n" 3669 "#if 1\n" 3670 "#endif", 3671 Style); 3672 } 3673 3674 TEST_F(FormatTest, FormatHashIfNotAtStartOfLine) { 3675 verifyFormat("{\n { a #c; }\n}"); 3676 } 3677 3678 TEST_F(FormatTest, FormatUnbalancedStructuralElements) { 3679 EXPECT_EQ("#define A \\\n { \\\n {\nint i;", 3680 format("#define A { {\nint i;", getLLVMStyleWithColumns(11))); 3681 EXPECT_EQ("#define A \\\n } \\\n }\nint i;", 3682 format("#define A } }\nint i;", getLLVMStyleWithColumns(11))); 3683 } 3684 3685 TEST_F(FormatTest, EscapedNewlines) { 3686 FormatStyle Narrow = getLLVMStyleWithColumns(11); 3687 EXPECT_EQ("#define A \\\n int i; \\\n int j;", 3688 format("#define A \\\nint i;\\\n int j;", Narrow)); 3689 EXPECT_EQ("#define A\n\nint i;", format("#define A \\\n\n int i;")); 3690 EXPECT_EQ("template <class T> f();", format("\\\ntemplate <class T> f();")); 3691 EXPECT_EQ("/* \\ \\ \\\n */", format("\\\n/* \\ \\ \\\n */")); 3692 EXPECT_EQ("<a\n\\\\\n>", format("<a\n\\\\\n>")); 3693 3694 FormatStyle AlignLeft = getLLVMStyle(); 3695 AlignLeft.AlignEscapedNewlines = FormatStyle::ENAS_Left; 3696 EXPECT_EQ("#define MACRO(x) \\\n" 3697 "private: \\\n" 3698 " int x(int a);\n", 3699 format("#define MACRO(x) \\\n" 3700 "private: \\\n" 3701 " int x(int a);\n", 3702 AlignLeft)); 3703 3704 // CRLF line endings 3705 EXPECT_EQ("#define A \\\r\n int i; \\\r\n int j;", 3706 format("#define A \\\r\nint i;\\\r\n int j;", Narrow)); 3707 EXPECT_EQ("#define A\r\n\r\nint i;", format("#define A \\\r\n\r\n int i;")); 3708 EXPECT_EQ("template <class T> f();", format("\\\ntemplate <class T> f();")); 3709 EXPECT_EQ("/* \\ \\ \\\r\n */", format("\\\r\n/* \\ \\ \\\r\n */")); 3710 EXPECT_EQ("<a\r\n\\\\\r\n>", format("<a\r\n\\\\\r\n>")); 3711 EXPECT_EQ("#define MACRO(x) \\\r\n" 3712 "private: \\\r\n" 3713 " int x(int a);\r\n", 3714 format("#define MACRO(x) \\\r\n" 3715 "private: \\\r\n" 3716 " int x(int a);\r\n", 3717 AlignLeft)); 3718 3719 FormatStyle DontAlign = getLLVMStyle(); 3720 DontAlign.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign; 3721 DontAlign.MaxEmptyLinesToKeep = 3; 3722 // FIXME: can't use verifyFormat here because the newline before 3723 // "public:" is not inserted the first time it's reformatted 3724 EXPECT_EQ("#define A \\\n" 3725 " class Foo { \\\n" 3726 " void bar(); \\\n" 3727 "\\\n" 3728 "\\\n" 3729 "\\\n" 3730 " public: \\\n" 3731 " void baz(); \\\n" 3732 " };", 3733 format("#define A \\\n" 3734 " class Foo { \\\n" 3735 " void bar(); \\\n" 3736 "\\\n" 3737 "\\\n" 3738 "\\\n" 3739 " public: \\\n" 3740 " void baz(); \\\n" 3741 " };", 3742 DontAlign)); 3743 } 3744 3745 TEST_F(FormatTest, CalculateSpaceOnConsecutiveLinesInMacro) { 3746 verifyFormat("#define A \\\n" 3747 " int v( \\\n" 3748 " a); \\\n" 3749 " int i;", 3750 getLLVMStyleWithColumns(11)); 3751 } 3752 3753 TEST_F(FormatTest, MixingPreprocessorDirectivesAndNormalCode) { 3754 EXPECT_EQ( 3755 "#define ALooooooooooooooooooooooooooooooooooooooongMacro(" 3756 " \\\n" 3757 " aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)\n" 3758 "\n" 3759 "AlooooooooooooooooooooooooooooooooooooooongCaaaaaaaaaal(\n" 3760 " aLooooooooooooooooooooooonPaaaaaaaaaaaaaaaaaaaaarmmmm);\n", 3761 format(" #define ALooooooooooooooooooooooooooooooooooooooongMacro(" 3762 "\\\n" 3763 "aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)\n" 3764 " \n" 3765 " AlooooooooooooooooooooooooooooooooooooooongCaaaaaaaaaal(\n" 3766 " aLooooooooooooooooooooooonPaaaaaaaaaaaaaaaaaaaaarmmmm);\n")); 3767 } 3768 3769 TEST_F(FormatTest, LayoutStatementsAroundPreprocessorDirectives) { 3770 EXPECT_EQ("int\n" 3771 "#define A\n" 3772 " a;", 3773 format("int\n#define A\na;")); 3774 verifyFormat("functionCallTo(\n" 3775 " someOtherFunction(\n" 3776 " withSomeParameters, whichInSequence,\n" 3777 " areLongerThanALine(andAnotherCall,\n" 3778 "#define A B\n" 3779 " withMoreParamters,\n" 3780 " whichStronglyInfluenceTheLayout),\n" 3781 " andMoreParameters),\n" 3782 " trailing);", 3783 getLLVMStyleWithColumns(69)); 3784 verifyFormat("Foo::Foo()\n" 3785 "#ifdef BAR\n" 3786 " : baz(0)\n" 3787 "#endif\n" 3788 "{\n" 3789 "}"); 3790 verifyFormat("void f() {\n" 3791 " if (true)\n" 3792 "#ifdef A\n" 3793 " f(42);\n" 3794 " x();\n" 3795 "#else\n" 3796 " g();\n" 3797 " x();\n" 3798 "#endif\n" 3799 "}"); 3800 verifyFormat("void f(param1, param2,\n" 3801 " param3,\n" 3802 "#ifdef A\n" 3803 " param4(param5,\n" 3804 "#ifdef A1\n" 3805 " param6,\n" 3806 "#ifdef A2\n" 3807 " param7),\n" 3808 "#else\n" 3809 " param8),\n" 3810 " param9,\n" 3811 "#endif\n" 3812 " param10,\n" 3813 "#endif\n" 3814 " param11)\n" 3815 "#else\n" 3816 " param12)\n" 3817 "#endif\n" 3818 "{\n" 3819 " x();\n" 3820 "}", 3821 getLLVMStyleWithColumns(28)); 3822 verifyFormat("#if 1\n" 3823 "int i;"); 3824 verifyFormat("#if 1\n" 3825 "#endif\n" 3826 "#if 1\n" 3827 "#else\n" 3828 "#endif\n"); 3829 verifyFormat("DEBUG({\n" 3830 " return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 3831 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;\n" 3832 "});\n" 3833 "#if a\n" 3834 "#else\n" 3835 "#endif"); 3836 3837 verifyIncompleteFormat("void f(\n" 3838 "#if A\n" 3839 ");\n" 3840 "#else\n" 3841 "#endif"); 3842 } 3843 3844 TEST_F(FormatTest, GraciouslyHandleIncorrectPreprocessorConditions) { 3845 verifyFormat("#endif\n" 3846 "#if B"); 3847 } 3848 3849 TEST_F(FormatTest, FormatsJoinedLinesOnSubsequentRuns) { 3850 FormatStyle SingleLine = getLLVMStyle(); 3851 SingleLine.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_WithoutElse; 3852 verifyFormat("#if 0\n" 3853 "#elif 1\n" 3854 "#endif\n" 3855 "void foo() {\n" 3856 " if (test) foo2();\n" 3857 "}", 3858 SingleLine); 3859 } 3860 3861 TEST_F(FormatTest, LayoutBlockInsideParens) { 3862 verifyFormat("functionCall({ int i; });"); 3863 verifyFormat("functionCall({\n" 3864 " int i;\n" 3865 " int j;\n" 3866 "});"); 3867 verifyFormat("functionCall(\n" 3868 " {\n" 3869 " int i;\n" 3870 " int j;\n" 3871 " },\n" 3872 " aaaa, bbbb, cccc);"); 3873 verifyFormat("functionA(functionB({\n" 3874 " int i;\n" 3875 " int j;\n" 3876 " }),\n" 3877 " aaaa, bbbb, cccc);"); 3878 verifyFormat("functionCall(\n" 3879 " {\n" 3880 " int i;\n" 3881 " int j;\n" 3882 " },\n" 3883 " aaaa, bbbb, // comment\n" 3884 " cccc);"); 3885 verifyFormat("functionA(functionB({\n" 3886 " int i;\n" 3887 " int j;\n" 3888 " }),\n" 3889 " aaaa, bbbb, // comment\n" 3890 " cccc);"); 3891 verifyFormat("functionCall(aaaa, bbbb, { int i; });"); 3892 verifyFormat("functionCall(aaaa, bbbb, {\n" 3893 " int i;\n" 3894 " int j;\n" 3895 "});"); 3896 verifyFormat( 3897 "Aaa(\n" // FIXME: There shouldn't be a linebreak here. 3898 " {\n" 3899 " int i; // break\n" 3900 " },\n" 3901 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb,\n" 3902 " ccccccccccccccccc));"); 3903 verifyFormat("DEBUG({\n" 3904 " if (a)\n" 3905 " f();\n" 3906 "});"); 3907 } 3908 3909 TEST_F(FormatTest, LayoutBlockInsideStatement) { 3910 EXPECT_EQ("SOME_MACRO { int i; }\n" 3911 "int i;", 3912 format(" SOME_MACRO {int i;} int i;")); 3913 } 3914 3915 TEST_F(FormatTest, LayoutNestedBlocks) { 3916 verifyFormat("void AddOsStrings(unsigned bitmask) {\n" 3917 " struct s {\n" 3918 " int i;\n" 3919 " };\n" 3920 " s kBitsToOs[] = {{10}};\n" 3921 " for (int i = 0; i < 10; ++i)\n" 3922 " return;\n" 3923 "}"); 3924 verifyFormat("call(parameter, {\n" 3925 " something();\n" 3926 " // Comment using all columns.\n" 3927 " somethingelse();\n" 3928 "});", 3929 getLLVMStyleWithColumns(40)); 3930 verifyFormat("DEBUG( //\n" 3931 " { f(); }, a);"); 3932 verifyFormat("DEBUG( //\n" 3933 " {\n" 3934 " f(); //\n" 3935 " },\n" 3936 " a);"); 3937 3938 EXPECT_EQ("call(parameter, {\n" 3939 " something();\n" 3940 " // Comment too\n" 3941 " // looooooooooong.\n" 3942 " somethingElse();\n" 3943 "});", 3944 format("call(parameter, {\n" 3945 " something();\n" 3946 " // Comment too looooooooooong.\n" 3947 " somethingElse();\n" 3948 "});", 3949 getLLVMStyleWithColumns(29))); 3950 EXPECT_EQ("DEBUG({ int i; });", format("DEBUG({ int i; });")); 3951 EXPECT_EQ("DEBUG({ // comment\n" 3952 " int i;\n" 3953 "});", 3954 format("DEBUG({ // comment\n" 3955 "int i;\n" 3956 "});")); 3957 EXPECT_EQ("DEBUG({\n" 3958 " int i;\n" 3959 "\n" 3960 " // comment\n" 3961 " int j;\n" 3962 "});", 3963 format("DEBUG({\n" 3964 " int i;\n" 3965 "\n" 3966 " // comment\n" 3967 " int j;\n" 3968 "});")); 3969 3970 verifyFormat("DEBUG({\n" 3971 " if (a)\n" 3972 " return;\n" 3973 "});"); 3974 verifyGoogleFormat("DEBUG({\n" 3975 " if (a) return;\n" 3976 "});"); 3977 FormatStyle Style = getGoogleStyle(); 3978 Style.ColumnLimit = 45; 3979 verifyFormat("Debug(\n" 3980 " aaaaa,\n" 3981 " {\n" 3982 " if (aaaaaaaaaaaaaaaaaaaaaaaa) return;\n" 3983 " },\n" 3984 " a);", 3985 Style); 3986 3987 verifyFormat("SomeFunction({MACRO({ return output; }), b});"); 3988 3989 verifyNoCrash("^{v^{a}}"); 3990 } 3991 3992 TEST_F(FormatTest, FormatNestedBlocksInMacros) { 3993 EXPECT_EQ("#define MACRO() \\\n" 3994 " Debug(aaa, /* force line break */ \\\n" 3995 " { \\\n" 3996 " int i; \\\n" 3997 " int j; \\\n" 3998 " })", 3999 format("#define MACRO() Debug(aaa, /* force line break */ \\\n" 4000 " { int i; int j; })", 4001 getGoogleStyle())); 4002 4003 EXPECT_EQ("#define A \\\n" 4004 " [] { \\\n" 4005 " xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx( \\\n" 4006 " xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); \\\n" 4007 " }", 4008 format("#define A [] { xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx( \\\n" 4009 "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); }", 4010 getGoogleStyle())); 4011 } 4012 4013 TEST_F(FormatTest, PutEmptyBlocksIntoOneLine) { 4014 EXPECT_EQ("{}", format("{}")); 4015 verifyFormat("enum E {};"); 4016 verifyFormat("enum E {}"); 4017 FormatStyle Style = getLLVMStyle(); 4018 Style.SpaceInEmptyBlock = true; 4019 EXPECT_EQ("void f() { }", format("void f() {}", Style)); 4020 Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Empty; 4021 EXPECT_EQ("while (true) { }", format("while (true) {}", Style)); 4022 } 4023 4024 TEST_F(FormatTest, FormatBeginBlockEndMacros) { 4025 FormatStyle Style = getLLVMStyle(); 4026 Style.MacroBlockBegin = "^[A-Z_]+_BEGIN$"; 4027 Style.MacroBlockEnd = "^[A-Z_]+_END$"; 4028 verifyFormat("FOO_BEGIN\n" 4029 " FOO_ENTRY\n" 4030 "FOO_END", 4031 Style); 4032 verifyFormat("FOO_BEGIN\n" 4033 " NESTED_FOO_BEGIN\n" 4034 " NESTED_FOO_ENTRY\n" 4035 " NESTED_FOO_END\n" 4036 "FOO_END", 4037 Style); 4038 verifyFormat("FOO_BEGIN(Foo, Bar)\n" 4039 " int x;\n" 4040 " x = 1;\n" 4041 "FOO_END(Baz)", 4042 Style); 4043 } 4044 4045 //===----------------------------------------------------------------------===// 4046 // Line break tests. 4047 //===----------------------------------------------------------------------===// 4048 4049 TEST_F(FormatTest, PreventConfusingIndents) { 4050 verifyFormat( 4051 "void f() {\n" 4052 " SomeLongMethodName(SomeReallyLongMethod(CallOtherReallyLongMethod(\n" 4053 " parameter, parameter, parameter)),\n" 4054 " SecondLongCall(parameter));\n" 4055 "}"); 4056 verifyFormat( 4057 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 4058 " aaaaaaaaaaaaaaaaaaaaaaaa(\n" 4059 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 4060 " aaaaaaaaaaaaaaaaaaaaaaaa);"); 4061 verifyFormat( 4062 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 4063 " [aaaaaaaaaaaaaaaaaaaaaaaa\n" 4064 " [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]\n" 4065 " [aaaaaaaaaaaaaaaaaaaaaaaa]];"); 4066 verifyFormat( 4067 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<\n" 4068 " aaaaaaaaaaaaaaaaaaaaaaaa<\n" 4069 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>,\n" 4070 " aaaaaaaaaaaaaaaaaaaaaaaa>;"); 4071 verifyFormat("int a = bbbb && ccc &&\n" 4072 " fffff(\n" 4073 "#define A Just forcing a new line\n" 4074 " ddd);"); 4075 } 4076 4077 TEST_F(FormatTest, LineBreakingInBinaryExpressions) { 4078 verifyFormat( 4079 "bool aaaaaaa =\n" 4080 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaa).aaaaaaaaaaaaaaaaaaa() ||\n" 4081 " bbbbbbbb();"); 4082 verifyFormat( 4083 "bool aaaaaaa =\n" 4084 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaa).aaaaaaaaaaaaaaaaaaa() or\n" 4085 " bbbbbbbb();"); 4086 4087 verifyFormat("bool aaaaaaaaaaaaaaaaaaaaa =\n" 4088 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa != bbbbbbbbbbbbbbbbbb &&\n" 4089 " ccccccccc == ddddddddddd;"); 4090 verifyFormat("bool aaaaaaaaaaaaaaaaaaaaa =\n" 4091 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa != bbbbbbbbbbbbbbbbbb and\n" 4092 " ccccccccc == ddddddddddd;"); 4093 verifyFormat( 4094 "bool aaaaaaaaaaaaaaaaaaaaa =\n" 4095 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa not_eq bbbbbbbbbbbbbbbbbb and\n" 4096 " ccccccccc == ddddddddddd;"); 4097 4098 verifyFormat("aaaaaa = aaaaaaa(aaaaaaa, // break\n" 4099 " aaaaaa) &&\n" 4100 " bbbbbb && cccccc;"); 4101 verifyFormat("aaaaaa = aaaaaaa(aaaaaaa, // break\n" 4102 " aaaaaa) >>\n" 4103 " bbbbbb;"); 4104 verifyFormat("aa = Whitespaces.addUntouchableComment(\n" 4105 " SourceMgr.getSpellingColumnNumber(\n" 4106 " TheLine.Last->FormatTok.Tok.getLocation()) -\n" 4107 " 1);"); 4108 4109 verifyFormat("if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n" 4110 " bbbbbbbbbbbbbbbbbb) && // aaaaaaaaaaaaaaaa\n" 4111 " cccccc) {\n}"); 4112 verifyFormat("if constexpr ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n" 4113 " bbbbbbbbbbbbbbbbbb) && // aaaaaaaaaaa\n" 4114 " cccccc) {\n}"); 4115 verifyFormat("if CONSTEXPR ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n" 4116 " bbbbbbbbbbbbbbbbbb) && // aaaaaaaaaaa\n" 4117 " cccccc) {\n}"); 4118 verifyFormat("b = a &&\n" 4119 " // Comment\n" 4120 " b.c && d;"); 4121 4122 // If the LHS of a comparison is not a binary expression itself, the 4123 // additional linebreak confuses many people. 4124 verifyFormat( 4125 "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 4126 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) > 5) {\n" 4127 "}"); 4128 verifyFormat( 4129 "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 4130 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) == 5) {\n" 4131 "}"); 4132 verifyFormat( 4133 "if (aaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaaaaaaaaa(\n" 4134 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) == 5) {\n" 4135 "}"); 4136 verifyFormat( 4137 "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 4138 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) <=> 5) {\n" 4139 "}"); 4140 // Even explicit parentheses stress the precedence enough to make the 4141 // additional break unnecessary. 4142 verifyFormat("if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 4143 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) == 5) {\n" 4144 "}"); 4145 // This cases is borderline, but with the indentation it is still readable. 4146 verifyFormat( 4147 "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 4148 " aaaaaaaaaaaaaaa) > aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 4149 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n" 4150 "}", 4151 getLLVMStyleWithColumns(75)); 4152 4153 // If the LHS is a binary expression, we should still use the additional break 4154 // as otherwise the formatting hides the operator precedence. 4155 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 4156 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n" 4157 " 5) {\n" 4158 "}"); 4159 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 4160 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa <=>\n" 4161 " 5) {\n" 4162 "}"); 4163 4164 FormatStyle OnePerLine = getLLVMStyle(); 4165 OnePerLine.BinPackParameters = false; 4166 verifyFormat( 4167 "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n" 4168 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n" 4169 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}", 4170 OnePerLine); 4171 4172 verifyFormat("int i = someFunction(aaaaaaa, 0)\n" 4173 " .aaa(aaaaaaaaaaaaa) *\n" 4174 " aaaaaaa +\n" 4175 " aaaaaaa;", 4176 getLLVMStyleWithColumns(40)); 4177 } 4178 4179 TEST_F(FormatTest, ExpressionIndentation) { 4180 verifyFormat("bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 4181 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 4182 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n" 4183 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n" 4184 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb +\n" 4185 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb &&\n" 4186 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n" 4187 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >\n" 4188 " ccccccccccccccccccccccccccccccccccccccccc;"); 4189 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n" 4190 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 4191 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n" 4192 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}"); 4193 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 4194 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n" 4195 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n" 4196 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}"); 4197 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n" 4198 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n" 4199 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 4200 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}"); 4201 verifyFormat("if () {\n" 4202 "} else if (aaaaa && bbbbb > // break\n" 4203 " ccccc) {\n" 4204 "}"); 4205 verifyFormat("if () {\n" 4206 "} else if constexpr (aaaaa && bbbbb > // break\n" 4207 " ccccc) {\n" 4208 "}"); 4209 verifyFormat("if () {\n" 4210 "} else if CONSTEXPR (aaaaa && bbbbb > // break\n" 4211 " ccccc) {\n" 4212 "}"); 4213 verifyFormat("if () {\n" 4214 "} else if (aaaaa &&\n" 4215 " bbbbb > // break\n" 4216 " ccccc &&\n" 4217 " ddddd) {\n" 4218 "}"); 4219 4220 // Presence of a trailing comment used to change indentation of b. 4221 verifyFormat("return aaaaaaaaaaaaaaaaaaa +\n" 4222 " b;\n" 4223 "return aaaaaaaaaaaaaaaaaaa +\n" 4224 " b; //", 4225 getLLVMStyleWithColumns(30)); 4226 } 4227 4228 TEST_F(FormatTest, ExpressionIndentationBreakingBeforeOperators) { 4229 // Not sure what the best system is here. Like this, the LHS can be found 4230 // immediately above an operator (everything with the same or a higher 4231 // indent). The RHS is aligned right of the operator and so compasses 4232 // everything until something with the same indent as the operator is found. 4233 // FIXME: Is this a good system? 4234 FormatStyle Style = getLLVMStyle(); 4235 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 4236 verifyFormat( 4237 "bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 4238 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 4239 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 4240 " == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 4241 " * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 4242 " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 4243 " && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 4244 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 4245 " > ccccccccccccccccccccccccccccccccccccccccc;", 4246 Style); 4247 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 4248 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 4249 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 4250 " == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}", 4251 Style); 4252 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 4253 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 4254 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 4255 " == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}", 4256 Style); 4257 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 4258 " == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 4259 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 4260 " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}", 4261 Style); 4262 verifyFormat("if () {\n" 4263 "} else if (aaaaa\n" 4264 " && bbbbb // break\n" 4265 " > ccccc) {\n" 4266 "}", 4267 Style); 4268 verifyFormat("return (a)\n" 4269 " // comment\n" 4270 " + b;", 4271 Style); 4272 verifyFormat( 4273 "int aaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 4274 " * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 4275 " + cc;", 4276 Style); 4277 4278 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 4279 " = aaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaa;", 4280 Style); 4281 4282 // Forced by comments. 4283 verifyFormat( 4284 "unsigned ContentSize =\n" 4285 " sizeof(int16_t) // DWARF ARange version number\n" 4286 " + sizeof(int32_t) // Offset of CU in the .debug_info section\n" 4287 " + sizeof(int8_t) // Pointer Size (in bytes)\n" 4288 " + sizeof(int8_t); // Segment Size (in bytes)"); 4289 4290 verifyFormat("return boost::fusion::at_c<0>(iiii).second\n" 4291 " == boost::fusion::at_c<1>(iiii).second;", 4292 Style); 4293 4294 Style.ColumnLimit = 60; 4295 verifyFormat("zzzzzzzzzz\n" 4296 " = bbbbbbbbbbbbbbbbb\n" 4297 " >> aaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaa);", 4298 Style); 4299 4300 Style.ColumnLimit = 80; 4301 Style.IndentWidth = 4; 4302 Style.TabWidth = 4; 4303 Style.UseTab = FormatStyle::UT_Always; 4304 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 4305 Style.AlignOperands = false; 4306 EXPECT_EQ("return someVeryVeryLongConditionThatBarelyFitsOnALine\n" 4307 "\t&& (someOtherLongishConditionPart1\n" 4308 "\t\t|| someOtherEvenLongerNestedConditionPart2);", 4309 format("return someVeryVeryLongConditionThatBarelyFitsOnALine && " 4310 "(someOtherLongishConditionPart1 || " 4311 "someOtherEvenLongerNestedConditionPart2);", 4312 Style)); 4313 } 4314 4315 TEST_F(FormatTest, EnforcedOperatorWraps) { 4316 // Here we'd like to wrap after the || operators, but a comment is forcing an 4317 // earlier wrap. 4318 verifyFormat("bool x = aaaaa //\n" 4319 " || bbbbb\n" 4320 " //\n" 4321 " || cccc;"); 4322 } 4323 4324 TEST_F(FormatTest, NoOperandAlignment) { 4325 FormatStyle Style = getLLVMStyle(); 4326 Style.AlignOperands = false; 4327 verifyFormat("aaaaaaaaaaaaaa(aaaaaaaaaaaa,\n" 4328 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 4329 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 4330 Style); 4331 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment; 4332 verifyFormat("bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 4333 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 4334 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 4335 " == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 4336 " * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 4337 " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 4338 " && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 4339 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 4340 " > ccccccccccccccccccccccccccccccccccccccccc;", 4341 Style); 4342 4343 verifyFormat("int aaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 4344 " * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 4345 " + cc;", 4346 Style); 4347 verifyFormat("int a = aa\n" 4348 " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 4349 " * cccccccccccccccccccccccccccccccccccc;\n", 4350 Style); 4351 4352 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 4353 verifyFormat("return (a > b\n" 4354 " // comment1\n" 4355 " // comment2\n" 4356 " || c);", 4357 Style); 4358 } 4359 4360 TEST_F(FormatTest, BreakingBeforeNonAssigmentOperators) { 4361 FormatStyle Style = getLLVMStyle(); 4362 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment; 4363 verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n" 4364 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 4365 " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;", 4366 Style); 4367 } 4368 4369 TEST_F(FormatTest, AllowBinPackingInsideArguments) { 4370 FormatStyle Style = getLLVMStyle(); 4371 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment; 4372 Style.BinPackArguments = false; 4373 Style.ColumnLimit = 40; 4374 verifyFormat("void test() {\n" 4375 " someFunction(\n" 4376 " this + argument + is + quite\n" 4377 " + long + so + it + gets + wrapped\n" 4378 " + but + remains + bin - packed);\n" 4379 "}", 4380 Style); 4381 verifyFormat("void test() {\n" 4382 " someFunction(arg1,\n" 4383 " this + argument + is\n" 4384 " + quite + long + so\n" 4385 " + it + gets + wrapped\n" 4386 " + but + remains + bin\n" 4387 " - packed,\n" 4388 " arg3);\n" 4389 "}", 4390 Style); 4391 verifyFormat("void test() {\n" 4392 " someFunction(\n" 4393 " arg1,\n" 4394 " this + argument + has\n" 4395 " + anotherFunc(nested,\n" 4396 " calls + whose\n" 4397 " + arguments\n" 4398 " + are + also\n" 4399 " + wrapped,\n" 4400 " in + addition)\n" 4401 " + to + being + bin - packed,\n" 4402 " arg3);\n" 4403 "}", 4404 Style); 4405 4406 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None; 4407 verifyFormat("void test() {\n" 4408 " someFunction(\n" 4409 " arg1,\n" 4410 " this + argument + has +\n" 4411 " anotherFunc(nested,\n" 4412 " calls + whose +\n" 4413 " arguments +\n" 4414 " are + also +\n" 4415 " wrapped,\n" 4416 " in + addition) +\n" 4417 " to + being + bin - packed,\n" 4418 " arg3);\n" 4419 "}", 4420 Style); 4421 } 4422 4423 TEST_F(FormatTest, ConstructorInitializers) { 4424 verifyFormat("Constructor() : Initializer(FitsOnTheLine) {}"); 4425 verifyFormat("Constructor() : Inttializer(FitsOnTheLine) {}", 4426 getLLVMStyleWithColumns(45)); 4427 verifyFormat("Constructor()\n" 4428 " : Inttializer(FitsOnTheLine) {}", 4429 getLLVMStyleWithColumns(44)); 4430 verifyFormat("Constructor()\n" 4431 " : Inttializer(FitsOnTheLine) {}", 4432 getLLVMStyleWithColumns(43)); 4433 4434 verifyFormat("template <typename T>\n" 4435 "Constructor() : Initializer(FitsOnTheLine) {}", 4436 getLLVMStyleWithColumns(45)); 4437 4438 verifyFormat( 4439 "SomeClass::Constructor()\n" 4440 " : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}"); 4441 4442 verifyFormat( 4443 "SomeClass::Constructor()\n" 4444 " : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 4445 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}"); 4446 verifyFormat( 4447 "SomeClass::Constructor()\n" 4448 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 4449 " aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}"); 4450 verifyFormat("Constructor(aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 4451 " aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 4452 " : aaaaaaaaaa(aaaaaa) {}"); 4453 4454 verifyFormat("Constructor()\n" 4455 " : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 4456 " aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 4457 " aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 4458 " aaaaaaaaaaaaaaaaaaaaaaa() {}"); 4459 4460 verifyFormat("Constructor()\n" 4461 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 4462 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}"); 4463 4464 verifyFormat("Constructor(int Parameter = 0)\n" 4465 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa),\n" 4466 " aaaaaaaaaaaa(aaaaaaaaaaaaaaaaa) {}"); 4467 verifyFormat("Constructor()\n" 4468 " : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbbbbb(b) {\n" 4469 "}", 4470 getLLVMStyleWithColumns(60)); 4471 verifyFormat("Constructor()\n" 4472 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 4473 " aaaaaaaaaaaaaaaaaaaaaaaaa(aaaa, aaaa)) {}"); 4474 4475 // Here a line could be saved by splitting the second initializer onto two 4476 // lines, but that is not desirable. 4477 verifyFormat("Constructor()\n" 4478 " : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaa),\n" 4479 " aaaaaaaaaaa(aaaaaaaaaaa),\n" 4480 " aaaaaaaaaaaaaaaaaaaaat(aaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}"); 4481 4482 FormatStyle OnePerLine = getLLVMStyle(); 4483 OnePerLine.ConstructorInitializerAllOnOneLineOrOnePerLine = true; 4484 OnePerLine.AllowAllParametersOfDeclarationOnNextLine = false; 4485 verifyFormat("SomeClass::Constructor()\n" 4486 " : aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 4487 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 4488 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", 4489 OnePerLine); 4490 verifyFormat("SomeClass::Constructor()\n" 4491 " : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), // Some comment\n" 4492 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 4493 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", 4494 OnePerLine); 4495 verifyFormat("MyClass::MyClass(int var)\n" 4496 " : some_var_(var), // 4 space indent\n" 4497 " some_other_var_(var + 1) { // lined up\n" 4498 "}", 4499 OnePerLine); 4500 verifyFormat("Constructor()\n" 4501 " : aaaaa(aaaaaa),\n" 4502 " aaaaa(aaaaaa),\n" 4503 " aaaaa(aaaaaa),\n" 4504 " aaaaa(aaaaaa),\n" 4505 " aaaaa(aaaaaa) {}", 4506 OnePerLine); 4507 verifyFormat("Constructor()\n" 4508 " : aaaaa(aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa,\n" 4509 " aaaaaaaaaaaaaaaaaaaaaa) {}", 4510 OnePerLine); 4511 OnePerLine.BinPackParameters = false; 4512 verifyFormat( 4513 "Constructor()\n" 4514 " : aaaaaaaaaaaaaaaaaaaaaaaa(\n" 4515 " aaaaaaaaaaa().aaa(),\n" 4516 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}", 4517 OnePerLine); 4518 OnePerLine.ColumnLimit = 60; 4519 verifyFormat("Constructor()\n" 4520 " : aaaaaaaaaaaaaaaaaaaa(a),\n" 4521 " bbbbbbbbbbbbbbbbbbbbbbbb(b) {}", 4522 OnePerLine); 4523 4524 EXPECT_EQ("Constructor()\n" 4525 " : // Comment forcing unwanted break.\n" 4526 " aaaa(aaaa) {}", 4527 format("Constructor() :\n" 4528 " // Comment forcing unwanted break.\n" 4529 " aaaa(aaaa) {}")); 4530 } 4531 4532 TEST_F(FormatTest, AllowAllConstructorInitializersOnNextLine) { 4533 FormatStyle Style = getLLVMStyle(); 4534 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma; 4535 Style.ColumnLimit = 60; 4536 Style.ConstructorInitializerAllOnOneLineOrOnePerLine = true; 4537 Style.AllowAllConstructorInitializersOnNextLine = true; 4538 Style.BinPackParameters = false; 4539 4540 for (int i = 0; i < 4; ++i) { 4541 // Test all combinations of parameters that should not have an effect. 4542 Style.AllowAllParametersOfDeclarationOnNextLine = i & 1; 4543 Style.AllowAllArgumentsOnNextLine = i & 2; 4544 4545 Style.AllowAllConstructorInitializersOnNextLine = true; 4546 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma; 4547 verifyFormat("Constructor()\n" 4548 " : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}", 4549 Style); 4550 verifyFormat("Constructor() : a(a), b(b) {}", Style); 4551 4552 Style.AllowAllConstructorInitializersOnNextLine = false; 4553 verifyFormat("Constructor()\n" 4554 " : aaaaaaaaaaaaaaaaaaaa(a)\n" 4555 " , bbbbbbbbbbbbbbbbbbbbb(b) {}", 4556 Style); 4557 verifyFormat("Constructor() : a(a), b(b) {}", Style); 4558 4559 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon; 4560 Style.AllowAllConstructorInitializersOnNextLine = true; 4561 verifyFormat("Constructor()\n" 4562 " : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}", 4563 Style); 4564 4565 Style.AllowAllConstructorInitializersOnNextLine = false; 4566 verifyFormat("Constructor()\n" 4567 " : aaaaaaaaaaaaaaaaaaaa(a),\n" 4568 " bbbbbbbbbbbbbbbbbbbbb(b) {}", 4569 Style); 4570 4571 Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon; 4572 Style.AllowAllConstructorInitializersOnNextLine = true; 4573 verifyFormat("Constructor() :\n" 4574 " aaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}", 4575 Style); 4576 4577 Style.AllowAllConstructorInitializersOnNextLine = false; 4578 verifyFormat("Constructor() :\n" 4579 " aaaaaaaaaaaaaaaaaa(a),\n" 4580 " bbbbbbbbbbbbbbbbbbbbb(b) {}", 4581 Style); 4582 } 4583 4584 // Test interactions between AllowAllParametersOfDeclarationOnNextLine and 4585 // AllowAllConstructorInitializersOnNextLine in all 4586 // BreakConstructorInitializers modes 4587 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma; 4588 Style.AllowAllParametersOfDeclarationOnNextLine = true; 4589 Style.AllowAllConstructorInitializersOnNextLine = false; 4590 verifyFormat("SomeClassWithALongName::Constructor(\n" 4591 " int aaaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbbb)\n" 4592 " : aaaaaaaaaaaaaaaaaaaa(a)\n" 4593 " , bbbbbbbbbbbbbbbbbbbbb(b) {}", 4594 Style); 4595 4596 Style.AllowAllConstructorInitializersOnNextLine = true; 4597 verifyFormat("SomeClassWithALongName::Constructor(\n" 4598 " int aaaaaaaaaaaaaaaaaaaaaaaa,\n" 4599 " int bbbbbbbbbbbbb,\n" 4600 " int cccccccccccccccc)\n" 4601 " : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}", 4602 Style); 4603 4604 Style.AllowAllParametersOfDeclarationOnNextLine = false; 4605 Style.AllowAllConstructorInitializersOnNextLine = false; 4606 verifyFormat("SomeClassWithALongName::Constructor(\n" 4607 " int aaaaaaaaaaaaaaaaaaaaaaaa,\n" 4608 " int bbbbbbbbbbbbb)\n" 4609 " : aaaaaaaaaaaaaaaaaaaa(a)\n" 4610 " , bbbbbbbbbbbbbbbbbbbbb(b) {}", 4611 Style); 4612 4613 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon; 4614 4615 Style.AllowAllParametersOfDeclarationOnNextLine = true; 4616 verifyFormat("SomeClassWithALongName::Constructor(\n" 4617 " int aaaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbbb)\n" 4618 " : aaaaaaaaaaaaaaaaaaaa(a),\n" 4619 " bbbbbbbbbbbbbbbbbbbbb(b) {}", 4620 Style); 4621 4622 Style.AllowAllConstructorInitializersOnNextLine = true; 4623 verifyFormat("SomeClassWithALongName::Constructor(\n" 4624 " int aaaaaaaaaaaaaaaaaaaaaaaa,\n" 4625 " int bbbbbbbbbbbbb,\n" 4626 " int cccccccccccccccc)\n" 4627 " : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}", 4628 Style); 4629 4630 Style.AllowAllParametersOfDeclarationOnNextLine = false; 4631 Style.AllowAllConstructorInitializersOnNextLine = false; 4632 verifyFormat("SomeClassWithALongName::Constructor(\n" 4633 " int aaaaaaaaaaaaaaaaaaaaaaaa,\n" 4634 " int bbbbbbbbbbbbb)\n" 4635 " : aaaaaaaaaaaaaaaaaaaa(a),\n" 4636 " bbbbbbbbbbbbbbbbbbbbb(b) {}", 4637 Style); 4638 4639 Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon; 4640 Style.AllowAllParametersOfDeclarationOnNextLine = true; 4641 verifyFormat("SomeClassWithALongName::Constructor(\n" 4642 " int aaaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbbb) :\n" 4643 " aaaaaaaaaaaaaaaaaaaa(a),\n" 4644 " bbbbbbbbbbbbbbbbbbbbb(b) {}", 4645 Style); 4646 4647 Style.AllowAllConstructorInitializersOnNextLine = true; 4648 verifyFormat("SomeClassWithALongName::Constructor(\n" 4649 " int aaaaaaaaaaaaaaaaaaaaaaaa,\n" 4650 " int bbbbbbbbbbbbb,\n" 4651 " int cccccccccccccccc) :\n" 4652 " aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}", 4653 Style); 4654 4655 Style.AllowAllParametersOfDeclarationOnNextLine = false; 4656 Style.AllowAllConstructorInitializersOnNextLine = false; 4657 verifyFormat("SomeClassWithALongName::Constructor(\n" 4658 " int aaaaaaaaaaaaaaaaaaaaaaaa,\n" 4659 " int bbbbbbbbbbbbb) :\n" 4660 " aaaaaaaaaaaaaaaaaaaa(a),\n" 4661 " bbbbbbbbbbbbbbbbbbbbb(b) {}", 4662 Style); 4663 } 4664 4665 TEST_F(FormatTest, AllowAllArgumentsOnNextLine) { 4666 FormatStyle Style = getLLVMStyle(); 4667 Style.ColumnLimit = 60; 4668 Style.BinPackArguments = false; 4669 for (int i = 0; i < 4; ++i) { 4670 // Test all combinations of parameters that should not have an effect. 4671 Style.AllowAllParametersOfDeclarationOnNextLine = i & 1; 4672 Style.AllowAllConstructorInitializersOnNextLine = i & 2; 4673 4674 Style.AllowAllArgumentsOnNextLine = true; 4675 verifyFormat("void foo() {\n" 4676 " FunctionCallWithReallyLongName(\n" 4677 " aaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbb);\n" 4678 "}", 4679 Style); 4680 Style.AllowAllArgumentsOnNextLine = false; 4681 verifyFormat("void foo() {\n" 4682 " FunctionCallWithReallyLongName(\n" 4683 " aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 4684 " bbbbbbbbbbbb);\n" 4685 "}", 4686 Style); 4687 4688 Style.AllowAllArgumentsOnNextLine = true; 4689 verifyFormat("void foo() {\n" 4690 " auto VariableWithReallyLongName = {\n" 4691 " aaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbb};\n" 4692 "}", 4693 Style); 4694 Style.AllowAllArgumentsOnNextLine = false; 4695 verifyFormat("void foo() {\n" 4696 " auto VariableWithReallyLongName = {\n" 4697 " aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 4698 " bbbbbbbbbbbb};\n" 4699 "}", 4700 Style); 4701 } 4702 4703 // This parameter should not affect declarations. 4704 Style.BinPackParameters = false; 4705 Style.AllowAllArgumentsOnNextLine = false; 4706 Style.AllowAllParametersOfDeclarationOnNextLine = true; 4707 verifyFormat("void FunctionCallWithReallyLongName(\n" 4708 " int aaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbb);", 4709 Style); 4710 Style.AllowAllParametersOfDeclarationOnNextLine = false; 4711 verifyFormat("void FunctionCallWithReallyLongName(\n" 4712 " int aaaaaaaaaaaaaaaaaaaaaaa,\n" 4713 " int bbbbbbbbbbbb);", 4714 Style); 4715 } 4716 4717 TEST_F(FormatTest, BreakConstructorInitializersAfterColon) { 4718 FormatStyle Style = getLLVMStyle(); 4719 Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon; 4720 4721 verifyFormat("Constructor() : Initializer(FitsOnTheLine) {}"); 4722 verifyFormat("Constructor() : Initializer(FitsOnTheLine) {}", 4723 getStyleWithColumns(Style, 45)); 4724 verifyFormat("Constructor() :\n" 4725 " Initializer(FitsOnTheLine) {}", 4726 getStyleWithColumns(Style, 44)); 4727 verifyFormat("Constructor() :\n" 4728 " Initializer(FitsOnTheLine) {}", 4729 getStyleWithColumns(Style, 43)); 4730 4731 verifyFormat("template <typename T>\n" 4732 "Constructor() : Initializer(FitsOnTheLine) {}", 4733 getStyleWithColumns(Style, 50)); 4734 Style.ConstructorInitializerAllOnOneLineOrOnePerLine = true; 4735 verifyFormat( 4736 "SomeClass::Constructor() :\n" 4737 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}", 4738 Style); 4739 4740 Style.ConstructorInitializerAllOnOneLineOrOnePerLine = false; 4741 verifyFormat( 4742 "SomeClass::Constructor() :\n" 4743 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}", 4744 Style); 4745 4746 verifyFormat( 4747 "SomeClass::Constructor() :\n" 4748 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 4749 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", 4750 Style); 4751 verifyFormat( 4752 "SomeClass::Constructor() :\n" 4753 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 4754 " aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}", 4755 Style); 4756 verifyFormat("Constructor(aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 4757 " aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) :\n" 4758 " aaaaaaaaaa(aaaaaa) {}", 4759 Style); 4760 4761 verifyFormat("Constructor() :\n" 4762 " aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 4763 " aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 4764 " aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 4765 " aaaaaaaaaaaaaaaaaaaaaaa() {}", 4766 Style); 4767 4768 verifyFormat("Constructor() :\n" 4769 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 4770 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}", 4771 Style); 4772 4773 verifyFormat("Constructor(int Parameter = 0) :\n" 4774 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa),\n" 4775 " aaaaaaaaaaaa(aaaaaaaaaaaaaaaaa) {}", 4776 Style); 4777 verifyFormat("Constructor() :\n" 4778 " aaaaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbbbbb(b) {\n" 4779 "}", 4780 getStyleWithColumns(Style, 60)); 4781 verifyFormat("Constructor() :\n" 4782 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 4783 " aaaaaaaaaaaaaaaaaaaaaaaaa(aaaa, aaaa)) {}", 4784 Style); 4785 4786 // Here a line could be saved by splitting the second initializer onto two 4787 // lines, but that is not desirable. 4788 verifyFormat("Constructor() :\n" 4789 " aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaa),\n" 4790 " aaaaaaaaaaa(aaaaaaaaaaa),\n" 4791 " aaaaaaaaaaaaaaaaaaaaat(aaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}", 4792 Style); 4793 4794 FormatStyle OnePerLine = Style; 4795 OnePerLine.ConstructorInitializerAllOnOneLineOrOnePerLine = true; 4796 OnePerLine.AllowAllConstructorInitializersOnNextLine = false; 4797 verifyFormat("SomeClass::Constructor() :\n" 4798 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 4799 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 4800 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", 4801 OnePerLine); 4802 verifyFormat("SomeClass::Constructor() :\n" 4803 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa), // Some comment\n" 4804 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 4805 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", 4806 OnePerLine); 4807 verifyFormat("MyClass::MyClass(int var) :\n" 4808 " some_var_(var), // 4 space indent\n" 4809 " some_other_var_(var + 1) { // lined up\n" 4810 "}", 4811 OnePerLine); 4812 verifyFormat("Constructor() :\n" 4813 " aaaaa(aaaaaa),\n" 4814 " aaaaa(aaaaaa),\n" 4815 " aaaaa(aaaaaa),\n" 4816 " aaaaa(aaaaaa),\n" 4817 " aaaaa(aaaaaa) {}", 4818 OnePerLine); 4819 verifyFormat("Constructor() :\n" 4820 " aaaaa(aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa,\n" 4821 " aaaaaaaaaaaaaaaaaaaaaa) {}", 4822 OnePerLine); 4823 OnePerLine.BinPackParameters = false; 4824 verifyFormat("Constructor() :\n" 4825 " aaaaaaaaaaaaaaaaaaaaaaaa(\n" 4826 " aaaaaaaaaaa().aaa(),\n" 4827 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}", 4828 OnePerLine); 4829 OnePerLine.ColumnLimit = 60; 4830 verifyFormat("Constructor() :\n" 4831 " aaaaaaaaaaaaaaaaaaaa(a),\n" 4832 " bbbbbbbbbbbbbbbbbbbbbbbb(b) {}", 4833 OnePerLine); 4834 4835 EXPECT_EQ("Constructor() :\n" 4836 " // Comment forcing unwanted break.\n" 4837 " aaaa(aaaa) {}", 4838 format("Constructor() :\n" 4839 " // Comment forcing unwanted break.\n" 4840 " aaaa(aaaa) {}", 4841 Style)); 4842 4843 Style.ColumnLimit = 0; 4844 verifyFormat("SomeClass::Constructor() :\n" 4845 " a(a) {}", 4846 Style); 4847 verifyFormat("SomeClass::Constructor() noexcept :\n" 4848 " a(a) {}", 4849 Style); 4850 verifyFormat("SomeClass::Constructor() :\n" 4851 " a(a), b(b), c(c) {}", 4852 Style); 4853 verifyFormat("SomeClass::Constructor() :\n" 4854 " a(a) {\n" 4855 " foo();\n" 4856 " bar();\n" 4857 "}", 4858 Style); 4859 4860 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 4861 verifyFormat("SomeClass::Constructor() :\n" 4862 " a(a), b(b), c(c) {\n" 4863 "}", 4864 Style); 4865 verifyFormat("SomeClass::Constructor() :\n" 4866 " a(a) {\n" 4867 "}", 4868 Style); 4869 4870 Style.ColumnLimit = 80; 4871 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All; 4872 Style.ConstructorInitializerIndentWidth = 2; 4873 verifyFormat("SomeClass::Constructor() : a(a), b(b), c(c) {}", Style); 4874 verifyFormat("SomeClass::Constructor() :\n" 4875 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 4876 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {}", 4877 Style); 4878 4879 // `ConstructorInitializerIndentWidth` actually applies to InheritanceList as 4880 // well 4881 Style.BreakInheritanceList = FormatStyle::BILS_BeforeColon; 4882 verifyFormat( 4883 "class SomeClass\n" 4884 " : public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 4885 " public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};", 4886 Style); 4887 Style.BreakInheritanceList = FormatStyle::BILS_BeforeComma; 4888 verifyFormat( 4889 "class SomeClass\n" 4890 " : public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 4891 " , public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};", 4892 Style); 4893 Style.BreakInheritanceList = FormatStyle::BILS_AfterColon; 4894 verifyFormat( 4895 "class SomeClass :\n" 4896 " public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 4897 " public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};", 4898 Style); 4899 } 4900 4901 #ifndef EXPENSIVE_CHECKS 4902 // Expensive checks enables libstdc++ checking which includes validating the 4903 // state of ranges used in std::priority_queue - this blows out the 4904 // runtime/scalability of the function and makes this test unacceptably slow. 4905 TEST_F(FormatTest, MemoizationTests) { 4906 // This breaks if the memoization lookup does not take \c Indent and 4907 // \c LastSpace into account. 4908 verifyFormat( 4909 "extern CFRunLoopTimerRef\n" 4910 "CFRunLoopTimerCreate(CFAllocatorRef allocato, CFAbsoluteTime fireDate,\n" 4911 " CFTimeInterval interval, CFOptionFlags flags,\n" 4912 " CFIndex order, CFRunLoopTimerCallBack callout,\n" 4913 " CFRunLoopTimerContext *context) {}"); 4914 4915 // Deep nesting somewhat works around our memoization. 4916 verifyFormat( 4917 "aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n" 4918 " aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n" 4919 " aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n" 4920 " aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n" 4921 " aaaaa())))))))))))))))))))))))))))))))))))))));", 4922 getLLVMStyleWithColumns(65)); 4923 verifyFormat( 4924 "aaaaa(\n" 4925 " aaaaa,\n" 4926 " aaaaa(\n" 4927 " aaaaa,\n" 4928 " aaaaa(\n" 4929 " aaaaa,\n" 4930 " aaaaa(\n" 4931 " aaaaa,\n" 4932 " aaaaa(\n" 4933 " aaaaa,\n" 4934 " aaaaa(\n" 4935 " aaaaa,\n" 4936 " aaaaa(\n" 4937 " aaaaa,\n" 4938 " aaaaa(\n" 4939 " aaaaa,\n" 4940 " aaaaa(\n" 4941 " aaaaa,\n" 4942 " aaaaa(\n" 4943 " aaaaa,\n" 4944 " aaaaa(\n" 4945 " aaaaa,\n" 4946 " aaaaa(\n" 4947 " aaaaa,\n" 4948 " aaaaa))))))))))));", 4949 getLLVMStyleWithColumns(65)); 4950 verifyFormat( 4951 "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" 4952 " a),\n" 4953 " a),\n" 4954 " a),\n" 4955 " a),\n" 4956 " a),\n" 4957 " a),\n" 4958 " a),\n" 4959 " a),\n" 4960 " a),\n" 4961 " a),\n" 4962 " a),\n" 4963 " a),\n" 4964 " a),\n" 4965 " a),\n" 4966 " a),\n" 4967 " a),\n" 4968 " a)", 4969 getLLVMStyleWithColumns(65)); 4970 4971 // This test takes VERY long when memoization is broken. 4972 FormatStyle OnePerLine = getLLVMStyle(); 4973 OnePerLine.ConstructorInitializerAllOnOneLineOrOnePerLine = true; 4974 OnePerLine.BinPackParameters = false; 4975 std::string input = "Constructor()\n" 4976 " : aaaa(a,\n"; 4977 for (unsigned i = 0, e = 80; i != e; ++i) { 4978 input += " a,\n"; 4979 } 4980 input += " a) {}"; 4981 verifyFormat(input, OnePerLine); 4982 } 4983 #endif 4984 4985 TEST_F(FormatTest, BreaksAsHighAsPossible) { 4986 verifyFormat( 4987 "void f() {\n" 4988 " if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaa && aaaaaaaaaaaaaaaaaaaaaaaaaa) ||\n" 4989 " (bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb && bbbbbbbbbbbbbbbbbbbbbbbbbb))\n" 4990 " f();\n" 4991 "}"); 4992 verifyFormat("if (Intervals[i].getRange().getFirst() <\n" 4993 " Intervals[i - 1].getRange().getLast()) {\n}"); 4994 } 4995 4996 TEST_F(FormatTest, BreaksFunctionDeclarations) { 4997 // Principially, we break function declarations in a certain order: 4998 // 1) break amongst arguments. 4999 verifyFormat("Aaaaaaaaaaaaaa bbbbbbbbbbbbbb(Cccccccccccccc cccccccccccccc,\n" 5000 " Cccccccccccccc cccccccccccccc);"); 5001 verifyFormat("template <class TemplateIt>\n" 5002 "SomeReturnType SomeFunction(TemplateIt begin, TemplateIt end,\n" 5003 " TemplateIt *stop) {}"); 5004 5005 // 2) break after return type. 5006 verifyFormat( 5007 "Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 5008 "bbbbbbbbbbbbbb(Cccccccccccccc cccccccccccccccccccccccccc);", 5009 getGoogleStyle()); 5010 5011 // 3) break after (. 5012 verifyFormat( 5013 "Aaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbb(\n" 5014 " Cccccccccccccccccccccccccccccc cccccccccccccccccccccccccccccccc);", 5015 getGoogleStyle()); 5016 5017 // 4) break before after nested name specifiers. 5018 verifyFormat( 5019 "Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 5020 "SomeClasssssssssssssssssssssssssssssssssssssss::\n" 5021 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(Cccccccccccccc cccccccccc);", 5022 getGoogleStyle()); 5023 5024 // However, there are exceptions, if a sufficient amount of lines can be 5025 // saved. 5026 // FIXME: The precise cut-offs wrt. the number of saved lines might need some 5027 // more adjusting. 5028 verifyFormat("Aaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbb(Cccccccccccccc cccccccccc,\n" 5029 " Cccccccccccccc cccccccccc,\n" 5030 " Cccccccccccccc cccccccccc,\n" 5031 " Cccccccccccccc cccccccccc,\n" 5032 " Cccccccccccccc cccccccccc);"); 5033 verifyFormat( 5034 "Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 5035 "bbbbbbbbbbb(Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n" 5036 " Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n" 5037 " Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc);", 5038 getGoogleStyle()); 5039 verifyFormat( 5040 "Aaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(Cccccccccccccc cccccccccc,\n" 5041 " Cccccccccccccc cccccccccc,\n" 5042 " Cccccccccccccc cccccccccc,\n" 5043 " Cccccccccccccc cccccccccc,\n" 5044 " Cccccccccccccc cccccccccc,\n" 5045 " Cccccccccccccc cccccccccc,\n" 5046 " Cccccccccccccc cccccccccc);"); 5047 verifyFormat("Aaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n" 5048 " Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n" 5049 " Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n" 5050 " Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n" 5051 " Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc);"); 5052 5053 // Break after multi-line parameters. 5054 verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 5055 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 5056 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 5057 " bbbb bbbb);"); 5058 verifyFormat("void SomeLoooooooooooongFunction(\n" 5059 " std::unique_ptr<aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>\n" 5060 " aaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 5061 " int bbbbbbbbbbbbb);"); 5062 5063 // Treat overloaded operators like other functions. 5064 verifyFormat("SomeLoooooooooooooooooooooooooogType\n" 5065 "operator>(const SomeLoooooooooooooooooooooooooogType &other);"); 5066 verifyFormat("SomeLoooooooooooooooooooooooooogType\n" 5067 "operator>>(const SomeLooooooooooooooooooooooooogType &other);"); 5068 verifyFormat("SomeLoooooooooooooooooooooooooogType\n" 5069 "operator<<(const SomeLooooooooooooooooooooooooogType &other);"); 5070 verifyGoogleFormat( 5071 "SomeLoooooooooooooooooooooooooooooogType operator>>(\n" 5072 " const SomeLooooooooogType &a, const SomeLooooooooogType &b);"); 5073 verifyGoogleFormat( 5074 "SomeLoooooooooooooooooooooooooooooogType operator<<(\n" 5075 " const SomeLooooooooogType &a, const SomeLooooooooogType &b);"); 5076 verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 5077 " int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa = 1);"); 5078 verifyFormat("aaaaaaaaaaaaaaaaaaaaaa\n" 5079 "aaaaaaaaaaaaaaaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaa = 1);"); 5080 verifyGoogleFormat( 5081 "typename aaaaaaaaaa<aaaaaa>::aaaaaaaaaaa\n" 5082 "aaaaaaaaaa<aaaaaa>::aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 5083 " bool *aaaaaaaaaaaaaaaaaa, bool *aa) {}"); 5084 verifyGoogleFormat("template <typename T>\n" 5085 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 5086 "aaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaaaaaaaa(\n" 5087 " aaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaa);"); 5088 5089 FormatStyle Style = getLLVMStyle(); 5090 Style.PointerAlignment = FormatStyle::PAS_Left; 5091 verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 5092 " aaaaaaaaaaaaaaaaaaaaaaaaa* const aaaaaaaaaaaa) {}", 5093 Style); 5094 verifyFormat("void aaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa*\n" 5095 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}", 5096 Style); 5097 } 5098 5099 TEST_F(FormatTest, DontBreakBeforeQualifiedOperator) { 5100 // Regression test for https://bugs.llvm.org/show_bug.cgi?id=40516: 5101 // Prefer keeping `::` followed by `operator` together. 5102 EXPECT_EQ("const aaaa::bbbbbbb &\n" 5103 "ccccccccc::operator++() {\n" 5104 " stuff();\n" 5105 "}", 5106 format("const aaaa::bbbbbbb\n" 5107 "&ccccccccc::operator++() { stuff(); }", 5108 getLLVMStyleWithColumns(40))); 5109 } 5110 5111 TEST_F(FormatTest, TrailingReturnType) { 5112 verifyFormat("auto foo() -> int;\n"); 5113 // correct trailing return type spacing 5114 verifyFormat("auto operator->() -> int;\n"); 5115 verifyFormat("auto operator++(int) -> int;\n"); 5116 5117 verifyFormat("struct S {\n" 5118 " auto bar() const -> int;\n" 5119 "};"); 5120 verifyFormat("template <size_t Order, typename T>\n" 5121 "auto load_img(const std::string &filename)\n" 5122 " -> alias::tensor<Order, T, mem::tag::cpu> {}"); 5123 verifyFormat("auto SomeFunction(A aaaaaaaaaaaaaaaaaaaaa) const\n" 5124 " -> decltype(f(aaaaaaaaaaaaaaaaaaaaa)) {}"); 5125 verifyFormat("auto doSomething(Aaaaaa *aaaaaa) -> decltype(aaaaaa->f()) {}"); 5126 verifyFormat("template <typename T>\n" 5127 "auto aaaaaaaaaaaaaaaaaaaaaa(T t)\n" 5128 " -> decltype(eaaaaaaaaaaaaaaa<T>(t.a).aaaaaaaa());"); 5129 5130 // Not trailing return types. 5131 verifyFormat("void f() { auto a = b->c(); }"); 5132 } 5133 5134 TEST_F(FormatTest, DeductionGuides) { 5135 verifyFormat("template <class T> A(const T &, const T &) -> A<T &>;"); 5136 verifyFormat("template <class T> explicit A(T &, T &&) -> A<T>;"); 5137 verifyFormat("template <class... Ts> S(Ts...) -> S<Ts...>;"); 5138 verifyFormat( 5139 "template <class... T>\n" 5140 "array(T &&... t) -> array<std::common_type_t<T...>, sizeof...(T)>;"); 5141 verifyFormat("template <class T> A() -> A<decltype(p->foo<3>())>;"); 5142 verifyFormat("template <class T> A() -> A<decltype(foo<traits<1>>)>;"); 5143 verifyFormat("template <class T> A() -> A<sizeof(p->foo<1>)>;"); 5144 verifyFormat("template <class T> A() -> A<(3 < 2)>;"); 5145 verifyFormat("template <class T> A() -> A<((3) < (2))>;"); 5146 verifyFormat("template <class T> x() -> x<1>;"); 5147 verifyFormat("template <class T> explicit x(T &) -> x<1>;"); 5148 5149 // Ensure not deduction guides. 5150 verifyFormat("c()->f<int>();"); 5151 verifyFormat("x()->foo<1>;"); 5152 verifyFormat("x = p->foo<3>();"); 5153 verifyFormat("x()->x<1>();"); 5154 verifyFormat("x()->x<1>;"); 5155 } 5156 5157 TEST_F(FormatTest, BreaksFunctionDeclarationsWithTrailingTokens) { 5158 // Avoid breaking before trailing 'const' or other trailing annotations, if 5159 // they are not function-like. 5160 FormatStyle Style = getGoogleStyle(); 5161 Style.ColumnLimit = 47; 5162 verifyFormat("void someLongFunction(\n" 5163 " int someLoooooooooooooongParameter) const {\n}", 5164 getLLVMStyleWithColumns(47)); 5165 verifyFormat("LoooooongReturnType\n" 5166 "someLoooooooongFunction() const {}", 5167 getLLVMStyleWithColumns(47)); 5168 verifyFormat("LoooooongReturnType someLoooooooongFunction()\n" 5169 " const {}", 5170 Style); 5171 verifyFormat("void SomeFunction(aaaaa aaaaaaaaaaaaaaaaaaaa,\n" 5172 " aaaaa aaaaaaaaaaaaaaaaaaaa) OVERRIDE;"); 5173 verifyFormat("void SomeFunction(aaaaa aaaaaaaaaaaaaaaaaaaa,\n" 5174 " aaaaa aaaaaaaaaaaaaaaaaaaa) OVERRIDE FINAL;"); 5175 verifyFormat("void SomeFunction(aaaaa aaaaaaaaaaaaaaaaaaaa,\n" 5176 " aaaaa aaaaaaaaaaaaaaaaaaaa) override final;"); 5177 verifyFormat("virtual void aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaa aaaa,\n" 5178 " aaaaaaaaaaa aaaaa) const override;"); 5179 verifyGoogleFormat( 5180 "virtual void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 5181 " const override;"); 5182 5183 // Even if the first parameter has to be wrapped. 5184 verifyFormat("void someLongFunction(\n" 5185 " int someLongParameter) const {}", 5186 getLLVMStyleWithColumns(46)); 5187 verifyFormat("void someLongFunction(\n" 5188 " int someLongParameter) const {}", 5189 Style); 5190 verifyFormat("void someLongFunction(\n" 5191 " int someLongParameter) override {}", 5192 Style); 5193 verifyFormat("void someLongFunction(\n" 5194 " int someLongParameter) OVERRIDE {}", 5195 Style); 5196 verifyFormat("void someLongFunction(\n" 5197 " int someLongParameter) final {}", 5198 Style); 5199 verifyFormat("void someLongFunction(\n" 5200 " int someLongParameter) FINAL {}", 5201 Style); 5202 verifyFormat("void someLongFunction(\n" 5203 " int parameter) const override {}", 5204 Style); 5205 5206 Style.BreakBeforeBraces = FormatStyle::BS_Allman; 5207 verifyFormat("void someLongFunction(\n" 5208 " int someLongParameter) const\n" 5209 "{\n" 5210 "}", 5211 Style); 5212 5213 Style.BreakBeforeBraces = FormatStyle::BS_Whitesmiths; 5214 verifyFormat("void someLongFunction(\n" 5215 " int someLongParameter) const\n" 5216 " {\n" 5217 " }", 5218 Style); 5219 5220 // Unless these are unknown annotations. 5221 verifyFormat("void SomeFunction(aaaaaaaaaa aaaaaaaaaaaaaaa,\n" 5222 " aaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 5223 " LONG_AND_UGLY_ANNOTATION;"); 5224 5225 // Breaking before function-like trailing annotations is fine to keep them 5226 // close to their arguments. 5227 verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 5228 " LOCKS_EXCLUDED(aaaaaaaaaaaaa);"); 5229 verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) const\n" 5230 " LOCKS_EXCLUDED(aaaaaaaaaaaaa);"); 5231 verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) const\n" 5232 " LOCKS_EXCLUDED(aaaaaaaaaaaaa) {}"); 5233 verifyGoogleFormat("void aaaaaaaaaaaaaa(aaaaaaaa aaa) override\n" 5234 " AAAAAAAAAAAAAAAAAAAAAAAA(aaaaaaaaaaaaaaa);"); 5235 verifyFormat("SomeFunction([](int i) LOCKS_EXCLUDED(a) {});"); 5236 5237 verifyFormat( 5238 "void aaaaaaaaaaaaaaaaaa()\n" 5239 " __attribute__((aaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaa,\n" 5240 " aaaaaaaaaaaaaaaaaaaaaaaaa));"); 5241 verifyFormat("bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 5242 " __attribute__((unused));"); 5243 verifyGoogleFormat( 5244 "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 5245 " GUARDED_BY(aaaaaaaaaaaa);"); 5246 verifyGoogleFormat( 5247 "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 5248 " GUARDED_BY(aaaaaaaaaaaa);"); 5249 verifyGoogleFormat( 5250 "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa GUARDED_BY(aaaaaaaaaaaa) =\n" 5251 " aaaaaaaa::aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 5252 verifyGoogleFormat( 5253 "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa GUARDED_BY(aaaaaaaaaaaa) =\n" 5254 " aaaaaaaaaaaaaaaaaaaaaaaaa;"); 5255 } 5256 5257 TEST_F(FormatTest, FunctionAnnotations) { 5258 verifyFormat("DEPRECATED(\"Use NewClass::NewFunction instead.\")\n" 5259 "int OldFunction(const string ¶meter) {}"); 5260 verifyFormat("DEPRECATED(\"Use NewClass::NewFunction instead.\")\n" 5261 "string OldFunction(const string ¶meter) {}"); 5262 verifyFormat("template <typename T>\n" 5263 "DEPRECATED(\"Use NewClass::NewFunction instead.\")\n" 5264 "string OldFunction(const string ¶meter) {}"); 5265 5266 // Not function annotations. 5267 verifyFormat("ASSERT(\"aaaaa\") << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 5268 " << bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"); 5269 verifyFormat("TEST_F(ThisIsATestFixtureeeeeeeeeeeee,\n" 5270 " ThisIsATestWithAReallyReallyReallyReallyLongName) {}"); 5271 verifyFormat("MACRO(abc).function() // wrap\n" 5272 " << abc;"); 5273 verifyFormat("MACRO(abc)->function() // wrap\n" 5274 " << abc;"); 5275 verifyFormat("MACRO(abc)::function() // wrap\n" 5276 " << abc;"); 5277 } 5278 5279 TEST_F(FormatTest, BreaksDesireably) { 5280 verifyFormat("if (aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa) ||\n" 5281 " aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa) ||\n" 5282 " aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa)) {\n}"); 5283 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 5284 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n" 5285 "}"); 5286 5287 verifyFormat( 5288 "aaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 5289 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}"); 5290 5291 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 5292 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 5293 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa));"); 5294 5295 verifyFormat( 5296 "aaaaaaaa(aaaaaaaaaaaaa,\n" 5297 " aaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 5298 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)),\n" 5299 " aaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 5300 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)));"); 5301 5302 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n" 5303 " (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 5304 5305 verifyFormat( 5306 "void f() {\n" 5307 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa &&\n" 5308 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n" 5309 "}"); 5310 verifyFormat( 5311 "aaaaaa(new Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 5312 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaa));"); 5313 verifyFormat( 5314 "aaaaaa(aaa, new Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 5315 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaa));"); 5316 verifyFormat( 5317 "aaaaaa(aaa,\n" 5318 " new Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 5319 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 5320 " aaaa);"); 5321 verifyFormat("aaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 5322 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 5323 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 5324 5325 // Indent consistently independent of call expression and unary operator. 5326 verifyFormat("aaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n" 5327 " dddddddddddddddddddddddddddddd));"); 5328 verifyFormat("aaaaaaaaaaa(!bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n" 5329 " dddddddddddddddddddddddddddddd));"); 5330 verifyFormat("aaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbb.ccccccccccccccccc(\n" 5331 " dddddddddddddddddddddddddddddd));"); 5332 5333 // This test case breaks on an incorrect memoization, i.e. an optimization not 5334 // taking into account the StopAt value. 5335 verifyFormat( 5336 "return aaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaa ||\n" 5337 " aaaaaaaaaaa(aaaaaaaaa) || aaaaaaaaaaaaaaaaaaaaaaa ||\n" 5338 " aaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaa ||\n" 5339 " (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 5340 5341 verifyFormat("{\n {\n {\n" 5342 " Annotation.SpaceRequiredBefore =\n" 5343 " Line.Tokens[i - 1].Tok.isNot(tok::l_paren) &&\n" 5344 " Line.Tokens[i - 1].Tok.isNot(tok::l_square);\n" 5345 " }\n }\n}"); 5346 5347 // Break on an outer level if there was a break on an inner level. 5348 EXPECT_EQ("f(g(h(a, // comment\n" 5349 " b, c),\n" 5350 " d, e),\n" 5351 " x, y);", 5352 format("f(g(h(a, // comment\n" 5353 " b, c), d, e), x, y);")); 5354 5355 // Prefer breaking similar line breaks. 5356 verifyFormat( 5357 "const int kTrackingOptions = NSTrackingMouseMoved |\n" 5358 " NSTrackingMouseEnteredAndExited |\n" 5359 " NSTrackingActiveAlways;"); 5360 } 5361 5362 TEST_F(FormatTest, FormatsDeclarationsOnePerLine) { 5363 FormatStyle NoBinPacking = getGoogleStyle(); 5364 NoBinPacking.BinPackParameters = false; 5365 NoBinPacking.BinPackArguments = true; 5366 verifyFormat("void f() {\n" 5367 " f(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaa,\n" 5368 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n" 5369 "}", 5370 NoBinPacking); 5371 verifyFormat("void f(int aaaaaaaaaaaaaaaaaaaa,\n" 5372 " int aaaaaaaaaaaaaaaaaaaa,\n" 5373 " int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}", 5374 NoBinPacking); 5375 5376 NoBinPacking.AllowAllParametersOfDeclarationOnNextLine = false; 5377 verifyFormat("void aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 5378 " vector<int> bbbbbbbbbbbbbbb);", 5379 NoBinPacking); 5380 // FIXME: This behavior difference is probably not wanted. However, currently 5381 // we cannot distinguish BreakBeforeParameter being set because of the wrapped 5382 // template arguments from BreakBeforeParameter being set because of the 5383 // one-per-line formatting. 5384 verifyFormat( 5385 "void fffffffffff(aaaaaaaaaaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaa,\n" 5386 " aaaaaaaaaa> aaaaaaaaaa);", 5387 NoBinPacking); 5388 verifyFormat( 5389 "void fffffffffff(\n" 5390 " aaaaaaaaaaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaa>\n" 5391 " aaaaaaaaaa);"); 5392 } 5393 5394 TEST_F(FormatTest, FormatsOneParameterPerLineIfNecessary) { 5395 FormatStyle NoBinPacking = getGoogleStyle(); 5396 NoBinPacking.BinPackParameters = false; 5397 NoBinPacking.BinPackArguments = false; 5398 verifyFormat("f(aaaaaaaaaaaaaaaaaaaa,\n" 5399 " aaaaaaaaaaaaaaaaaaaa,\n" 5400 " aaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaa);", 5401 NoBinPacking); 5402 verifyFormat("aaaaaaa(aaaaaaaaaaaaa,\n" 5403 " aaaaaaaaaaaaa,\n" 5404 " aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa));", 5405 NoBinPacking); 5406 verifyFormat( 5407 "aaaaaaaa(aaaaaaaaaaaaa,\n" 5408 " aaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 5409 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)),\n" 5410 " aaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 5411 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)));", 5412 NoBinPacking); 5413 verifyFormat("aaaaaaaaaaaaaaa(aaaaaaaaa, aaaaaaaaa, aaaaaaaaaaaaaaaaaaaaa)\n" 5414 " .aaaaaaaaaaaaaaaaaa();", 5415 NoBinPacking); 5416 verifyFormat("void f() {\n" 5417 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 5418 " aaaaaaaaaa, aaaaaaaaaa, aaaaaaaaaa, aaaaaaaaaaa);\n" 5419 "}", 5420 NoBinPacking); 5421 5422 verifyFormat( 5423 "aaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa,\n" 5424 " aaaaaaaaaaaa,\n" 5425 " aaaaaaaaaaaa);", 5426 NoBinPacking); 5427 verifyFormat( 5428 "somefunction(someotherFunction(ddddddddddddddddddddddddddddddddddd,\n" 5429 " ddddddddddddddddddddddddddddd),\n" 5430 " test);", 5431 NoBinPacking); 5432 5433 verifyFormat("std::vector<aaaaaaaaaaaaaaaaaaaaaaa,\n" 5434 " aaaaaaaaaaaaaaaaaaaaaaa,\n" 5435 " aaaaaaaaaaaaaaaaaaaaaaa>\n" 5436 " aaaaaaaaaaaaaaaaaa;", 5437 NoBinPacking); 5438 verifyFormat("a(\"a\"\n" 5439 " \"a\",\n" 5440 " a);"); 5441 5442 NoBinPacking.AllowAllParametersOfDeclarationOnNextLine = false; 5443 verifyFormat("void aaaaaaaaaa(aaaaaaaaa,\n" 5444 " aaaaaaaaa,\n" 5445 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 5446 NoBinPacking); 5447 verifyFormat( 5448 "void f() {\n" 5449 " aaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaa, aaaaaaaaa, aaaaaaaaaaaaaaaaaaaaa)\n" 5450 " .aaaaaaa();\n" 5451 "}", 5452 NoBinPacking); 5453 verifyFormat( 5454 "template <class SomeType, class SomeOtherType>\n" 5455 "SomeType SomeFunction(SomeType Type, SomeOtherType OtherType) {}", 5456 NoBinPacking); 5457 } 5458 5459 TEST_F(FormatTest, AdaptiveOnePerLineFormatting) { 5460 FormatStyle Style = getLLVMStyleWithColumns(15); 5461 Style.ExperimentalAutoDetectBinPacking = true; 5462 EXPECT_EQ("aaa(aaaa,\n" 5463 " aaaa,\n" 5464 " aaaa);\n" 5465 "aaa(aaaa,\n" 5466 " aaaa,\n" 5467 " aaaa);", 5468 format("aaa(aaaa,\n" // one-per-line 5469 " aaaa,\n" 5470 " aaaa );\n" 5471 "aaa(aaaa, aaaa, aaaa);", // inconclusive 5472 Style)); 5473 EXPECT_EQ("aaa(aaaa, aaaa,\n" 5474 " aaaa);\n" 5475 "aaa(aaaa, aaaa,\n" 5476 " aaaa);", 5477 format("aaa(aaaa, aaaa,\n" // bin-packed 5478 " aaaa );\n" 5479 "aaa(aaaa, aaaa, aaaa);", // inconclusive 5480 Style)); 5481 } 5482 5483 TEST_F(FormatTest, FormatsBuilderPattern) { 5484 verifyFormat("return llvm::StringSwitch<Reference::Kind>(name)\n" 5485 " .StartsWith(\".eh_frame_hdr\", ORDER_EH_FRAMEHDR)\n" 5486 " .StartsWith(\".eh_frame\", ORDER_EH_FRAME)\n" 5487 " .StartsWith(\".init\", ORDER_INIT)\n" 5488 " .StartsWith(\".fini\", ORDER_FINI)\n" 5489 " .StartsWith(\".hash\", ORDER_HASH)\n" 5490 " .Default(ORDER_TEXT);\n"); 5491 5492 verifyFormat("return aaaaaaaaaaaaaaaaa->aaaaa().aaaaaaaaaaaaa().aaaaaa() <\n" 5493 " aaaaaaaaaaaaaaa->aaaaa().aaaaaaaaaaaaa().aaaaaa();"); 5494 verifyFormat("aaaaaaa->aaaaaaa\n" 5495 " ->aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 5496 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 5497 " ->aaaaaaaa(aaaaaaaaaaaaaaa);"); 5498 verifyFormat( 5499 "aaaaaaa->aaaaaaa\n" 5500 " ->aaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 5501 " ->aaaaaaaa(aaaaaaaaaaaaaaa);"); 5502 verifyFormat( 5503 "aaaaaaaaaaaaaaaaaaa()->aaaaaa(bbbbb)->aaaaaaaaaaaaaaaaaaa( // break\n" 5504 " aaaaaaaaaaaaaa);"); 5505 verifyFormat( 5506 "aaaaaaaaaaaaaaaaaaaaaaa *aaaaaaaaa =\n" 5507 " aaaaaa->aaaaaaaaaaaa()\n" 5508 " ->aaaaaaaaaaaaaaaa(\n" 5509 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 5510 " ->aaaaaaaaaaaaaaaaa();"); 5511 verifyGoogleFormat( 5512 "void f() {\n" 5513 " someo->Add((new util::filetools::Handler(dir))\n" 5514 " ->OnEvent1(NewPermanentCallback(\n" 5515 " this, &HandlerHolderClass::EventHandlerCBA))\n" 5516 " ->OnEvent2(NewPermanentCallback(\n" 5517 " this, &HandlerHolderClass::EventHandlerCBB))\n" 5518 " ->OnEvent3(NewPermanentCallback(\n" 5519 " this, &HandlerHolderClass::EventHandlerCBC))\n" 5520 " ->OnEvent5(NewPermanentCallback(\n" 5521 " this, &HandlerHolderClass::EventHandlerCBD))\n" 5522 " ->OnEvent6(NewPermanentCallback(\n" 5523 " this, &HandlerHolderClass::EventHandlerCBE)));\n" 5524 "}"); 5525 5526 verifyFormat( 5527 "aaaaaaaaaaa().aaaaaaaaaaa().aaaaaaaaaaa().aaaaaaaaaaa().aaaaaaaaaaa();"); 5528 verifyFormat("aaaaaaaaaaaaaaa()\n" 5529 " .aaaaaaaaaaaaaaa()\n" 5530 " .aaaaaaaaaaaaaaa()\n" 5531 " .aaaaaaaaaaaaaaa()\n" 5532 " .aaaaaaaaaaaaaaa();"); 5533 verifyFormat("aaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa()\n" 5534 " .aaaaaaaaaaaaaaa()\n" 5535 " .aaaaaaaaaaaaaaa()\n" 5536 " .aaaaaaaaaaaaaaa();"); 5537 verifyFormat("aaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa()\n" 5538 " .aaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa()\n" 5539 " .aaaaaaaaaaaaaaa();"); 5540 verifyFormat("aaaaaaaaaaaaa->aaaaaaaaaaaaaaaaaaaaaaaa()\n" 5541 " ->aaaaaaaaaaaaaae(0)\n" 5542 " ->aaaaaaaaaaaaaaa();"); 5543 5544 // Don't linewrap after very short segments. 5545 verifyFormat("a().aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 5546 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 5547 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 5548 verifyFormat("aa().aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 5549 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 5550 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 5551 verifyFormat("aaa()\n" 5552 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 5553 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 5554 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 5555 5556 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaa()\n" 5557 " .aaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 5558 " .has<bbbbbbbbbbbbbbbbbbbbb>();"); 5559 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaa()\n" 5560 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<\n" 5561 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>();"); 5562 5563 // Prefer not to break after empty parentheses. 5564 verifyFormat("FirstToken->WhitespaceRange.getBegin().getLocWithOffset(\n" 5565 " First->LastNewlineOffset);"); 5566 5567 // Prefer not to create "hanging" indents. 5568 verifyFormat( 5569 "return !soooooooooooooome_map\n" 5570 " .insert(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 5571 " .second;"); 5572 verifyFormat( 5573 "return aaaaaaaaaaaaaaaa\n" 5574 " .aaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa)\n" 5575 " .aaaa(aaaaaaaaaaaaaa);"); 5576 // No hanging indent here. 5577 verifyFormat("aaaaaaaaaaaaaaaa.aaaaaaaaaaaaaa.aaaaaaaaaaaaaaa(\n" 5578 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 5579 verifyFormat("aaaaaaaaaaaaaaaa.aaaaaaaaaaaaaa().aaaaaaaaaaaaaaa(\n" 5580 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 5581 verifyFormat("aaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa)\n" 5582 " .aaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 5583 getLLVMStyleWithColumns(60)); 5584 verifyFormat("aaaaaaaaaaaaaaaaaa\n" 5585 " .aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa)\n" 5586 " .aaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 5587 getLLVMStyleWithColumns(59)); 5588 verifyFormat("aaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 5589 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 5590 " .aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 5591 5592 // Dont break if only closing statements before member call 5593 verifyFormat("test() {\n" 5594 " ([]() -> {\n" 5595 " int b = 32;\n" 5596 " return 3;\n" 5597 " }).foo();\n" 5598 "}"); 5599 verifyFormat("test() {\n" 5600 " (\n" 5601 " []() -> {\n" 5602 " int b = 32;\n" 5603 " return 3;\n" 5604 " },\n" 5605 " foo, bar)\n" 5606 " .foo();\n" 5607 "}"); 5608 verifyFormat("test() {\n" 5609 " ([]() -> {\n" 5610 " int b = 32;\n" 5611 " return 3;\n" 5612 " })\n" 5613 " .foo()\n" 5614 " .bar();\n" 5615 "}"); 5616 verifyFormat("test() {\n" 5617 " ([]() -> {\n" 5618 " int b = 32;\n" 5619 " return 3;\n" 5620 " })\n" 5621 " .foo(\"aaaaaaaaaaaaaaaaa\"\n" 5622 " \"bbbb\");\n" 5623 "}", 5624 getLLVMStyleWithColumns(30)); 5625 } 5626 5627 TEST_F(FormatTest, BreaksAccordingToOperatorPrecedence) { 5628 verifyFormat( 5629 "if (aaaaaaaaaaaaaaaaaaaaaaaaa ||\n" 5630 " bbbbbbbbbbbbbbbbbbbbbbbbb && ccccccccccccccccccccccccc) {\n}"); 5631 verifyFormat( 5632 "if (aaaaaaaaaaaaaaaaaaaaaaaaa or\n" 5633 " bbbbbbbbbbbbbbbbbbbbbbbbb and cccccccccccccccccccccccc) {\n}"); 5634 5635 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa && bbbbbbbbbbbbbbbbbbbbbbbbb ||\n" 5636 " ccccccccccccccccccccccccc) {\n}"); 5637 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa and bbbbbbbbbbbbbbbbbbbbbbbb or\n" 5638 " ccccccccccccccccccccccccc) {\n}"); 5639 5640 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa || bbbbbbbbbbbbbbbbbbbbbbbbb ||\n" 5641 " ccccccccccccccccccccccccc) {\n}"); 5642 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa or bbbbbbbbbbbbbbbbbbbbbbbbb or\n" 5643 " ccccccccccccccccccccccccc) {\n}"); 5644 5645 verifyFormat( 5646 "if ((aaaaaaaaaaaaaaaaaaaaaaaaa || bbbbbbbbbbbbbbbbbbbbbbbbb) &&\n" 5647 " ccccccccccccccccccccccccc) {\n}"); 5648 verifyFormat( 5649 "if ((aaaaaaaaaaaaaaaaaaaaaaaaa or bbbbbbbbbbbbbbbbbbbbbbbbb) and\n" 5650 " ccccccccccccccccccccccccc) {\n}"); 5651 5652 verifyFormat("return aaaa & AAAAAAAAAAAAAAAAAAAAAAAAAAAAA ||\n" 5653 " bbbb & BBBBBBBBBBBBBBBBBBBBBBBBBBBBB ||\n" 5654 " cccc & CCCCCCCCCCCCCCCCCCCCCCCCCC ||\n" 5655 " dddd & DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD;"); 5656 verifyFormat("return aaaa & AAAAAAAAAAAAAAAAAAAAAAAAAAAAA or\n" 5657 " bbbb & BBBBBBBBBBBBBBBBBBBBBBBBBBBBB or\n" 5658 " cccc & CCCCCCCCCCCCCCCCCCCCCCCCCC or\n" 5659 " dddd & DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD;"); 5660 5661 verifyFormat("if ((aaaaaaaaaa != aaaaaaaaaaaaaaa ||\n" 5662 " aaaaaaaaaaaaaaaaaaaaaaaa() >= aaaaaaaaaaaaaaaaaaaa) &&\n" 5663 " aaaaaaaaaaaaaaa != aa) {\n}"); 5664 verifyFormat("if ((aaaaaaaaaa != aaaaaaaaaaaaaaa or\n" 5665 " aaaaaaaaaaaaaaaaaaaaaaaa() >= aaaaaaaaaaaaaaaaaaaa) and\n" 5666 " aaaaaaaaaaaaaaa != aa) {\n}"); 5667 } 5668 5669 TEST_F(FormatTest, BreaksAfterAssignments) { 5670 verifyFormat( 5671 "unsigned Cost =\n" 5672 " TTI.getMemoryOpCost(I->getOpcode(), VectorTy, SI->getAlignment(),\n" 5673 " SI->getPointerAddressSpaceee());\n"); 5674 verifyFormat( 5675 "CharSourceRange LineRange = CharSourceRange::getTokenRange(\n" 5676 " Line.Tokens.front().Tok.getLo(), Line.Tokens.back().Tok.getLoc());"); 5677 5678 verifyFormat( 5679 "aaaaaaaaaaaaaaaaaaaaaaaaaa aaaa = aaaaaaaaaaaaaa(0).aaaa().aaaaaaaaa(\n" 5680 " aaaaaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaaaaaaa);"); 5681 verifyFormat("unsigned OriginalStartColumn =\n" 5682 " SourceMgr.getSpellingColumnNumber(\n" 5683 " Current.FormatTok.getStartOfNonWhitespace()) -\n" 5684 " 1;"); 5685 } 5686 5687 TEST_F(FormatTest, ConfigurableBreakAssignmentPenalty) { 5688 FormatStyle Style = getLLVMStyle(); 5689 verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaa =\n" 5690 " bbbbbbbbbbbbbbbbbbbbbbbbbb + cccccccccccccccccccccccccc;", 5691 Style); 5692 5693 Style.PenaltyBreakAssignment = 20; 5694 verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaa = bbbbbbbbbbbbbbbbbbbbbbbbbb +\n" 5695 " cccccccccccccccccccccccccc;", 5696 Style); 5697 } 5698 5699 TEST_F(FormatTest, AlignsAfterAssignments) { 5700 verifyFormat( 5701 "int Result = aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n" 5702 " aaaaaaaaaaaaaaaaaaaaaaaaa;"); 5703 verifyFormat( 5704 "Result += aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n" 5705 " aaaaaaaaaaaaaaaaaaaaaaaaa;"); 5706 verifyFormat( 5707 "Result >>= aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n" 5708 " aaaaaaaaaaaaaaaaaaaaaaaaa;"); 5709 verifyFormat( 5710 "int Result = (aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n" 5711 " aaaaaaaaaaaaaaaaaaaaaaaaa);"); 5712 verifyFormat( 5713 "double LooooooooooooooooooooooooongResult = aaaaaaaaaaaaaaaaaaaaaaaa +\n" 5714 " aaaaaaaaaaaaaaaaaaaaaaaa +\n" 5715 " aaaaaaaaaaaaaaaaaaaaaaaa;"); 5716 } 5717 5718 TEST_F(FormatTest, AlignsAfterReturn) { 5719 verifyFormat( 5720 "return aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n" 5721 " aaaaaaaaaaaaaaaaaaaaaaaaa;"); 5722 verifyFormat( 5723 "return (aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n" 5724 " aaaaaaaaaaaaaaaaaaaaaaaaa);"); 5725 verifyFormat( 5726 "return aaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >=\n" 5727 " aaaaaaaaaaaaaaaaaaaaaa();"); 5728 verifyFormat( 5729 "return (aaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >=\n" 5730 " aaaaaaaaaaaaaaaaaaaaaa());"); 5731 verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 5732 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 5733 verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 5734 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) &&\n" 5735 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 5736 verifyFormat("return\n" 5737 " // true if code is one of a or b.\n" 5738 " code == a || code == b;"); 5739 } 5740 5741 TEST_F(FormatTest, AlignsAfterOpenBracket) { 5742 verifyFormat( 5743 "void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaa aaaaaaaa,\n" 5744 " aaaaaaaaa aaaaaaa) {}"); 5745 verifyFormat( 5746 "SomeLongVariableName->someVeryLongFunctionName(aaaaaaaaaaa aaaaaaaaa,\n" 5747 " aaaaaaaaaaa aaaaaaaaa);"); 5748 verifyFormat( 5749 "SomeLongVariableName->someFunction(foooooooo(aaaaaaaaaaaaaaa,\n" 5750 " aaaaaaaaaaaaaaaaaaaaa));"); 5751 FormatStyle Style = getLLVMStyle(); 5752 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 5753 verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 5754 " aaaaaaaaaaa aaaaaaaa, aaaaaaaaa aaaaaaa) {}", 5755 Style); 5756 verifyFormat("SomeLongVariableName->someVeryLongFunctionName(\n" 5757 " aaaaaaaaaaa aaaaaaaaa, aaaaaaaaaaa aaaaaaaaa);", 5758 Style); 5759 verifyFormat("SomeLongVariableName->someFunction(\n" 5760 " foooooooo(aaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaa));", 5761 Style); 5762 verifyFormat( 5763 "void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaa aaaaaaaa,\n" 5764 " aaaaaaaaa aaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}", 5765 Style); 5766 verifyFormat( 5767 "SomeLongVariableName->someVeryLongFunctionName(aaaaaaaaaaa aaaaaaaaa,\n" 5768 " aaaaaaaaaaa aaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 5769 Style); 5770 verifyFormat( 5771 "SomeLongVariableName->someFunction(foooooooo(aaaaaaaaaaaaaaa,\n" 5772 " aaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa));", 5773 Style); 5774 5775 verifyFormat("bbbbbbbbbbbb(aaaaaaaaaaaaaaaaaaaaaaaa, //\n" 5776 " ccccccc(aaaaaaaaaaaaaaaaa, //\n" 5777 " b));", 5778 Style); 5779 5780 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 5781 Style.BinPackArguments = false; 5782 Style.BinPackParameters = false; 5783 verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 5784 " aaaaaaaaaaa aaaaaaaa,\n" 5785 " aaaaaaaaa aaaaaaa,\n" 5786 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}", 5787 Style); 5788 verifyFormat("SomeLongVariableName->someVeryLongFunctionName(\n" 5789 " aaaaaaaaaaa aaaaaaaaa,\n" 5790 " aaaaaaaaaaa aaaaaaaaa,\n" 5791 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 5792 Style); 5793 verifyFormat("SomeLongVariableName->someFunction(foooooooo(\n" 5794 " aaaaaaaaaaaaaaa,\n" 5795 " aaaaaaaaaaaaaaaaaaaaa,\n" 5796 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa));", 5797 Style); 5798 verifyFormat( 5799 "aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa(\n" 5800 " aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)));", 5801 Style); 5802 verifyFormat( 5803 "aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaa.aaaaaaaaaa(\n" 5804 " aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)));", 5805 Style); 5806 verifyFormat( 5807 "aaaaaaaaaaaaaaaaaaaaaaaa(\n" 5808 " aaaaaaaaaaaaaaaaaaaaa(\n" 5809 " aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)),\n" 5810 " aaaaaaaaaaaaaaaa);", 5811 Style); 5812 verifyFormat( 5813 "aaaaaaaaaaaaaaaaaaaaaaaa(\n" 5814 " aaaaaaaaaaaaaaaaaaaaa(\n" 5815 " aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)) &&\n" 5816 " aaaaaaaaaaaaaaaa);", 5817 Style); 5818 } 5819 5820 TEST_F(FormatTest, ParenthesesAndOperandAlignment) { 5821 FormatStyle Style = getLLVMStyleWithColumns(40); 5822 verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n" 5823 " bbbbbbbbbbbbbbbbbbbbbb);", 5824 Style); 5825 Style.AlignAfterOpenBracket = FormatStyle::BAS_Align; 5826 Style.AlignOperands = false; 5827 verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n" 5828 " bbbbbbbbbbbbbbbbbbbbbb);", 5829 Style); 5830 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 5831 Style.AlignOperands = true; 5832 verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n" 5833 " bbbbbbbbbbbbbbbbbbbbbb);", 5834 Style); 5835 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 5836 Style.AlignOperands = false; 5837 verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n" 5838 " bbbbbbbbbbbbbbbbbbbbbb);", 5839 Style); 5840 } 5841 5842 TEST_F(FormatTest, BreaksConditionalExpressions) { 5843 verifyFormat( 5844 "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 5845 " ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 5846 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 5847 verifyFormat( 5848 "aaaa(aaaaaaaaaa, aaaaaaaa,\n" 5849 " aaaaaaaaaaaaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 5850 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 5851 verifyFormat( 5852 "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 5853 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 5854 verifyFormat("aaaa(aaaaaaaaa, aaaaaaaaa,\n" 5855 " aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 5856 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 5857 verifyFormat( 5858 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa ? aaaa(aaaaaa)\n" 5859 " : aaaaaaaaaaaaa);"); 5860 verifyFormat( 5861 "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n" 5862 " aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 5863 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 5864 " aaaaaaaaaaaaa);"); 5865 verifyFormat( 5866 "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n" 5867 " aaaaaaaaaaaaaaaa ?: aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 5868 " aaaaaaaaaaaaa);"); 5869 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 5870 " ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 5871 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 5872 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 5873 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 5874 verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 5875 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 5876 " ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 5877 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 5878 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 5879 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 5880 " aaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 5881 verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 5882 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 5883 " ?: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 5884 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 5885 " aaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 5886 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 5887 " ? aaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 5888 " : aaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 5889 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaa =\n" 5890 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 5891 " ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 5892 " : aaaaaaaaaaaaaaaa;"); 5893 verifyFormat( 5894 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 5895 " ? aaaaaaaaaaaaaaa\n" 5896 " : aaaaaaaaaaaaaaa;"); 5897 verifyFormat("f(aaaaaaaaaaaaaaaa == // force break\n" 5898 " aaaaaaaaa\n" 5899 " ? b\n" 5900 " : c);"); 5901 verifyFormat("return aaaa == bbbb\n" 5902 " // comment\n" 5903 " ? aaaa\n" 5904 " : bbbb;"); 5905 verifyFormat("unsigned Indent =\n" 5906 " format(TheLine.First,\n" 5907 " IndentForLevel[TheLine.Level] >= 0\n" 5908 " ? IndentForLevel[TheLine.Level]\n" 5909 " : TheLine * 2,\n" 5910 " TheLine.InPPDirective, PreviousEndOfLineColumn);", 5911 getLLVMStyleWithColumns(60)); 5912 verifyFormat("bool aaaaaa = aaaaaaaaaaaaa //\n" 5913 " ? aaaaaaaaaaaaaaa\n" 5914 " : bbbbbbbbbbbbbbb //\n" 5915 " ? ccccccccccccccc\n" 5916 " : ddddddddddddddd;"); 5917 verifyFormat("bool aaaaaa = aaaaaaaaaaaaa //\n" 5918 " ? aaaaaaaaaaaaaaa\n" 5919 " : (bbbbbbbbbbbbbbb //\n" 5920 " ? ccccccccccccccc\n" 5921 " : ddddddddddddddd);"); 5922 verifyFormat( 5923 "int aaaaaaaaaaaaaaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 5924 " ? aaaaaaaaaaaaaaaaaaaaaaaaa +\n" 5925 " aaaaaaaaaaaaaaaaaaaaa +\n" 5926 " aaaaaaaaaaaaaaaaaaaaa\n" 5927 " : aaaaaaaaaa;"); 5928 verifyFormat( 5929 "aaaaaa = aaaaaaaaaaaa ? aaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 5930 " : aaaaaaaaaaaaaaaaaaaaaa\n" 5931 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 5932 5933 FormatStyle NoBinPacking = getLLVMStyle(); 5934 NoBinPacking.BinPackArguments = false; 5935 verifyFormat( 5936 "void f() {\n" 5937 " g(aaa,\n" 5938 " aaaaaaaaaa == aaaaaaaaaa ? aaaa : aaaaa,\n" 5939 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 5940 " ? aaaaaaaaaaaaaaa\n" 5941 " : aaaaaaaaaaaaaaa);\n" 5942 "}", 5943 NoBinPacking); 5944 verifyFormat( 5945 "void f() {\n" 5946 " g(aaa,\n" 5947 " aaaaaaaaaa == aaaaaaaaaa ? aaaa : aaaaa,\n" 5948 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 5949 " ?: aaaaaaaaaaaaaaa);\n" 5950 "}", 5951 NoBinPacking); 5952 5953 verifyFormat("SomeFunction(aaaaaaaaaaaaaaaaa,\n" 5954 " // comment.\n" 5955 " ccccccccccccccccccccccccccccccccccccccc\n" 5956 " ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 5957 " : bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb);"); 5958 5959 // Assignments in conditional expressions. Apparently not uncommon :-(. 5960 verifyFormat("return a != b\n" 5961 " // comment\n" 5962 " ? a = b\n" 5963 " : a = b;"); 5964 verifyFormat("return a != b\n" 5965 " // comment\n" 5966 " ? a = a != b\n" 5967 " // comment\n" 5968 " ? a = b\n" 5969 " : a\n" 5970 " : a;\n"); 5971 verifyFormat("return a != b\n" 5972 " // comment\n" 5973 " ? a\n" 5974 " : a = a != b\n" 5975 " // comment\n" 5976 " ? a = b\n" 5977 " : a;"); 5978 } 5979 5980 TEST_F(FormatTest, BreaksConditionalExpressionsAfterOperator) { 5981 FormatStyle Style = getLLVMStyle(); 5982 Style.BreakBeforeTernaryOperators = false; 5983 Style.ColumnLimit = 70; 5984 verifyFormat( 5985 "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaa ?\n" 5986 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n" 5987 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 5988 Style); 5989 verifyFormat( 5990 "aaaa(aaaaaaaaaa, aaaaaaaa,\n" 5991 " aaaaaaaaaaaaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n" 5992 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 5993 Style); 5994 verifyFormat( 5995 "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n" 5996 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 5997 Style); 5998 verifyFormat("aaaa(aaaaaaaa, aaaaaaaaaa,\n" 5999 " aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n" 6000 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 6001 Style); 6002 verifyFormat( 6003 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa ? aaaa(aaaaaa) :\n" 6004 " aaaaaaaaaaaaa);", 6005 Style); 6006 verifyFormat( 6007 "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n" 6008 " aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n" 6009 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 6010 " aaaaaaaaaaaaa);", 6011 Style); 6012 verifyFormat( 6013 "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n" 6014 " aaaaaaaaaaaaaaaa ?: aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 6015 " aaaaaaaaaaaaa);", 6016 Style); 6017 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n" 6018 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6019 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) :\n" 6020 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6021 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 6022 Style); 6023 verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 6024 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n" 6025 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6026 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) :\n" 6027 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6028 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 6029 " aaaaaaaaaaaaaaaaaaaaaaaaaaa);", 6030 Style); 6031 verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 6032 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?:\n" 6033 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6034 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 6035 " aaaaaaaaaaaaaaaaaaaaaaaaaaa);", 6036 Style); 6037 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n" 6038 " aaaaaaaaaaaaaaaaaaaaaaaaaaa :\n" 6039 " aaaaaaaaaaaaaaaaaaaaaaaaaaa;", 6040 Style); 6041 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaa =\n" 6042 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n" 6043 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n" 6044 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;", 6045 Style); 6046 verifyFormat( 6047 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n" 6048 " aaaaaaaaaaaaaaa :\n" 6049 " aaaaaaaaaaaaaaa;", 6050 Style); 6051 verifyFormat("f(aaaaaaaaaaaaaaaa == // force break\n" 6052 " aaaaaaaaa ?\n" 6053 " b :\n" 6054 " c);", 6055 Style); 6056 verifyFormat("unsigned Indent =\n" 6057 " format(TheLine.First,\n" 6058 " IndentForLevel[TheLine.Level] >= 0 ?\n" 6059 " IndentForLevel[TheLine.Level] :\n" 6060 " TheLine * 2,\n" 6061 " TheLine.InPPDirective, PreviousEndOfLineColumn);", 6062 Style); 6063 verifyFormat("bool aaaaaa = aaaaaaaaaaaaa ? //\n" 6064 " aaaaaaaaaaaaaaa :\n" 6065 " bbbbbbbbbbbbbbb ? //\n" 6066 " ccccccccccccccc :\n" 6067 " ddddddddddddddd;", 6068 Style); 6069 verifyFormat("bool aaaaaa = aaaaaaaaaaaaa ? //\n" 6070 " aaaaaaaaaaaaaaa :\n" 6071 " (bbbbbbbbbbbbbbb ? //\n" 6072 " ccccccccccccccc :\n" 6073 " ddddddddddddddd);", 6074 Style); 6075 verifyFormat("int i = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n" 6076 " /*bbbbbbbbbbbbbbb=*/bbbbbbbbbbbbbbbbbbbbbbbbb :\n" 6077 " ccccccccccccccccccccccccccc;", 6078 Style); 6079 verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n" 6080 " aaaaa :\n" 6081 " bbbbbbbbbbbbbbb + cccccccccccccccc;", 6082 Style); 6083 } 6084 6085 TEST_F(FormatTest, DeclarationsOfMultipleVariables) { 6086 verifyFormat("bool aaaaaaaaaaaaaaaaa = aaaaaa->aaaaaaaaaaaaaaaaa(),\n" 6087 " aaaaaaaaaaa = aaaaaa->aaaaaaaaaaa();"); 6088 verifyFormat("bool a = true, b = false;"); 6089 6090 verifyFormat("bool aaaaaaaaaaaaaaaaaaaaaaaaa =\n" 6091 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaa),\n" 6092 " bbbbbbbbbbbbbbbbbbbbbbbbb =\n" 6093 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(bbbbbbbbbbbbbbbb);"); 6094 verifyFormat( 6095 "bool aaaaaaaaaaaaaaaaaaaaa =\n" 6096 " bbbbbbbbbbbbbbbbbbbbbbbbbbbb && cccccccccccccccccccccccccccc,\n" 6097 " d = e && f;"); 6098 verifyFormat("aaaaaaaaa a = aaaaaaaaaaaaaaaaaaaa, b = bbbbbbbbbbbbbbbbbbbb,\n" 6099 " c = cccccccccccccccccccc, d = dddddddddddddddddddd;"); 6100 verifyFormat("aaaaaaaaa *a = aaaaaaaaaaaaaaaaaaa, *b = bbbbbbbbbbbbbbbbbbb,\n" 6101 " *c = ccccccccccccccccccc, *d = ddddddddddddddddddd;"); 6102 verifyFormat("aaaaaaaaa ***a = aaaaaaaaaaaaaaaaaaa, ***b = bbbbbbbbbbbbbbb,\n" 6103 " ***c = ccccccccccccccccccc, ***d = ddddddddddddddd;"); 6104 6105 FormatStyle Style = getGoogleStyle(); 6106 Style.PointerAlignment = FormatStyle::PAS_Left; 6107 Style.DerivePointerAlignment = false; 6108 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6109 " *aaaaaaaaaaaaaaaaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaa,\n" 6110 " *b = bbbbbbbbbbbbbbbbbbb;", 6111 Style); 6112 verifyFormat("aaaaaaaaa *a = aaaaaaaaaaaaaaaaaaa, *b = bbbbbbbbbbbbbbbbbbb,\n" 6113 " *b = bbbbbbbbbbbbbbbbbbb, *d = ddddddddddddddddddd;", 6114 Style); 6115 verifyFormat("vector<int*> a, b;", Style); 6116 verifyFormat("for (int *p, *q; p != q; p = p->next) {\n}", Style); 6117 } 6118 6119 TEST_F(FormatTest, ConditionalExpressionsInBrackets) { 6120 verifyFormat("arr[foo ? bar : baz];"); 6121 verifyFormat("f()[foo ? bar : baz];"); 6122 verifyFormat("(a + b)[foo ? bar : baz];"); 6123 verifyFormat("arr[foo ? (4 > 5 ? 4 : 5) : 5 < 5 ? 5 : 7];"); 6124 } 6125 6126 TEST_F(FormatTest, AlignsStringLiterals) { 6127 verifyFormat("loooooooooooooooooooooooooongFunction(\"short literal \"\n" 6128 " \"short literal\");"); 6129 verifyFormat( 6130 "looooooooooooooooooooooooongFunction(\n" 6131 " \"short literal\"\n" 6132 " \"looooooooooooooooooooooooooooooooooooooooooooooooong literal\");"); 6133 verifyFormat("someFunction(\"Always break between multi-line\"\n" 6134 " \" string literals\",\n" 6135 " and, other, parameters);"); 6136 EXPECT_EQ("fun + \"1243\" /* comment */\n" 6137 " \"5678\";", 6138 format("fun + \"1243\" /* comment */\n" 6139 " \"5678\";", 6140 getLLVMStyleWithColumns(28))); 6141 EXPECT_EQ( 6142 "aaaaaa = \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n" 6143 " \"aaaaaaaaaaaaaaaaaaaaa\"\n" 6144 " \"aaaaaaaaaaaaaaaa\";", 6145 format("aaaaaa =" 6146 "\"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaa " 6147 "aaaaaaaaaaaaaaaaaaaaa\" " 6148 "\"aaaaaaaaaaaaaaaa\";")); 6149 verifyFormat("a = a + \"a\"\n" 6150 " \"a\"\n" 6151 " \"a\";"); 6152 verifyFormat("f(\"a\", \"b\"\n" 6153 " \"c\");"); 6154 6155 verifyFormat( 6156 "#define LL_FORMAT \"ll\"\n" 6157 "printf(\"aaaaa: %d, bbbbbb: %\" LL_FORMAT \"d, cccccccc: %\" LL_FORMAT\n" 6158 " \"d, ddddddddd: %\" LL_FORMAT \"d\");"); 6159 6160 verifyFormat("#define A(X) \\\n" 6161 " \"aaaaa\" #X \"bbbbbb\" \\\n" 6162 " \"ccccc\"", 6163 getLLVMStyleWithColumns(23)); 6164 verifyFormat("#define A \"def\"\n" 6165 "f(\"abc\" A \"ghi\"\n" 6166 " \"jkl\");"); 6167 6168 verifyFormat("f(L\"a\"\n" 6169 " L\"b\");"); 6170 verifyFormat("#define A(X) \\\n" 6171 " L\"aaaaa\" #X L\"bbbbbb\" \\\n" 6172 " L\"ccccc\"", 6173 getLLVMStyleWithColumns(25)); 6174 6175 verifyFormat("f(@\"a\"\n" 6176 " @\"b\");"); 6177 verifyFormat("NSString s = @\"a\"\n" 6178 " @\"b\"\n" 6179 " @\"c\";"); 6180 verifyFormat("NSString s = @\"a\"\n" 6181 " \"b\"\n" 6182 " \"c\";"); 6183 } 6184 6185 TEST_F(FormatTest, ReturnTypeBreakingStyle) { 6186 FormatStyle Style = getLLVMStyle(); 6187 // No declarations or definitions should be moved to own line. 6188 Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_None; 6189 verifyFormat("class A {\n" 6190 " int f() { return 1; }\n" 6191 " int g();\n" 6192 "};\n" 6193 "int f() { return 1; }\n" 6194 "int g();\n", 6195 Style); 6196 6197 // All declarations and definitions should have the return type moved to its 6198 // own 6199 // line. 6200 Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_All; 6201 verifyFormat("class E {\n" 6202 " int\n" 6203 " f() {\n" 6204 " return 1;\n" 6205 " }\n" 6206 " int\n" 6207 " g();\n" 6208 "};\n" 6209 "int\n" 6210 "f() {\n" 6211 " return 1;\n" 6212 "}\n" 6213 "int\n" 6214 "g();\n", 6215 Style); 6216 6217 // Top-level definitions, and no kinds of declarations should have the 6218 // return type moved to its own line. 6219 Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_TopLevelDefinitions; 6220 verifyFormat("class B {\n" 6221 " int f() { return 1; }\n" 6222 " int g();\n" 6223 "};\n" 6224 "int\n" 6225 "f() {\n" 6226 " return 1;\n" 6227 "}\n" 6228 "int g();\n", 6229 Style); 6230 6231 // Top-level definitions and declarations should have the return type moved 6232 // to its own line. 6233 Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_TopLevel; 6234 verifyFormat("class C {\n" 6235 " int f() { return 1; }\n" 6236 " int g();\n" 6237 "};\n" 6238 "int\n" 6239 "f() {\n" 6240 " return 1;\n" 6241 "}\n" 6242 "int\n" 6243 "g();\n", 6244 Style); 6245 6246 // All definitions should have the return type moved to its own line, but no 6247 // kinds of declarations. 6248 Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_AllDefinitions; 6249 verifyFormat("class D {\n" 6250 " int\n" 6251 " f() {\n" 6252 " return 1;\n" 6253 " }\n" 6254 " int g();\n" 6255 "};\n" 6256 "int\n" 6257 "f() {\n" 6258 " return 1;\n" 6259 "}\n" 6260 "int g();\n", 6261 Style); 6262 verifyFormat("const char *\n" 6263 "f(void) {\n" // Break here. 6264 " return \"\";\n" 6265 "}\n" 6266 "const char *bar(void);\n", // No break here. 6267 Style); 6268 verifyFormat("template <class T>\n" 6269 "T *\n" 6270 "f(T &c) {\n" // Break here. 6271 " return NULL;\n" 6272 "}\n" 6273 "template <class T> T *f(T &c);\n", // No break here. 6274 Style); 6275 verifyFormat("class C {\n" 6276 " int\n" 6277 " operator+() {\n" 6278 " return 1;\n" 6279 " }\n" 6280 " int\n" 6281 " operator()() {\n" 6282 " return 1;\n" 6283 " }\n" 6284 "};\n", 6285 Style); 6286 verifyFormat("void\n" 6287 "A::operator()() {}\n" 6288 "void\n" 6289 "A::operator>>() {}\n" 6290 "void\n" 6291 "A::operator+() {}\n" 6292 "void\n" 6293 "A::operator*() {}\n" 6294 "void\n" 6295 "A::operator->() {}\n" 6296 "void\n" 6297 "A::operator void *() {}\n" 6298 "void\n" 6299 "A::operator void &() {}\n" 6300 "void\n" 6301 "A::operator void &&() {}\n" 6302 "void\n" 6303 "A::operator char *() {}\n" 6304 "void\n" 6305 "A::operator[]() {}\n" 6306 "void\n" 6307 "A::operator!() {}\n" 6308 "void\n" 6309 "A::operator**() {}\n" 6310 "void\n" 6311 "A::operator<Foo> *() {}\n" 6312 "void\n" 6313 "A::operator<Foo> **() {}\n" 6314 "void\n" 6315 "A::operator<Foo> &() {}\n" 6316 "void\n" 6317 "A::operator void **() {}\n", 6318 Style); 6319 verifyFormat("constexpr auto\n" 6320 "operator()() const -> reference {}\n" 6321 "constexpr auto\n" 6322 "operator>>() const -> reference {}\n" 6323 "constexpr auto\n" 6324 "operator+() const -> reference {}\n" 6325 "constexpr auto\n" 6326 "operator*() const -> reference {}\n" 6327 "constexpr auto\n" 6328 "operator->() const -> reference {}\n" 6329 "constexpr auto\n" 6330 "operator++() const -> reference {}\n" 6331 "constexpr auto\n" 6332 "operator void *() const -> reference {}\n" 6333 "constexpr auto\n" 6334 "operator void **() const -> reference {}\n" 6335 "constexpr auto\n" 6336 "operator void *() const -> reference {}\n" 6337 "constexpr auto\n" 6338 "operator void &() const -> reference {}\n" 6339 "constexpr auto\n" 6340 "operator void &&() const -> reference {}\n" 6341 "constexpr auto\n" 6342 "operator char *() const -> reference {}\n" 6343 "constexpr auto\n" 6344 "operator!() const -> reference {}\n" 6345 "constexpr auto\n" 6346 "operator[]() const -> reference {}\n", 6347 Style); 6348 verifyFormat("void *operator new(std::size_t s);", // No break here. 6349 Style); 6350 verifyFormat("void *\n" 6351 "operator new(std::size_t s) {}", 6352 Style); 6353 verifyFormat("void *\n" 6354 "operator delete[](void *ptr) {}", 6355 Style); 6356 Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup; 6357 verifyFormat("const char *\n" 6358 "f(void)\n" // Break here. 6359 "{\n" 6360 " return \"\";\n" 6361 "}\n" 6362 "const char *bar(void);\n", // No break here. 6363 Style); 6364 verifyFormat("template <class T>\n" 6365 "T *\n" // Problem here: no line break 6366 "f(T &c)\n" // Break here. 6367 "{\n" 6368 " return NULL;\n" 6369 "}\n" 6370 "template <class T> T *f(T &c);\n", // No break here. 6371 Style); 6372 verifyFormat("int\n" 6373 "foo(A<bool> a)\n" 6374 "{\n" 6375 " return a;\n" 6376 "}\n", 6377 Style); 6378 verifyFormat("int\n" 6379 "foo(A<8> a)\n" 6380 "{\n" 6381 " return a;\n" 6382 "}\n", 6383 Style); 6384 verifyFormat("int\n" 6385 "foo(A<B<bool>, 8> a)\n" 6386 "{\n" 6387 " return a;\n" 6388 "}\n", 6389 Style); 6390 verifyFormat("int\n" 6391 "foo(A<B<8>, bool> a)\n" 6392 "{\n" 6393 " return a;\n" 6394 "}\n", 6395 Style); 6396 verifyFormat("int\n" 6397 "foo(A<B<bool>, bool> a)\n" 6398 "{\n" 6399 " return a;\n" 6400 "}\n", 6401 Style); 6402 verifyFormat("int\n" 6403 "foo(A<B<8>, 8> a)\n" 6404 "{\n" 6405 " return a;\n" 6406 "}\n", 6407 Style); 6408 6409 Style = getGNUStyle(); 6410 6411 // Test for comments at the end of function declarations. 6412 verifyFormat("void\n" 6413 "foo (int a, /*abc*/ int b) // def\n" 6414 "{\n" 6415 "}\n", 6416 Style); 6417 6418 verifyFormat("void\n" 6419 "foo (int a, /* abc */ int b) /* def */\n" 6420 "{\n" 6421 "}\n", 6422 Style); 6423 6424 // Definitions that should not break after return type 6425 verifyFormat("void foo (int a, int b); // def\n", Style); 6426 verifyFormat("void foo (int a, int b); /* def */\n", Style); 6427 verifyFormat("void foo (int a, int b);\n", Style); 6428 } 6429 6430 TEST_F(FormatTest, AlwaysBreakBeforeMultilineStrings) { 6431 FormatStyle NoBreak = getLLVMStyle(); 6432 NoBreak.AlwaysBreakBeforeMultilineStrings = false; 6433 FormatStyle Break = getLLVMStyle(); 6434 Break.AlwaysBreakBeforeMultilineStrings = true; 6435 verifyFormat("aaaa = \"bbbb\"\n" 6436 " \"cccc\";", 6437 NoBreak); 6438 verifyFormat("aaaa =\n" 6439 " \"bbbb\"\n" 6440 " \"cccc\";", 6441 Break); 6442 verifyFormat("aaaa(\"bbbb\"\n" 6443 " \"cccc\");", 6444 NoBreak); 6445 verifyFormat("aaaa(\n" 6446 " \"bbbb\"\n" 6447 " \"cccc\");", 6448 Break); 6449 verifyFormat("aaaa(qqq, \"bbbb\"\n" 6450 " \"cccc\");", 6451 NoBreak); 6452 verifyFormat("aaaa(qqq,\n" 6453 " \"bbbb\"\n" 6454 " \"cccc\");", 6455 Break); 6456 verifyFormat("aaaa(qqq,\n" 6457 " L\"bbbb\"\n" 6458 " L\"cccc\");", 6459 Break); 6460 verifyFormat("aaaaa(aaaaaa, aaaaaaa(\"aaaa\"\n" 6461 " \"bbbb\"));", 6462 Break); 6463 verifyFormat("string s = someFunction(\n" 6464 " \"abc\"\n" 6465 " \"abc\");", 6466 Break); 6467 6468 // As we break before unary operators, breaking right after them is bad. 6469 verifyFormat("string foo = abc ? \"x\"\n" 6470 " \"blah blah blah blah blah blah\"\n" 6471 " : \"y\";", 6472 Break); 6473 6474 // Don't break if there is no column gain. 6475 verifyFormat("f(\"aaaa\"\n" 6476 " \"bbbb\");", 6477 Break); 6478 6479 // Treat literals with escaped newlines like multi-line string literals. 6480 EXPECT_EQ("x = \"a\\\n" 6481 "b\\\n" 6482 "c\";", 6483 format("x = \"a\\\n" 6484 "b\\\n" 6485 "c\";", 6486 NoBreak)); 6487 EXPECT_EQ("xxxx =\n" 6488 " \"a\\\n" 6489 "b\\\n" 6490 "c\";", 6491 format("xxxx = \"a\\\n" 6492 "b\\\n" 6493 "c\";", 6494 Break)); 6495 6496 EXPECT_EQ("NSString *const kString =\n" 6497 " @\"aaaa\"\n" 6498 " @\"bbbb\";", 6499 format("NSString *const kString = @\"aaaa\"\n" 6500 "@\"bbbb\";", 6501 Break)); 6502 6503 Break.ColumnLimit = 0; 6504 verifyFormat("const char *hello = \"hello llvm\";", Break); 6505 } 6506 6507 TEST_F(FormatTest, AlignsPipes) { 6508 verifyFormat( 6509 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6510 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6511 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 6512 verifyFormat( 6513 "aaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaa\n" 6514 " << aaaaaaaaaaaaaaaaaaaa;"); 6515 verifyFormat( 6516 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6517 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 6518 verifyFormat( 6519 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 6520 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 6521 verifyFormat( 6522 "llvm::outs() << \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"\n" 6523 " \"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\"\n" 6524 " << \"ccccccccccccccccccccccccccccccccccccccccccccccccc\";"); 6525 verifyFormat( 6526 "aaaaaaaa << (aaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6527 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 6528 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 6529 verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6530 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 6531 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 6532 " << bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;"); 6533 verifyFormat("llvm::errs() << \"aaaaaaaaaaaaaaaaaaaaaaa: \"\n" 6534 " << aaaaaaaaaaaaaaaaa(aaaaaaaa, aaaaaaaaaaa);"); 6535 verifyFormat( 6536 "llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6537 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 6538 verifyFormat( 6539 "auto Diag = diag() << aaaaaaaaaaaaaaaa(aaaaaaaaaaaa, aaaaaaaaaaaaa,\n" 6540 " aaaaaaaaaaaaaaaaaaaaaaaaaa);"); 6541 6542 verifyFormat("llvm::outs() << \"aaaaaaaaaaaaaaaa: \"\n" 6543 " << aaaaaaaa.aaaaaaaaaaaa(aaa)->aaaaaaaaaaaaaa();"); 6544 verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6545 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 6546 " aaaaaaaaaaaaaaaaaaaaa)\n" 6547 " << aaaaaaaaaaaaaaaaaaaaaaaaaa;"); 6548 verifyFormat("LOG_IF(aaa == //\n" 6549 " bbb)\n" 6550 " << a << b;"); 6551 6552 // But sometimes, breaking before the first "<<" is desirable. 6553 verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaa, aaaaaaaa)\n" 6554 " << aaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaa);"); 6555 verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbb)\n" 6556 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6557 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 6558 verifyFormat("SemaRef.Diag(Loc, diag::note_for_range_begin_end)\n" 6559 " << BEF << IsTemplate << Description << E->getType();"); 6560 verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaa, aaaaaaaa)\n" 6561 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6562 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 6563 verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaa, aaaaaaaa)\n" 6564 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6565 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 6566 " << aaa;"); 6567 6568 verifyFormat( 6569 "llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6570 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 6571 6572 // Incomplete string literal. 6573 EXPECT_EQ("llvm::errs() << \"\n" 6574 " << a;", 6575 format("llvm::errs() << \"\n<<a;")); 6576 6577 verifyFormat("void f() {\n" 6578 " CHECK_EQ(aaaa, (*bbbbbbbbb)->cccccc)\n" 6579 " << \"qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\";\n" 6580 "}"); 6581 6582 // Handle 'endl'. 6583 verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaa << endl\n" 6584 " << bbbbbbbbbbbbbbbbbbbbbb << endl;"); 6585 verifyFormat("llvm::errs() << endl << bbbbbbbbbbbbbbbbbbbbbb << endl;"); 6586 6587 // Handle '\n'. 6588 verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaa << \"\\n\"\n" 6589 " << bbbbbbbbbbbbbbbbbbbbbb << \"\\n\";"); 6590 verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaa << \'\\n\'\n" 6591 " << bbbbbbbbbbbbbbbbbbbbbb << \'\\n\';"); 6592 verifyFormat("llvm::errs() << aaaa << \"aaaaaaaaaaaaaaaaaa\\n\"\n" 6593 " << bbbb << \"bbbbbbbbbbbbbbbbbb\\n\";"); 6594 verifyFormat("llvm::errs() << \"\\n\" << bbbbbbbbbbbbbbbbbbbbbb << \"\\n\";"); 6595 } 6596 6597 TEST_F(FormatTest, KeepStringLabelValuePairsOnALine) { 6598 verifyFormat("return out << \"somepacket = {\\n\"\n" 6599 " << \" aaaaaa = \" << pkt.aaaaaa << \"\\n\"\n" 6600 " << \" bbbb = \" << pkt.bbbb << \"\\n\"\n" 6601 " << \" cccccc = \" << pkt.cccccc << \"\\n\"\n" 6602 " << \" ddd = [\" << pkt.ddd << \"]\\n\"\n" 6603 " << \"}\";"); 6604 6605 verifyFormat("llvm::outs() << \"aaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaa\n" 6606 " << \"aaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaa\n" 6607 " << \"aaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaa;"); 6608 verifyFormat( 6609 "llvm::outs() << \"aaaaaaaaaaaaaaaaa = \" << aaaaaaaaaaaaaaaaa\n" 6610 " << \"bbbbbbbbbbbbbbbbb = \" << bbbbbbbbbbbbbbbbb\n" 6611 " << \"ccccccccccccccccc = \" << ccccccccccccccccc\n" 6612 " << \"ddddddddddddddddd = \" << ddddddddddddddddd\n" 6613 " << \"eeeeeeeeeeeeeeeee = \" << eeeeeeeeeeeeeeeee;"); 6614 verifyFormat("llvm::outs() << aaaaaaaaaaaaaaaaaaaaaaaa << \"=\"\n" 6615 " << bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;"); 6616 verifyFormat( 6617 "void f() {\n" 6618 " llvm::outs() << \"aaaaaaaaaaaaaaaaaaaa: \"\n" 6619 " << aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n" 6620 "}"); 6621 6622 // Breaking before the first "<<" is generally not desirable. 6623 verifyFormat( 6624 "llvm::errs()\n" 6625 " << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6626 " << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6627 " << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6628 " << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;", 6629 getLLVMStyleWithColumns(70)); 6630 verifyFormat("llvm::errs() << \"aaaaaaaaaaaaaaaaaaa: \"\n" 6631 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6632 " << \"aaaaaaaaaaaaaaaaaaa: \"\n" 6633 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6634 " << \"aaaaaaaaaaaaaaaaaaa: \"\n" 6635 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;", 6636 getLLVMStyleWithColumns(70)); 6637 6638 verifyFormat("string v = \"aaaaaaaaaaaaaaaa: \" + aaaaaaaaaaaaaaaa +\n" 6639 " \"aaaaaaaaaaaaaaaa: \" + aaaaaaaaaaaaaaaa +\n" 6640 " \"aaaaaaaaaaaaaaaa: \" + aaaaaaaaaaaaaaaa;"); 6641 verifyFormat("string v = StrCat(\"aaaaaaaaaaaaaaaa: \", aaaaaaaaaaaaaaaa,\n" 6642 " \"aaaaaaaaaaaaaaaa: \", aaaaaaaaaaaaaaaa,\n" 6643 " \"aaaaaaaaaaaaaaaa: \", aaaaaaaaaaaaaaaa);"); 6644 verifyFormat("string v = \"aaaaaaaaaaaaaaaa: \" +\n" 6645 " (aaaa + aaaa);", 6646 getLLVMStyleWithColumns(40)); 6647 verifyFormat("string v = StrCat(\"aaaaaaaaaaaa: \" +\n" 6648 " (aaaaaaa + aaaaa));", 6649 getLLVMStyleWithColumns(40)); 6650 verifyFormat( 6651 "string v = StrCat(\"aaaaaaaaaaaaaaaaaaaaaaaaaaa: \",\n" 6652 " SomeFunction(aaaaaaaaaaaa, aaaaaaaa.aaaaaaa),\n" 6653 " bbbbbbbbbbbbbbbbbbbbbbb);"); 6654 } 6655 6656 TEST_F(FormatTest, UnderstandsEquals) { 6657 verifyFormat( 6658 "aaaaaaaaaaaaaaaaa =\n" 6659 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 6660 verifyFormat( 6661 "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n" 6662 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}"); 6663 verifyFormat( 6664 "if (a) {\n" 6665 " f();\n" 6666 "} else if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n" 6667 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n" 6668 "}"); 6669 6670 verifyFormat("if (int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n" 6671 " 100000000 + 10000000) {\n}"); 6672 } 6673 6674 TEST_F(FormatTest, WrapsAtFunctionCallsIfNecessary) { 6675 verifyFormat("LoooooooooooooooooooooooooooooooooooooongObject\n" 6676 " .looooooooooooooooooooooooooooooooooooooongFunction();"); 6677 6678 verifyFormat("LoooooooooooooooooooooooooooooooooooooongObject\n" 6679 " ->looooooooooooooooooooooooooooooooooooooongFunction();"); 6680 6681 verifyFormat( 6682 "LooooooooooooooooooooooooooooooooongObject->shortFunction(Parameter1,\n" 6683 " Parameter2);"); 6684 6685 verifyFormat( 6686 "ShortObject->shortFunction(\n" 6687 " LooooooooooooooooooooooooooooooooooooooooooooooongParameter1,\n" 6688 " LooooooooooooooooooooooooooooooooooooooooooooooongParameter2);"); 6689 6690 verifyFormat("loooooooooooooongFunction(\n" 6691 " LoooooooooooooongObject->looooooooooooooooongFunction());"); 6692 6693 verifyFormat( 6694 "function(LoooooooooooooooooooooooooooooooooooongObject\n" 6695 " ->loooooooooooooooooooooooooooooooooooooooongFunction());"); 6696 6697 verifyFormat("EXPECT_CALL(SomeObject, SomeFunction(Parameter))\n" 6698 " .WillRepeatedly(Return(SomeValue));"); 6699 verifyFormat("void f() {\n" 6700 " EXPECT_CALL(SomeObject, SomeFunction(Parameter))\n" 6701 " .Times(2)\n" 6702 " .WillRepeatedly(Return(SomeValue));\n" 6703 "}"); 6704 verifyFormat("SomeMap[std::pair(aaaaaaaaaaaa, bbbbbbbbbbbbbbb)].insert(\n" 6705 " ccccccccccccccccccccccc);"); 6706 verifyFormat("aaaaa(aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 6707 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 6708 " .aaaaa(aaaaa),\n" 6709 " aaaaaaaaaaaaaaaaaaaaa);"); 6710 verifyFormat("void f() {\n" 6711 " aaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6712 " aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa)->aaaaaaaaa());\n" 6713 "}"); 6714 verifyFormat("aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 6715 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 6716 " .aaaaaaaaaaaaaaa(aa(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 6717 " aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 6718 " aaaaaaaaaaaaaaaaaaaaaaaaaaa));"); 6719 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6720 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6721 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6722 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()) {\n" 6723 "}"); 6724 6725 // Here, it is not necessary to wrap at "." or "->". 6726 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaa) ||\n" 6727 " aaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}"); 6728 verifyFormat( 6729 "aaaaaaaaaaa->aaaaaaaaa(\n" 6730 " aaaaaaaaaaaaaaaaaaaaaaaaa,\n" 6731 " aaaaaaaaaaaaaaaaaa->aaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa));\n"); 6732 6733 verifyFormat( 6734 "aaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6735 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa().aaaaaaaaaaaaaaaaa());"); 6736 verifyFormat("a->aaaaaa()->aaaaaaaaaaa(aaaaaaaa()->aaaaaa()->aaaaa() *\n" 6737 " aaaaaaaaa()->aaaaaa()->aaaaa());"); 6738 verifyFormat("a->aaaaaa()->aaaaaaaaaaa(aaaaaaaa()->aaaaaa()->aaaaa() ||\n" 6739 " aaaaaaaaa()->aaaaaa()->aaaaa());"); 6740 6741 verifyFormat("aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 6742 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 6743 " .a();"); 6744 6745 FormatStyle NoBinPacking = getLLVMStyle(); 6746 NoBinPacking.BinPackParameters = false; 6747 verifyFormat("aaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa)\n" 6748 " .aaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa)\n" 6749 " .aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaa,\n" 6750 " aaaaaaaaaaaaaaaaaaa,\n" 6751 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 6752 NoBinPacking); 6753 6754 // If there is a subsequent call, change to hanging indentation. 6755 verifyFormat( 6756 "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6757 " aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa))\n" 6758 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 6759 verifyFormat( 6760 "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6761 " aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa));"); 6762 verifyFormat("aaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6763 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 6764 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 6765 verifyFormat("aaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6766 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 6767 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa());"); 6768 } 6769 6770 TEST_F(FormatTest, WrapsTemplateDeclarations) { 6771 verifyFormat("template <typename T>\n" 6772 "virtual void loooooooooooongFunction(int Param1, int Param2);"); 6773 verifyFormat("template <typename T>\n" 6774 "// T should be one of {A, B}.\n" 6775 "virtual void loooooooooooongFunction(int Param1, int Param2);"); 6776 verifyFormat( 6777 "template <typename T>\n" 6778 "using comment_to_xml_conversion = comment_to_xml_conversion<T, int>;"); 6779 verifyFormat("template <typename T>\n" 6780 "void f(int Paaaaaaaaaaaaaaaaaaaaaaaaaaaaaaram1,\n" 6781 " int Paaaaaaaaaaaaaaaaaaaaaaaaaaaaaaram2);"); 6782 verifyFormat( 6783 "template <typename T>\n" 6784 "void looooooooooooooooooooongFunction(int Paaaaaaaaaaaaaaaaaaaaram1,\n" 6785 " int Paaaaaaaaaaaaaaaaaaaaram2);"); 6786 verifyFormat( 6787 "template <typename T>\n" 6788 "aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaa,\n" 6789 " aaaaaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaaaaa,\n" 6790 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 6791 verifyFormat("template <typename T>\n" 6792 "void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6793 " int aaaaaaaaaaaaaaaaaaaaaa);"); 6794 verifyFormat( 6795 "template <typename T1, typename T2 = char, typename T3 = char,\n" 6796 " typename T4 = char>\n" 6797 "void f();"); 6798 verifyFormat("template <typename aaaaaaaaaaa, typename bbbbbbbbbbbbb,\n" 6799 " template <typename> class cccccccccccccccccccccc,\n" 6800 " typename ddddddddddddd>\n" 6801 "class C {};"); 6802 verifyFormat( 6803 "aaaaaaaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa>(\n" 6804 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 6805 6806 verifyFormat("void f() {\n" 6807 " a<aaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaa>(\n" 6808 " a(aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa));\n" 6809 "}"); 6810 6811 verifyFormat("template <typename T> class C {};"); 6812 verifyFormat("template <typename T> void f();"); 6813 verifyFormat("template <typename T> void f() {}"); 6814 verifyFormat( 6815 "aaaaaaaaaaaaa<aaaaaaaaaa, aaaaaaaaaaa,\n" 6816 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 6817 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa> *aaaa =\n" 6818 " new aaaaaaaaaaaaa<aaaaaaaaaa, aaaaaaaaaaa,\n" 6819 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 6820 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>(\n" 6821 " bbbbbbbbbbbbbbbbbbbbbbbb);", 6822 getLLVMStyleWithColumns(72)); 6823 EXPECT_EQ("static_cast<A< //\n" 6824 " B> *>(\n" 6825 "\n" 6826 ");", 6827 format("static_cast<A<//\n" 6828 " B>*>(\n" 6829 "\n" 6830 " );")); 6831 verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6832 " const typename aaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaa);"); 6833 6834 FormatStyle AlwaysBreak = getLLVMStyle(); 6835 AlwaysBreak.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes; 6836 verifyFormat("template <typename T>\nclass C {};", AlwaysBreak); 6837 verifyFormat("template <typename T>\nvoid f();", AlwaysBreak); 6838 verifyFormat("template <typename T>\nvoid f() {}", AlwaysBreak); 6839 verifyFormat("void aaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 6840 " bbbbbbbbbbbbbbbbbbbbbbbbbbbb>(\n" 6841 " ccccccccccccccccccccccccccccccccccccccccccccccc);"); 6842 verifyFormat("template <template <typename> class Fooooooo,\n" 6843 " template <typename> class Baaaaaaar>\n" 6844 "struct C {};", 6845 AlwaysBreak); 6846 verifyFormat("template <typename T> // T can be A, B or C.\n" 6847 "struct C {};", 6848 AlwaysBreak); 6849 verifyFormat("template <enum E> class A {\n" 6850 "public:\n" 6851 " E *f();\n" 6852 "};"); 6853 6854 FormatStyle NeverBreak = getLLVMStyle(); 6855 NeverBreak.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_No; 6856 verifyFormat("template <typename T> class C {};", NeverBreak); 6857 verifyFormat("template <typename T> void f();", NeverBreak); 6858 verifyFormat("template <typename T> void f() {}", NeverBreak); 6859 verifyFormat("template <typename T>\nvoid foo(aaaaaaaaaaaaaaaaaaaaaaaaaa " 6860 "bbbbbbbbbbbbbbbbbbbb) {}", 6861 NeverBreak); 6862 verifyFormat("void aaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 6863 " bbbbbbbbbbbbbbbbbbbbbbbbbbbb>(\n" 6864 " ccccccccccccccccccccccccccccccccccccccccccccccc);", 6865 NeverBreak); 6866 verifyFormat("template <template <typename> class Fooooooo,\n" 6867 " template <typename> class Baaaaaaar>\n" 6868 "struct C {};", 6869 NeverBreak); 6870 verifyFormat("template <typename T> // T can be A, B or C.\n" 6871 "struct C {};", 6872 NeverBreak); 6873 verifyFormat("template <enum E> class A {\n" 6874 "public:\n" 6875 " E *f();\n" 6876 "};", 6877 NeverBreak); 6878 NeverBreak.PenaltyBreakTemplateDeclaration = 100; 6879 verifyFormat("template <typename T> void\nfoo(aaaaaaaaaaaaaaaaaaaaaaaaaa " 6880 "bbbbbbbbbbbbbbbbbbbb) {}", 6881 NeverBreak); 6882 } 6883 6884 TEST_F(FormatTest, WrapsTemplateDeclarationsWithComments) { 6885 FormatStyle Style = getGoogleStyle(FormatStyle::LK_Cpp); 6886 Style.ColumnLimit = 60; 6887 EXPECT_EQ("// Baseline - no comments.\n" 6888 "template <\n" 6889 " typename aaaaaaaaaaaaaaaaaaaaaa<bbbbbbbbbbbb>::value>\n" 6890 "void f() {}", 6891 format("// Baseline - no comments.\n" 6892 "template <\n" 6893 " typename aaaaaaaaaaaaaaaaaaaaaa<bbbbbbbbbbbb>::value>\n" 6894 "void f() {}", 6895 Style)); 6896 6897 EXPECT_EQ("template <\n" 6898 " typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing\n" 6899 "void f() {}", 6900 format("template <\n" 6901 " typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing\n" 6902 "void f() {}", 6903 Style)); 6904 6905 EXPECT_EQ( 6906 "template <\n" 6907 " typename aaaaaaaaaa<bbbbbbbbbbbb>::value> /* line */\n" 6908 "void f() {}", 6909 format("template <typename aaaaaaaaaa<bbbbbbbbbbbb>::value> /* line */\n" 6910 "void f() {}", 6911 Style)); 6912 6913 EXPECT_EQ( 6914 "template <\n" 6915 " typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing\n" 6916 " // multiline\n" 6917 "void f() {}", 6918 format("template <\n" 6919 " typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing\n" 6920 " // multiline\n" 6921 "void f() {}", 6922 Style)); 6923 6924 EXPECT_EQ( 6925 "template <typename aaaaaaaaaa<\n" 6926 " bbbbbbbbbbbb>::value> // trailing loooong\n" 6927 "void f() {}", 6928 format( 6929 "template <\n" 6930 " typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing loooong\n" 6931 "void f() {}", 6932 Style)); 6933 } 6934 6935 TEST_F(FormatTest, WrapsTemplateParameters) { 6936 FormatStyle Style = getLLVMStyle(); 6937 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 6938 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None; 6939 verifyFormat( 6940 "template <typename... a> struct q {};\n" 6941 "extern q<aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa,\n" 6942 " aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa>\n" 6943 " y;", 6944 Style); 6945 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 6946 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 6947 verifyFormat( 6948 "template <typename... a> struct r {};\n" 6949 "extern r<aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa,\n" 6950 " aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa>\n" 6951 " y;", 6952 Style); 6953 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 6954 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None; 6955 verifyFormat("template <typename... a> struct s {};\n" 6956 "extern s<\n" 6957 " aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, " 6958 "aaaaaaaaaaaaaaaaaaaaaa,\n" 6959 " aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, " 6960 "aaaaaaaaaaaaaaaaaaaaaa>\n" 6961 " y;", 6962 Style); 6963 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 6964 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 6965 verifyFormat("template <typename... a> struct t {};\n" 6966 "extern t<\n" 6967 " aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, " 6968 "aaaaaaaaaaaaaaaaaaaaaa,\n" 6969 " aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, " 6970 "aaaaaaaaaaaaaaaaaaaaaa>\n" 6971 " y;", 6972 Style); 6973 } 6974 6975 TEST_F(FormatTest, WrapsAtNestedNameSpecifiers) { 6976 verifyFormat( 6977 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n" 6978 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 6979 verifyFormat( 6980 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n" 6981 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6982 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa());"); 6983 6984 // FIXME: Should we have the extra indent after the second break? 6985 verifyFormat( 6986 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n" 6987 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n" 6988 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 6989 6990 verifyFormat( 6991 "aaaaaaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb::\n" 6992 " cccccccccccccccccccccccccccccccccccccccccccccc());"); 6993 6994 // Breaking at nested name specifiers is generally not desirable. 6995 verifyFormat( 6996 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6997 " aaaaaaaaaaaaaaaaaaaaaaa);"); 6998 6999 verifyFormat("aaaaaaaaaaaaaaaaaa(aaaaaaaa,\n" 7000 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n" 7001 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7002 " aaaaaaaaaaaaaaaaaaaaa);", 7003 getLLVMStyleWithColumns(74)); 7004 7005 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n" 7006 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7007 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 7008 } 7009 7010 TEST_F(FormatTest, UnderstandsTemplateParameters) { 7011 verifyFormat("A<int> a;"); 7012 verifyFormat("A<A<A<int>>> a;"); 7013 verifyFormat("A<A<A<int, 2>, 3>, 4> a;"); 7014 verifyFormat("bool x = a < 1 || 2 > a;"); 7015 verifyFormat("bool x = 5 < f<int>();"); 7016 verifyFormat("bool x = f<int>() > 5;"); 7017 verifyFormat("bool x = 5 < a<int>::x;"); 7018 verifyFormat("bool x = a < 4 ? a > 2 : false;"); 7019 verifyFormat("bool x = f() ? a < 2 : a > 2;"); 7020 7021 verifyGoogleFormat("A<A<int>> a;"); 7022 verifyGoogleFormat("A<A<A<int>>> a;"); 7023 verifyGoogleFormat("A<A<A<A<int>>>> a;"); 7024 verifyGoogleFormat("A<A<int> > a;"); 7025 verifyGoogleFormat("A<A<A<int> > > a;"); 7026 verifyGoogleFormat("A<A<A<A<int> > > > a;"); 7027 verifyGoogleFormat("A<::A<int>> a;"); 7028 verifyGoogleFormat("A<::A> a;"); 7029 verifyGoogleFormat("A< ::A> a;"); 7030 verifyGoogleFormat("A< ::A<int> > a;"); 7031 EXPECT_EQ("A<A<A<A>>> a;", format("A<A<A<A> >> a;", getGoogleStyle())); 7032 EXPECT_EQ("A<A<A<A>>> a;", format("A<A<A<A>> > a;", getGoogleStyle())); 7033 EXPECT_EQ("A<::A<int>> a;", format("A< ::A<int>> a;", getGoogleStyle())); 7034 EXPECT_EQ("A<::A<int>> a;", format("A<::A<int> > a;", getGoogleStyle())); 7035 EXPECT_EQ("auto x = [] { A<A<A<A>>> a; };", 7036 format("auto x=[]{A<A<A<A> >> a;};", getGoogleStyle())); 7037 7038 verifyFormat("A<A<int>> a;", getChromiumStyle(FormatStyle::LK_Cpp)); 7039 7040 // template closer followed by a token that starts with > or = 7041 verifyFormat("bool b = a<1> > 1;"); 7042 verifyFormat("bool b = a<1> >= 1;"); 7043 verifyFormat("int i = a<1> >> 1;"); 7044 FormatStyle Style = getLLVMStyle(); 7045 Style.SpaceBeforeAssignmentOperators = false; 7046 verifyFormat("bool b= a<1> == 1;", Style); 7047 verifyFormat("a<int> = 1;", Style); 7048 verifyFormat("a<int> >>= 1;", Style); 7049 7050 verifyFormat("test >> a >> b;"); 7051 verifyFormat("test << a >> b;"); 7052 7053 verifyFormat("f<int>();"); 7054 verifyFormat("template <typename T> void f() {}"); 7055 verifyFormat("struct A<std::enable_if<sizeof(T2) < sizeof(int32)>::type>;"); 7056 verifyFormat("struct A<std::enable_if<sizeof(T2) ? sizeof(int32) : " 7057 "sizeof(char)>::type>;"); 7058 verifyFormat("template <class T> struct S<std::is_arithmetic<T>{}> {};"); 7059 verifyFormat("f(a.operator()<A>());"); 7060 verifyFormat("f(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7061 " .template operator()<A>());", 7062 getLLVMStyleWithColumns(35)); 7063 7064 // Not template parameters. 7065 verifyFormat("return a < b && c > d;"); 7066 verifyFormat("void f() {\n" 7067 " while (a < b && c > d) {\n" 7068 " }\n" 7069 "}"); 7070 verifyFormat("template <typename... Types>\n" 7071 "typename enable_if<0 < sizeof...(Types)>::type Foo() {}"); 7072 7073 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7074 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaa >> aaaaa);", 7075 getLLVMStyleWithColumns(60)); 7076 verifyFormat("static_assert(is_convertible<A &&, B>::value, \"AAA\");"); 7077 verifyFormat("Constructor(A... a) : a_(X<A>{std::forward<A>(a)}...) {}"); 7078 verifyFormat("< < < < < < < < < < < < < < < < < < < < < < < < < < < < < <"); 7079 } 7080 7081 TEST_F(FormatTest, BitshiftOperatorWidth) { 7082 EXPECT_EQ("int a = 1 << 2; /* foo\n" 7083 " bar */", 7084 format("int a=1<<2; /* foo\n" 7085 " bar */")); 7086 7087 EXPECT_EQ("int b = 256 >> 1; /* foo\n" 7088 " bar */", 7089 format("int b =256>>1 ; /* foo\n" 7090 " bar */")); 7091 } 7092 7093 TEST_F(FormatTest, UnderstandsBinaryOperators) { 7094 verifyFormat("COMPARE(a, ==, b);"); 7095 verifyFormat("auto s = sizeof...(Ts) - 1;"); 7096 } 7097 7098 TEST_F(FormatTest, UnderstandsPointersToMembers) { 7099 verifyFormat("int A::*x;"); 7100 verifyFormat("int (S::*func)(void *);"); 7101 verifyFormat("void f() { int (S::*func)(void *); }"); 7102 verifyFormat("typedef bool *(Class::*Member)() const;"); 7103 verifyFormat("void f() {\n" 7104 " (a->*f)();\n" 7105 " a->*x;\n" 7106 " (a.*f)();\n" 7107 " ((*a).*f)();\n" 7108 " a.*x;\n" 7109 "}"); 7110 verifyFormat("void f() {\n" 7111 " (a->*aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)(\n" 7112 " aaaa, bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb);\n" 7113 "}"); 7114 verifyFormat( 7115 "(aaaaaaaaaa->*bbbbbbb)(\n" 7116 " aaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa));"); 7117 FormatStyle Style = getLLVMStyle(); 7118 Style.PointerAlignment = FormatStyle::PAS_Left; 7119 verifyFormat("typedef bool* (Class::*Member)() const;", Style); 7120 } 7121 7122 TEST_F(FormatTest, UnderstandsUnaryOperators) { 7123 verifyFormat("int a = -2;"); 7124 verifyFormat("f(-1, -2, -3);"); 7125 verifyFormat("a[-1] = 5;"); 7126 verifyFormat("int a = 5 + -2;"); 7127 verifyFormat("if (i == -1) {\n}"); 7128 verifyFormat("if (i != -1) {\n}"); 7129 verifyFormat("if (i > -1) {\n}"); 7130 verifyFormat("if (i < -1) {\n}"); 7131 verifyFormat("++(a->f());"); 7132 verifyFormat("--(a->f());"); 7133 verifyFormat("(a->f())++;"); 7134 verifyFormat("a[42]++;"); 7135 verifyFormat("if (!(a->f())) {\n}"); 7136 verifyFormat("if (!+i) {\n}"); 7137 verifyFormat("~&a;"); 7138 7139 verifyFormat("a-- > b;"); 7140 verifyFormat("b ? -a : c;"); 7141 verifyFormat("n * sizeof char16;"); 7142 verifyFormat("n * alignof char16;", getGoogleStyle()); 7143 verifyFormat("sizeof(char);"); 7144 verifyFormat("alignof(char);", getGoogleStyle()); 7145 7146 verifyFormat("return -1;"); 7147 verifyFormat("throw -1;"); 7148 verifyFormat("switch (a) {\n" 7149 "case -1:\n" 7150 " break;\n" 7151 "}"); 7152 verifyFormat("#define X -1"); 7153 verifyFormat("#define X -kConstant"); 7154 7155 verifyFormat("const NSPoint kBrowserFrameViewPatternOffset = {-5, +3};"); 7156 verifyFormat("const NSPoint kBrowserFrameViewPatternOffset = {+5, -3};"); 7157 7158 verifyFormat("int a = /* confusing comment */ -1;"); 7159 // FIXME: The space after 'i' is wrong, but hopefully, this is a rare case. 7160 verifyFormat("int a = i /* confusing comment */++;"); 7161 7162 verifyFormat("co_yield -1;"); 7163 verifyFormat("co_return -1;"); 7164 } 7165 7166 TEST_F(FormatTest, DoesNotIndentRelativeToUnaryOperators) { 7167 verifyFormat("if (!aaaaaaaaaa( // break\n" 7168 " aaaaa)) {\n" 7169 "}"); 7170 verifyFormat("aaaaaaaaaa(!aaaaaaaaaa( // break\n" 7171 " aaaaa));"); 7172 verifyFormat("*aaa = aaaaaaa( // break\n" 7173 " bbbbbb);"); 7174 } 7175 7176 TEST_F(FormatTest, UnderstandsOverloadedOperators) { 7177 verifyFormat("bool operator<();"); 7178 verifyFormat("bool operator>();"); 7179 verifyFormat("bool operator=();"); 7180 verifyFormat("bool operator==();"); 7181 verifyFormat("bool operator!=();"); 7182 verifyFormat("int operator+();"); 7183 verifyFormat("int operator++();"); 7184 verifyFormat("int operator++(int) volatile noexcept;"); 7185 verifyFormat("bool operator,();"); 7186 verifyFormat("bool operator();"); 7187 verifyFormat("bool operator()();"); 7188 verifyFormat("bool operator[]();"); 7189 verifyFormat("operator bool();"); 7190 verifyFormat("operator int();"); 7191 verifyFormat("operator void *();"); 7192 verifyFormat("operator SomeType<int>();"); 7193 verifyFormat("operator SomeType<int, int>();"); 7194 verifyFormat("operator SomeType<SomeType<int>>();"); 7195 verifyFormat("void *operator new(std::size_t size);"); 7196 verifyFormat("void *operator new[](std::size_t size);"); 7197 verifyFormat("void operator delete(void *ptr);"); 7198 verifyFormat("void operator delete[](void *ptr);"); 7199 verifyFormat("template <typename AAAAAAA, typename BBBBBBB>\n" 7200 "AAAAAAA operator/(const AAAAAAA &a, BBBBBBB &b);"); 7201 verifyFormat("aaaaaaaaaaaaaaaaaaaaaa operator,(\n" 7202 " aaaaaaaaaaaaaaaaaaaaa &aaaaaaaaaaaaaaaaaaaaaaaaaa) const;"); 7203 7204 verifyFormat( 7205 "ostream &operator<<(ostream &OutputStream,\n" 7206 " SomeReallyLongType WithSomeReallyLongValue);"); 7207 verifyFormat("bool operator<(const aaaaaaaaaaaaaaaaaaaaa &left,\n" 7208 " const aaaaaaaaaaaaaaaaaaaaa &right) {\n" 7209 " return left.group < right.group;\n" 7210 "}"); 7211 verifyFormat("SomeType &operator=(const SomeType &S);"); 7212 verifyFormat("f.template operator()<int>();"); 7213 7214 verifyGoogleFormat("operator void*();"); 7215 verifyGoogleFormat("operator SomeType<SomeType<int>>();"); 7216 verifyGoogleFormat("operator ::A();"); 7217 7218 verifyFormat("using A::operator+;"); 7219 verifyFormat("inline A operator^(const A &lhs, const A &rhs) {}\n" 7220 "int i;"); 7221 } 7222 7223 TEST_F(FormatTest, UnderstandsFunctionRefQualification) { 7224 verifyFormat("Deleted &operator=(const Deleted &) & = default;"); 7225 verifyFormat("Deleted &operator=(const Deleted &) && = delete;"); 7226 verifyFormat("SomeType MemberFunction(const Deleted &) & = delete;"); 7227 verifyFormat("SomeType MemberFunction(const Deleted &) && = delete;"); 7228 verifyFormat("Deleted &operator=(const Deleted &) &;"); 7229 verifyFormat("Deleted &operator=(const Deleted &) &&;"); 7230 verifyFormat("SomeType MemberFunction(const Deleted &) &;"); 7231 verifyFormat("SomeType MemberFunction(const Deleted &) &&;"); 7232 verifyFormat("SomeType MemberFunction(const Deleted &) && {}"); 7233 verifyFormat("SomeType MemberFunction(const Deleted &) && final {}"); 7234 verifyFormat("SomeType MemberFunction(const Deleted &) && override {}"); 7235 verifyFormat("void Fn(T const &) const &;"); 7236 verifyFormat("void Fn(T const volatile &&) const volatile &&;"); 7237 verifyFormat("template <typename T>\n" 7238 "void F(T) && = delete;", 7239 getGoogleStyle()); 7240 7241 FormatStyle AlignLeft = getLLVMStyle(); 7242 AlignLeft.PointerAlignment = FormatStyle::PAS_Left; 7243 verifyFormat("void A::b() && {}", AlignLeft); 7244 verifyFormat("Deleted& operator=(const Deleted&) & = default;", AlignLeft); 7245 verifyFormat("SomeType MemberFunction(const Deleted&) & = delete;", 7246 AlignLeft); 7247 verifyFormat("Deleted& operator=(const Deleted&) &;", AlignLeft); 7248 verifyFormat("SomeType MemberFunction(const Deleted&) &;", AlignLeft); 7249 verifyFormat("auto Function(T t) & -> void {}", AlignLeft); 7250 verifyFormat("auto Function(T... t) & -> void {}", AlignLeft); 7251 verifyFormat("auto Function(T) & -> void {}", AlignLeft); 7252 verifyFormat("auto Function(T) & -> void;", AlignLeft); 7253 verifyFormat("void Fn(T const&) const&;", AlignLeft); 7254 verifyFormat("void Fn(T const volatile&&) const volatile&&;", AlignLeft); 7255 7256 FormatStyle Spaces = getLLVMStyle(); 7257 Spaces.SpacesInCStyleCastParentheses = true; 7258 verifyFormat("Deleted &operator=(const Deleted &) & = default;", Spaces); 7259 verifyFormat("SomeType MemberFunction(const Deleted &) & = delete;", Spaces); 7260 verifyFormat("Deleted &operator=(const Deleted &) &;", Spaces); 7261 verifyFormat("SomeType MemberFunction(const Deleted &) &;", Spaces); 7262 7263 Spaces.SpacesInCStyleCastParentheses = false; 7264 Spaces.SpacesInParentheses = true; 7265 verifyFormat("Deleted &operator=( const Deleted & ) & = default;", Spaces); 7266 verifyFormat("SomeType MemberFunction( const Deleted & ) & = delete;", 7267 Spaces); 7268 verifyFormat("Deleted &operator=( const Deleted & ) &;", Spaces); 7269 verifyFormat("SomeType MemberFunction( const Deleted & ) &;", Spaces); 7270 7271 FormatStyle BreakTemplate = getLLVMStyle(); 7272 BreakTemplate.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes; 7273 7274 verifyFormat("struct f {\n" 7275 " template <class T>\n" 7276 " int &foo(const std::string &str) &noexcept {}\n" 7277 "};", 7278 BreakTemplate); 7279 7280 verifyFormat("struct f {\n" 7281 " template <class T>\n" 7282 " int &foo(const std::string &str) &&noexcept {}\n" 7283 "};", 7284 BreakTemplate); 7285 7286 verifyFormat("struct f {\n" 7287 " template <class T>\n" 7288 " int &foo(const std::string &str) const &noexcept {}\n" 7289 "};", 7290 BreakTemplate); 7291 7292 verifyFormat("struct f {\n" 7293 " template <class T>\n" 7294 " int &foo(const std::string &str) const &noexcept {}\n" 7295 "};", 7296 BreakTemplate); 7297 7298 verifyFormat("struct f {\n" 7299 " template <class T>\n" 7300 " auto foo(const std::string &str) &&noexcept -> int & {}\n" 7301 "};", 7302 BreakTemplate); 7303 7304 FormatStyle AlignLeftBreakTemplate = getLLVMStyle(); 7305 AlignLeftBreakTemplate.AlwaysBreakTemplateDeclarations = 7306 FormatStyle::BTDS_Yes; 7307 AlignLeftBreakTemplate.PointerAlignment = FormatStyle::PAS_Left; 7308 7309 verifyFormat("struct f {\n" 7310 " template <class T>\n" 7311 " int& foo(const std::string& str) & noexcept {}\n" 7312 "};", 7313 AlignLeftBreakTemplate); 7314 7315 verifyFormat("struct f {\n" 7316 " template <class T>\n" 7317 " int& foo(const std::string& str) && noexcept {}\n" 7318 "};", 7319 AlignLeftBreakTemplate); 7320 7321 verifyFormat("struct f {\n" 7322 " template <class T>\n" 7323 " int& foo(const std::string& str) const& noexcept {}\n" 7324 "};", 7325 AlignLeftBreakTemplate); 7326 7327 verifyFormat("struct f {\n" 7328 " template <class T>\n" 7329 " int& foo(const std::string& str) const&& noexcept {}\n" 7330 "};", 7331 AlignLeftBreakTemplate); 7332 7333 verifyFormat("struct f {\n" 7334 " template <class T>\n" 7335 " auto foo(const std::string& str) && noexcept -> int& {}\n" 7336 "};", 7337 AlignLeftBreakTemplate); 7338 7339 // The `&` in `Type&` should not be confused with a trailing `&` of 7340 // DEPRECATED(reason) member function. 7341 verifyFormat("struct f {\n" 7342 " template <class T>\n" 7343 " DEPRECATED(reason)\n" 7344 " Type &foo(arguments) {}\n" 7345 "};", 7346 BreakTemplate); 7347 7348 verifyFormat("struct f {\n" 7349 " template <class T>\n" 7350 " DEPRECATED(reason)\n" 7351 " Type& foo(arguments) {}\n" 7352 "};", 7353 AlignLeftBreakTemplate); 7354 7355 verifyFormat("void (*foopt)(int) = &func;"); 7356 } 7357 7358 TEST_F(FormatTest, UnderstandsNewAndDelete) { 7359 verifyFormat("void f() {\n" 7360 " A *a = new A;\n" 7361 " A *a = new (placement) A;\n" 7362 " delete a;\n" 7363 " delete (A *)a;\n" 7364 "}"); 7365 verifyFormat("new (aaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaa))\n" 7366 " typename aaaaaaaaaaaaaaaaaaaaaaaa();"); 7367 verifyFormat("auto aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n" 7368 " new (aaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaa))\n" 7369 " typename aaaaaaaaaaaaaaaaaaaaaaaa();"); 7370 verifyFormat("delete[] h->p;"); 7371 } 7372 7373 TEST_F(FormatTest, UnderstandsUsesOfStarAndAmp) { 7374 verifyFormat("int *f(int *a) {}"); 7375 verifyFormat("int main(int argc, char **argv) {}"); 7376 verifyFormat("Test::Test(int b) : a(b * b) {}"); 7377 verifyIndependentOfContext("f(a, *a);"); 7378 verifyFormat("void g() { f(*a); }"); 7379 verifyIndependentOfContext("int a = b * 10;"); 7380 verifyIndependentOfContext("int a = 10 * b;"); 7381 verifyIndependentOfContext("int a = b * c;"); 7382 verifyIndependentOfContext("int a += b * c;"); 7383 verifyIndependentOfContext("int a -= b * c;"); 7384 verifyIndependentOfContext("int a *= b * c;"); 7385 verifyIndependentOfContext("int a /= b * c;"); 7386 verifyIndependentOfContext("int a = *b;"); 7387 verifyIndependentOfContext("int a = *b * c;"); 7388 verifyIndependentOfContext("int a = b * *c;"); 7389 verifyIndependentOfContext("int a = b * (10);"); 7390 verifyIndependentOfContext("S << b * (10);"); 7391 verifyIndependentOfContext("return 10 * b;"); 7392 verifyIndependentOfContext("return *b * *c;"); 7393 verifyIndependentOfContext("return a & ~b;"); 7394 verifyIndependentOfContext("f(b ? *c : *d);"); 7395 verifyIndependentOfContext("int a = b ? *c : *d;"); 7396 verifyIndependentOfContext("*b = a;"); 7397 verifyIndependentOfContext("a * ~b;"); 7398 verifyIndependentOfContext("a * !b;"); 7399 verifyIndependentOfContext("a * +b;"); 7400 verifyIndependentOfContext("a * -b;"); 7401 verifyIndependentOfContext("a * ++b;"); 7402 verifyIndependentOfContext("a * --b;"); 7403 verifyIndependentOfContext("a[4] * b;"); 7404 verifyIndependentOfContext("a[a * a] = 1;"); 7405 verifyIndependentOfContext("f() * b;"); 7406 verifyIndependentOfContext("a * [self dostuff];"); 7407 verifyIndependentOfContext("int x = a * (a + b);"); 7408 verifyIndependentOfContext("(a *)(a + b);"); 7409 verifyIndependentOfContext("*(int *)(p & ~3UL) = 0;"); 7410 verifyIndependentOfContext("int *pa = (int *)&a;"); 7411 verifyIndependentOfContext("return sizeof(int **);"); 7412 verifyIndependentOfContext("return sizeof(int ******);"); 7413 verifyIndependentOfContext("return (int **&)a;"); 7414 verifyIndependentOfContext("f((*PointerToArray)[10]);"); 7415 verifyFormat("void f(Type (*parameter)[10]) {}"); 7416 verifyFormat("void f(Type (¶meter)[10]) {}"); 7417 verifyGoogleFormat("return sizeof(int**);"); 7418 verifyIndependentOfContext("Type **A = static_cast<Type **>(P);"); 7419 verifyGoogleFormat("Type** A = static_cast<Type**>(P);"); 7420 verifyFormat("auto a = [](int **&, int ***) {};"); 7421 verifyFormat("auto PointerBinding = [](const char *S) {};"); 7422 verifyFormat("typedef typeof(int(int, int)) *MyFunc;"); 7423 verifyFormat("[](const decltype(*a) &value) {}"); 7424 verifyFormat("decltype(a * b) F();"); 7425 verifyFormat("#define MACRO() [](A *a) { return 1; }"); 7426 verifyFormat("Constructor() : member([](A *a, B *b) {}) {}"); 7427 verifyIndependentOfContext("typedef void (*f)(int *a);"); 7428 verifyIndependentOfContext("int i{a * b};"); 7429 verifyIndependentOfContext("aaa && aaa->f();"); 7430 verifyIndependentOfContext("int x = ~*p;"); 7431 verifyFormat("Constructor() : a(a), area(width * height) {}"); 7432 verifyFormat("Constructor() : a(a), area(a, width * height) {}"); 7433 verifyGoogleFormat("MACRO Constructor(const int& i) : a(a), b(b) {}"); 7434 verifyFormat("void f() { f(a, c * d); }"); 7435 verifyFormat("void f() { f(new a(), c * d); }"); 7436 verifyFormat("void f(const MyOverride &override);"); 7437 verifyFormat("void f(const MyFinal &final);"); 7438 verifyIndependentOfContext("bool a = f() && override.f();"); 7439 verifyIndependentOfContext("bool a = f() && final.f();"); 7440 7441 verifyIndependentOfContext("InvalidRegions[*R] = 0;"); 7442 7443 verifyIndependentOfContext("A<int *> a;"); 7444 verifyIndependentOfContext("A<int **> a;"); 7445 verifyIndependentOfContext("A<int *, int *> a;"); 7446 verifyIndependentOfContext("A<int *[]> a;"); 7447 verifyIndependentOfContext( 7448 "const char *const p = reinterpret_cast<const char *const>(q);"); 7449 verifyIndependentOfContext("A<int **, int **> a;"); 7450 verifyIndependentOfContext("void f(int *a = d * e, int *b = c * d);"); 7451 verifyFormat("for (char **a = b; *a; ++a) {\n}"); 7452 verifyFormat("for (; a && b;) {\n}"); 7453 verifyFormat("bool foo = true && [] { return false; }();"); 7454 7455 verifyFormat( 7456 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7457 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa, *aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7458 7459 verifyGoogleFormat("int const* a = &b;"); 7460 verifyGoogleFormat("**outparam = 1;"); 7461 verifyGoogleFormat("*outparam = a * b;"); 7462 verifyGoogleFormat("int main(int argc, char** argv) {}"); 7463 verifyGoogleFormat("A<int*> a;"); 7464 verifyGoogleFormat("A<int**> a;"); 7465 verifyGoogleFormat("A<int*, int*> a;"); 7466 verifyGoogleFormat("A<int**, int**> a;"); 7467 verifyGoogleFormat("f(b ? *c : *d);"); 7468 verifyGoogleFormat("int a = b ? *c : *d;"); 7469 verifyGoogleFormat("Type* t = **x;"); 7470 verifyGoogleFormat("Type* t = *++*x;"); 7471 verifyGoogleFormat("*++*x;"); 7472 verifyGoogleFormat("Type* t = const_cast<T*>(&*x);"); 7473 verifyGoogleFormat("Type* t = x++ * y;"); 7474 verifyGoogleFormat( 7475 "const char* const p = reinterpret_cast<const char* const>(q);"); 7476 verifyGoogleFormat("void f(int i = 0, SomeType** temps = NULL);"); 7477 verifyGoogleFormat("void f(Bar* a = nullptr, Bar* b);"); 7478 verifyGoogleFormat("template <typename T>\n" 7479 "void f(int i = 0, SomeType** temps = NULL);"); 7480 7481 FormatStyle Left = getLLVMStyle(); 7482 Left.PointerAlignment = FormatStyle::PAS_Left; 7483 verifyFormat("x = *a(x) = *a(y);", Left); 7484 verifyFormat("for (;; *a = b) {\n}", Left); 7485 verifyFormat("return *this += 1;", Left); 7486 verifyFormat("throw *x;", Left); 7487 verifyFormat("delete *x;", Left); 7488 verifyFormat("typedef typeof(int(int, int))* MyFuncPtr;", Left); 7489 verifyFormat("[](const decltype(*a)* ptr) {}", Left); 7490 verifyFormat("typedef typeof /*comment*/ (int(int, int))* MyFuncPtr;", Left); 7491 verifyFormat("auto x(A&&, B&&, C&&) -> D;", Left); 7492 verifyFormat("auto x = [](A&&, B&&, C&&) -> D {};", Left); 7493 verifyFormat("template <class T> X(T&&, T&&, T&&) -> X<T>;", Left); 7494 7495 verifyIndependentOfContext("a = *(x + y);"); 7496 verifyIndependentOfContext("a = &(x + y);"); 7497 verifyIndependentOfContext("*(x + y).call();"); 7498 verifyIndependentOfContext("&(x + y)->call();"); 7499 verifyFormat("void f() { &(*I).first; }"); 7500 7501 verifyIndependentOfContext("f(b * /* confusing comment */ ++c);"); 7502 verifyFormat( 7503 "int *MyValues = {\n" 7504 " *A, // Operator detection might be confused by the '{'\n" 7505 " *BB // Operator detection might be confused by previous comment\n" 7506 "};"); 7507 7508 verifyIndependentOfContext("if (int *a = &b)"); 7509 verifyIndependentOfContext("if (int &a = *b)"); 7510 verifyIndependentOfContext("if (a & b[i])"); 7511 verifyIndependentOfContext("if constexpr (a & b[i])"); 7512 verifyIndependentOfContext("if CONSTEXPR (a & b[i])"); 7513 verifyIndependentOfContext("if (a * (b * c))"); 7514 verifyIndependentOfContext("if constexpr (a * (b * c))"); 7515 verifyIndependentOfContext("if CONSTEXPR (a * (b * c))"); 7516 verifyIndependentOfContext("if (a::b::c::d & b[i])"); 7517 verifyIndependentOfContext("if (*b[i])"); 7518 verifyIndependentOfContext("if (int *a = (&b))"); 7519 verifyIndependentOfContext("while (int *a = &b)"); 7520 verifyIndependentOfContext("while (a * (b * c))"); 7521 verifyIndependentOfContext("size = sizeof *a;"); 7522 verifyIndependentOfContext("if (a && (b = c))"); 7523 verifyFormat("void f() {\n" 7524 " for (const int &v : Values) {\n" 7525 " }\n" 7526 "}"); 7527 verifyFormat("for (int i = a * a; i < 10; ++i) {\n}"); 7528 verifyFormat("for (int i = 0; i < a * a; ++i) {\n}"); 7529 verifyGoogleFormat("for (int i = 0; i * 2 < z; i *= 2) {\n}"); 7530 7531 verifyFormat("#define A (!a * b)"); 7532 verifyFormat("#define MACRO \\\n" 7533 " int *i = a * b; \\\n" 7534 " void f(a *b);", 7535 getLLVMStyleWithColumns(19)); 7536 7537 verifyIndependentOfContext("A = new SomeType *[Length];"); 7538 verifyIndependentOfContext("A = new SomeType *[Length]();"); 7539 verifyIndependentOfContext("T **t = new T *;"); 7540 verifyIndependentOfContext("T **t = new T *();"); 7541 verifyGoogleFormat("A = new SomeType*[Length]();"); 7542 verifyGoogleFormat("A = new SomeType*[Length];"); 7543 verifyGoogleFormat("T** t = new T*;"); 7544 verifyGoogleFormat("T** t = new T*();"); 7545 7546 verifyFormat("STATIC_ASSERT((a & b) == 0);"); 7547 verifyFormat("STATIC_ASSERT(0 == (a & b));"); 7548 verifyFormat("template <bool a, bool b> " 7549 "typename t::if<x && y>::type f() {}"); 7550 verifyFormat("template <int *y> f() {}"); 7551 verifyFormat("vector<int *> v;"); 7552 verifyFormat("vector<int *const> v;"); 7553 verifyFormat("vector<int *const **const *> v;"); 7554 verifyFormat("vector<int *volatile> v;"); 7555 verifyFormat("vector<a * b> v;"); 7556 verifyFormat("foo<b && false>();"); 7557 verifyFormat("foo<b & 1>();"); 7558 verifyFormat("decltype(*::std::declval<const T &>()) void F();"); 7559 verifyFormat( 7560 "template <class T, class = typename std::enable_if<\n" 7561 " std::is_integral<T>::value &&\n" 7562 " (sizeof(T) > 1 || sizeof(T) < 8)>::type>\n" 7563 "void F();", 7564 getLLVMStyleWithColumns(70)); 7565 verifyFormat("template <class T,\n" 7566 " class = typename std::enable_if<\n" 7567 " std::is_integral<T>::value &&\n" 7568 " (sizeof(T) > 1 || sizeof(T) < 8)>::type,\n" 7569 " class U>\n" 7570 "void F();", 7571 getLLVMStyleWithColumns(70)); 7572 verifyFormat( 7573 "template <class T,\n" 7574 " class = typename ::std::enable_if<\n" 7575 " ::std::is_array<T>{} && ::std::is_array<T>{}>::type>\n" 7576 "void F();", 7577 getGoogleStyleWithColumns(68)); 7578 7579 verifyIndependentOfContext("MACRO(int *i);"); 7580 verifyIndependentOfContext("MACRO(auto *a);"); 7581 verifyIndependentOfContext("MACRO(const A *a);"); 7582 verifyIndependentOfContext("MACRO(A *const a);"); 7583 verifyIndependentOfContext("MACRO('0' <= c && c <= '9');"); 7584 verifyFormat("void f() { f(float{1}, a * a); }"); 7585 // FIXME: Is there a way to make this work? 7586 // verifyIndependentOfContext("MACRO(A *a);"); 7587 7588 verifyFormat("DatumHandle const *operator->() const { return input_; }"); 7589 verifyFormat("return options != nullptr && operator==(*options);"); 7590 7591 EXPECT_EQ("#define OP(x) \\\n" 7592 " ostream &operator<<(ostream &s, const A &a) { \\\n" 7593 " return s << a.DebugString(); \\\n" 7594 " }", 7595 format("#define OP(x) \\\n" 7596 " ostream &operator<<(ostream &s, const A &a) { \\\n" 7597 " return s << a.DebugString(); \\\n" 7598 " }", 7599 getLLVMStyleWithColumns(50))); 7600 7601 // FIXME: We cannot handle this case yet; we might be able to figure out that 7602 // foo<x> d > v; doesn't make sense. 7603 verifyFormat("foo<a<b && c> d> v;"); 7604 7605 FormatStyle PointerMiddle = getLLVMStyle(); 7606 PointerMiddle.PointerAlignment = FormatStyle::PAS_Middle; 7607 verifyFormat("delete *x;", PointerMiddle); 7608 verifyFormat("int * x;", PointerMiddle); 7609 verifyFormat("int *[] x;", PointerMiddle); 7610 verifyFormat("template <int * y> f() {}", PointerMiddle); 7611 verifyFormat("int * f(int * a) {}", PointerMiddle); 7612 verifyFormat("int main(int argc, char ** argv) {}", PointerMiddle); 7613 verifyFormat("Test::Test(int b) : a(b * b) {}", PointerMiddle); 7614 verifyFormat("A<int *> a;", PointerMiddle); 7615 verifyFormat("A<int **> a;", PointerMiddle); 7616 verifyFormat("A<int *, int *> a;", PointerMiddle); 7617 verifyFormat("A<int *[]> a;", PointerMiddle); 7618 verifyFormat("A = new SomeType *[Length]();", PointerMiddle); 7619 verifyFormat("A = new SomeType *[Length];", PointerMiddle); 7620 verifyFormat("T ** t = new T *;", PointerMiddle); 7621 7622 // Member function reference qualifiers aren't binary operators. 7623 verifyFormat("string // break\n" 7624 "operator()() & {}"); 7625 verifyFormat("string // break\n" 7626 "operator()() && {}"); 7627 verifyGoogleFormat("template <typename T>\n" 7628 "auto x() & -> int {}"); 7629 } 7630 7631 TEST_F(FormatTest, UnderstandsAttributes) { 7632 verifyFormat("SomeType s __attribute__((unused)) (InitValue);"); 7633 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa __attribute__((unused))\n" 7634 "aaaaaaaaaaaaaaaaaaaaaaa(int i);"); 7635 FormatStyle AfterType = getLLVMStyle(); 7636 AfterType.AlwaysBreakAfterReturnType = FormatStyle::RTBS_AllDefinitions; 7637 verifyFormat("__attribute__((nodebug)) void\n" 7638 "foo() {}\n", 7639 AfterType); 7640 } 7641 7642 TEST_F(FormatTest, UnderstandsSquareAttributes) { 7643 verifyFormat("SomeType s [[unused]] (InitValue);"); 7644 verifyFormat("SomeType s [[gnu::unused]] (InitValue);"); 7645 verifyFormat("SomeType s [[using gnu: unused]] (InitValue);"); 7646 verifyFormat("[[gsl::suppress(\"clang-tidy-check-name\")]] void f() {}"); 7647 verifyFormat("void f() [[deprecated(\"so sorry\")]];"); 7648 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7649 " [[unused]] aaaaaaaaaaaaaaaaaaaaaaa(int i);"); 7650 verifyFormat("[[nodiscard]] bool f() { return false; }"); 7651 verifyFormat("class [[nodiscard]] f {\npublic:\n f() {}\n}"); 7652 verifyFormat("class [[deprecated(\"so sorry\")]] f {\npublic:\n f() {}\n}"); 7653 verifyFormat("class [[gnu::unused]] f {\npublic:\n f() {}\n}"); 7654 7655 // Make sure we do not mistake attributes for array subscripts. 7656 verifyFormat("int a() {}\n" 7657 "[[unused]] int b() {}\n"); 7658 verifyFormat("NSArray *arr;\n" 7659 "arr[[Foo() bar]];"); 7660 7661 // On the other hand, we still need to correctly find array subscripts. 7662 verifyFormat("int a = std::vector<int>{1, 2, 3}[0];"); 7663 7664 // Make sure that we do not mistake Objective-C method inside array literals 7665 // as attributes, even if those method names are also keywords. 7666 verifyFormat("@[ [foo bar] ];"); 7667 verifyFormat("@[ [NSArray class] ];"); 7668 verifyFormat("@[ [foo enum] ];"); 7669 7670 // Make sure we do not parse attributes as lambda introducers. 7671 FormatStyle MultiLineFunctions = getLLVMStyle(); 7672 MultiLineFunctions.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 7673 verifyFormat("[[unused]] int b() {\n" 7674 " return 42;\n" 7675 "}\n", 7676 MultiLineFunctions); 7677 } 7678 7679 TEST_F(FormatTest, AttributePenaltyBreaking) { 7680 FormatStyle Style = getLLVMStyle(); 7681 verifyFormat("void ABCDEFGH::ABCDEFGHIJKLMN(\n" 7682 " [[maybe_unused]] const shared_ptr<ALongTypeName> &C d) {}", 7683 Style); 7684 verifyFormat("void ABCDEFGH::ABCDEFGHIJK(\n" 7685 " [[maybe_unused]] const shared_ptr<ALongTypeName> &C d) {}", 7686 Style); 7687 verifyFormat("void ABCDEFGH::ABCDEFGH([[maybe_unused]] const " 7688 "shared_ptr<ALongTypeName> &C d) {\n}", 7689 Style); 7690 } 7691 7692 TEST_F(FormatTest, UnderstandsEllipsis) { 7693 verifyFormat("int printf(const char *fmt, ...);"); 7694 verifyFormat("template <class... Ts> void Foo(Ts... ts) { Foo(ts...); }"); 7695 verifyFormat("template <class... Ts> void Foo(Ts *... ts) {}"); 7696 7697 FormatStyle PointersLeft = getLLVMStyle(); 7698 PointersLeft.PointerAlignment = FormatStyle::PAS_Left; 7699 verifyFormat("template <class... Ts> void Foo(Ts*... ts) {}", PointersLeft); 7700 } 7701 7702 TEST_F(FormatTest, AdaptivelyFormatsPointersAndReferences) { 7703 EXPECT_EQ("int *a;\n" 7704 "int *a;\n" 7705 "int *a;", 7706 format("int *a;\n" 7707 "int* a;\n" 7708 "int *a;", 7709 getGoogleStyle())); 7710 EXPECT_EQ("int* a;\n" 7711 "int* a;\n" 7712 "int* a;", 7713 format("int* a;\n" 7714 "int* a;\n" 7715 "int *a;", 7716 getGoogleStyle())); 7717 EXPECT_EQ("int *a;\n" 7718 "int *a;\n" 7719 "int *a;", 7720 format("int *a;\n" 7721 "int * a;\n" 7722 "int * a;", 7723 getGoogleStyle())); 7724 EXPECT_EQ("auto x = [] {\n" 7725 " int *a;\n" 7726 " int *a;\n" 7727 " int *a;\n" 7728 "};", 7729 format("auto x=[]{int *a;\n" 7730 "int * a;\n" 7731 "int * a;};", 7732 getGoogleStyle())); 7733 } 7734 7735 TEST_F(FormatTest, UnderstandsRvalueReferences) { 7736 verifyFormat("int f(int &&a) {}"); 7737 verifyFormat("int f(int a, char &&b) {}"); 7738 verifyFormat("void f() { int &&a = b; }"); 7739 verifyGoogleFormat("int f(int a, char&& b) {}"); 7740 verifyGoogleFormat("void f() { int&& a = b; }"); 7741 7742 verifyIndependentOfContext("A<int &&> a;"); 7743 verifyIndependentOfContext("A<int &&, int &&> a;"); 7744 verifyGoogleFormat("A<int&&> a;"); 7745 verifyGoogleFormat("A<int&&, int&&> a;"); 7746 7747 // Not rvalue references: 7748 verifyFormat("template <bool B, bool C> class A {\n" 7749 " static_assert(B && C, \"Something is wrong\");\n" 7750 "};"); 7751 verifyGoogleFormat("#define IF(a, b, c) if (a && (b == c))"); 7752 verifyGoogleFormat("#define WHILE(a, b, c) while (a && (b == c))"); 7753 verifyFormat("#define A(a, b) (a && b)"); 7754 } 7755 7756 TEST_F(FormatTest, FormatsBinaryOperatorsPrecedingEquals) { 7757 verifyFormat("void f() {\n" 7758 " x[aaaaaaaaa -\n" 7759 " b] = 23;\n" 7760 "}", 7761 getLLVMStyleWithColumns(15)); 7762 } 7763 7764 TEST_F(FormatTest, FormatsCasts) { 7765 verifyFormat("Type *A = static_cast<Type *>(P);"); 7766 verifyFormat("Type *A = (Type *)P;"); 7767 verifyFormat("Type *A = (vector<Type *, int *>)P;"); 7768 verifyFormat("int a = (int)(2.0f);"); 7769 verifyFormat("int a = (int)2.0f;"); 7770 verifyFormat("x[(int32)y];"); 7771 verifyFormat("x = (int32)y;"); 7772 verifyFormat("#define AA(X) sizeof(((X *)NULL)->a)"); 7773 verifyFormat("int a = (int)*b;"); 7774 verifyFormat("int a = (int)2.0f;"); 7775 verifyFormat("int a = (int)~0;"); 7776 verifyFormat("int a = (int)++a;"); 7777 verifyFormat("int a = (int)sizeof(int);"); 7778 verifyFormat("int a = (int)+2;"); 7779 verifyFormat("my_int a = (my_int)2.0f;"); 7780 verifyFormat("my_int a = (my_int)sizeof(int);"); 7781 verifyFormat("return (my_int)aaa;"); 7782 verifyFormat("#define x ((int)-1)"); 7783 verifyFormat("#define LENGTH(x, y) (x) - (y) + 1"); 7784 verifyFormat("#define p(q) ((int *)&q)"); 7785 verifyFormat("fn(a)(b) + 1;"); 7786 7787 verifyFormat("void f() { my_int a = (my_int)*b; }"); 7788 verifyFormat("void f() { return P ? (my_int)*P : (my_int)0; }"); 7789 verifyFormat("my_int a = (my_int)~0;"); 7790 verifyFormat("my_int a = (my_int)++a;"); 7791 verifyFormat("my_int a = (my_int)-2;"); 7792 verifyFormat("my_int a = (my_int)1;"); 7793 verifyFormat("my_int a = (my_int *)1;"); 7794 verifyFormat("my_int a = (const my_int)-1;"); 7795 verifyFormat("my_int a = (const my_int *)-1;"); 7796 verifyFormat("my_int a = (my_int)(my_int)-1;"); 7797 verifyFormat("my_int a = (ns::my_int)-2;"); 7798 verifyFormat("case (my_int)ONE:"); 7799 verifyFormat("auto x = (X)this;"); 7800 // Casts in Obj-C style calls used to not be recognized as such. 7801 verifyFormat("int a = [(type*)[((type*)val) arg] arg];", getGoogleStyle()); 7802 7803 // FIXME: single value wrapped with paren will be treated as cast. 7804 verifyFormat("void f(int i = (kValue)*kMask) {}"); 7805 7806 verifyFormat("{ (void)F; }"); 7807 7808 // Don't break after a cast's 7809 verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaaa =\n" 7810 " (aaaaaaaaaaaaaaaaaaaaaaaaaa *)(aaaaaaaaaaaaaaaaaaaaaa +\n" 7811 " bbbbbbbbbbbbbbbbbbbbbb);"); 7812 7813 // These are not casts. 7814 verifyFormat("void f(int *) {}"); 7815 verifyFormat("f(foo)->b;"); 7816 verifyFormat("f(foo).b;"); 7817 verifyFormat("f(foo)(b);"); 7818 verifyFormat("f(foo)[b];"); 7819 verifyFormat("[](foo) { return 4; }(bar);"); 7820 verifyFormat("(*funptr)(foo)[4];"); 7821 verifyFormat("funptrs[4](foo)[4];"); 7822 verifyFormat("void f(int *);"); 7823 verifyFormat("void f(int *) = 0;"); 7824 verifyFormat("void f(SmallVector<int>) {}"); 7825 verifyFormat("void f(SmallVector<int>);"); 7826 verifyFormat("void f(SmallVector<int>) = 0;"); 7827 verifyFormat("void f(int i = (kA * kB) & kMask) {}"); 7828 verifyFormat("int a = sizeof(int) * b;"); 7829 verifyFormat("int a = alignof(int) * b;", getGoogleStyle()); 7830 verifyFormat("template <> void f<int>(int i) SOME_ANNOTATION;"); 7831 verifyFormat("f(\"%\" SOME_MACRO(ll) \"d\");"); 7832 verifyFormat("aaaaa &operator=(const aaaaa &) LLVM_DELETED_FUNCTION;"); 7833 7834 // These are not casts, but at some point were confused with casts. 7835 verifyFormat("virtual void foo(int *) override;"); 7836 verifyFormat("virtual void foo(char &) const;"); 7837 verifyFormat("virtual void foo(int *a, char *) const;"); 7838 verifyFormat("int a = sizeof(int *) + b;"); 7839 verifyFormat("int a = alignof(int *) + b;", getGoogleStyle()); 7840 verifyFormat("bool b = f(g<int>) && c;"); 7841 verifyFormat("typedef void (*f)(int i) func;"); 7842 verifyFormat("void operator++(int) noexcept;"); 7843 verifyFormat("void operator++(int &) noexcept;"); 7844 verifyFormat("void operator delete(void *, std::size_t, const std::nothrow_t " 7845 "&) noexcept;"); 7846 verifyFormat( 7847 "void operator delete(std::size_t, const std::nothrow_t &) noexcept;"); 7848 verifyFormat("void operator delete(const std::nothrow_t &) noexcept;"); 7849 verifyFormat("void operator delete(std::nothrow_t &) noexcept;"); 7850 verifyFormat("void operator delete(nothrow_t &) noexcept;"); 7851 verifyFormat("void operator delete(foo &) noexcept;"); 7852 verifyFormat("void operator delete(foo) noexcept;"); 7853 verifyFormat("void operator delete(int) noexcept;"); 7854 verifyFormat("void operator delete(int &) noexcept;"); 7855 verifyFormat("void operator delete(int &) volatile noexcept;"); 7856 verifyFormat("void operator delete(int &) const"); 7857 verifyFormat("void operator delete(int &) = default"); 7858 verifyFormat("void operator delete(int &) = delete"); 7859 verifyFormat("void operator delete(int &) [[noreturn]]"); 7860 verifyFormat("void operator delete(int &) throw();"); 7861 verifyFormat("void operator delete(int &) throw(int);"); 7862 verifyFormat("auto operator delete(int &) -> int;"); 7863 verifyFormat("auto operator delete(int &) override"); 7864 verifyFormat("auto operator delete(int &) final"); 7865 7866 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *foo = (aaaaaaaaaaaaaaaaa *)\n" 7867 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;"); 7868 // FIXME: The indentation here is not ideal. 7869 verifyFormat( 7870 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7871 " [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = (*cccccccccccccccc)\n" 7872 " [dddddddddddddddddddddddddddddddddddddddddddddddddddddddd];"); 7873 } 7874 7875 TEST_F(FormatTest, FormatsFunctionTypes) { 7876 verifyFormat("A<bool()> a;"); 7877 verifyFormat("A<SomeType()> a;"); 7878 verifyFormat("A<void (*)(int, std::string)> a;"); 7879 verifyFormat("A<void *(int)>;"); 7880 verifyFormat("void *(*a)(int *, SomeType *);"); 7881 verifyFormat("int (*func)(void *);"); 7882 verifyFormat("void f() { int (*func)(void *); }"); 7883 verifyFormat("template <class CallbackClass>\n" 7884 "using MyCallback = void (CallbackClass::*)(SomeObject *Data);"); 7885 7886 verifyGoogleFormat("A<void*(int*, SomeType*)>;"); 7887 verifyGoogleFormat("void* (*a)(int);"); 7888 verifyGoogleFormat( 7889 "template <class CallbackClass>\n" 7890 "using MyCallback = void (CallbackClass::*)(SomeObject* Data);"); 7891 7892 // Other constructs can look somewhat like function types: 7893 verifyFormat("A<sizeof(*x)> a;"); 7894 verifyFormat("#define DEREF_AND_CALL_F(x) f(*x)"); 7895 verifyFormat("some_var = function(*some_pointer_var)[0];"); 7896 verifyFormat("void f() { function(*some_pointer_var)[0] = 10; }"); 7897 verifyFormat("int x = f(&h)();"); 7898 verifyFormat("returnsFunction(¶m1, ¶m2)(param);"); 7899 verifyFormat("std::function<\n" 7900 " LooooooooooongTemplatedType<\n" 7901 " SomeType>*(\n" 7902 " LooooooooooooooooongType type)>\n" 7903 " function;", 7904 getGoogleStyleWithColumns(40)); 7905 } 7906 7907 TEST_F(FormatTest, FormatsPointersToArrayTypes) { 7908 verifyFormat("A (*foo_)[6];"); 7909 verifyFormat("vector<int> (*foo_)[6];"); 7910 } 7911 7912 TEST_F(FormatTest, BreaksLongVariableDeclarations) { 7913 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n" 7914 " LoooooooooooooooooooooooooooooooooooooooongVariable;"); 7915 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType const\n" 7916 " LoooooooooooooooooooooooooooooooooooooooongVariable;"); 7917 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n" 7918 " *LoooooooooooooooooooooooooooooooooooooooongVariable;"); 7919 7920 // Different ways of ()-initializiation. 7921 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n" 7922 " LoooooooooooooooooooooooooooooooooooooooongVariable(1);"); 7923 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n" 7924 " LoooooooooooooooooooooooooooooooooooooooongVariable(a);"); 7925 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n" 7926 " LoooooooooooooooooooooooooooooooooooooooongVariable({});"); 7927 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n" 7928 " LoooooooooooooooooooooooooooooooooooooongVariable([A a]);"); 7929 7930 // Lambdas should not confuse the variable declaration heuristic. 7931 verifyFormat("LooooooooooooooooongType\n" 7932 " variable(nullptr, [](A *a) {});", 7933 getLLVMStyleWithColumns(40)); 7934 } 7935 7936 TEST_F(FormatTest, BreaksLongDeclarations) { 7937 verifyFormat("typedef LoooooooooooooooooooooooooooooooooooooooongType\n" 7938 " AnotherNameForTheLongType;"); 7939 verifyFormat("typedef LongTemplateType<aaaaaaaaaaaaaaaaaaa()>\n" 7940 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 7941 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n" 7942 "LoooooooooooooooooooooooooooooooongFunctionDeclaration();"); 7943 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType *\n" 7944 "LoooooooooooooooooooooooooooooooongFunctionDeclaration();"); 7945 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n" 7946 "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}"); 7947 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType MACRO\n" 7948 "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}"); 7949 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType const\n" 7950 "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}"); 7951 verifyFormat("decltype(LoooooooooooooooooooooooooooooooooooooooongName)\n" 7952 "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}"); 7953 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n" 7954 "LooooooooooooooooooooooooooongFunctionDeclaration(T... t);"); 7955 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n" 7956 "LooooooooooooooooooooooooooongFunctionDeclaration(T /*t*/) {}"); 7957 FormatStyle Indented = getLLVMStyle(); 7958 Indented.IndentWrappedFunctionNames = true; 7959 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n" 7960 " LoooooooooooooooooooooooooooooooongFunctionDeclaration();", 7961 Indented); 7962 verifyFormat( 7963 "LoooooooooooooooooooooooooooooooooooooooongReturnType\n" 7964 " LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}", 7965 Indented); 7966 verifyFormat( 7967 "LoooooooooooooooooooooooooooooooooooooooongReturnType const\n" 7968 " LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}", 7969 Indented); 7970 verifyFormat( 7971 "decltype(LoooooooooooooooooooooooooooooooooooooooongName)\n" 7972 " LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}", 7973 Indented); 7974 7975 // FIXME: Without the comment, this breaks after "(". 7976 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType // break\n" 7977 " (*LoooooooooooooooooooooooooooongFunctionTypeVarialbe)();", 7978 getGoogleStyle()); 7979 7980 verifyFormat("int *someFunction(int LoooooooooooooooooooongParam1,\n" 7981 " int LoooooooooooooooooooongParam2) {}"); 7982 verifyFormat( 7983 "TypeSpecDecl *TypeSpecDecl::Create(ASTContext &C, DeclContext *DC,\n" 7984 " SourceLocation L, IdentifierIn *II,\n" 7985 " Type *T) {}"); 7986 verifyFormat("ReallyLongReturnType<TemplateParam1, TemplateParam2>\n" 7987 "ReallyReaaallyLongFunctionName(\n" 7988 " const std::string &SomeParameter,\n" 7989 " const SomeType<string, SomeOtherTemplateParameter>\n" 7990 " &ReallyReallyLongParameterName,\n" 7991 " const SomeType<string, SomeOtherTemplateParameter>\n" 7992 " &AnotherLongParameterName) {}"); 7993 verifyFormat("template <typename A>\n" 7994 "SomeLoooooooooooooooooooooongType<\n" 7995 " typename some_namespace::SomeOtherType<A>::Type>\n" 7996 "Function() {}"); 7997 7998 verifyGoogleFormat( 7999 "aaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaa<aaaaaaaaaaaaa, aaaaaaaaaaaa>\n" 8000 " aaaaaaaaaaaaaaaaaaaaaaa;"); 8001 verifyGoogleFormat( 8002 "TypeSpecDecl* TypeSpecDecl::Create(ASTContext& C, DeclContext* DC,\n" 8003 " SourceLocation L) {}"); 8004 verifyGoogleFormat( 8005 "some_namespace::LongReturnType\n" 8006 "long_namespace::SomeVeryLongClass::SomeVeryLongFunction(\n" 8007 " int first_long_parameter, int second_parameter) {}"); 8008 8009 verifyGoogleFormat("template <typename T>\n" 8010 "aaaaaaaa::aaaaa::aaaaaa<T, aaaaaaaaaaaaaaaaaaaaaaaaa>\n" 8011 "aaaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaa() {}"); 8012 verifyGoogleFormat("A<A<A>> aaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8013 " int aaaaaaaaaaaaaaaaaaaaaaa);"); 8014 8015 verifyFormat("typedef size_t (*aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)(\n" 8016 " const aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8017 " *aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 8018 verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8019 " vector<aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>\n" 8020 " aaaaaaaaaaaaaaaaaaaaaaaa);"); 8021 verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8022 " vector<aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<\n" 8023 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>>\n" 8024 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 8025 8026 verifyFormat("template <typename T> // Templates on own line.\n" 8027 "static int // Some comment.\n" 8028 "MyFunction(int a);", 8029 getLLVMStyle()); 8030 } 8031 8032 TEST_F(FormatTest, FormatsArrays) { 8033 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaaaaaaaaaaaaaa]\n" 8034 " [bbbbbbbbbbbbbbbbbbbbbbbbb] = c;"); 8035 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaa(aaaaaaaaaaaa)]\n" 8036 " [bbbbbbbbbbb(bbbbbbbbbbbb)] = c;"); 8037 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaa &&\n" 8038 " aaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaa][aaaaaaaaaaaaa]) {\n}"); 8039 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8040 " [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = ccccccccccc;"); 8041 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8042 " [a][bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = cccccccc;"); 8043 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8044 " [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]\n" 8045 " [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = ccccccccccc;"); 8046 verifyFormat( 8047 "llvm::outs() << \"aaaaaaaaaaaa: \"\n" 8048 " << (*aaaaaaaiaaaaaaa)[aaaaaaaaaaaaaaaaaaaaaaaaa]\n" 8049 " [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa];"); 8050 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaaaaaa][a]\n" 8051 " .aaaaaaaaaaaaaaaaaaaaaa();"); 8052 8053 verifyGoogleFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<int>\n" 8054 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaa];"); 8055 verifyFormat( 8056 "aaaaaaaaaaa aaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaa->aaaaaaaaa[0]\n" 8057 " .aaaaaaa[0]\n" 8058 " .aaaaaaaaaaaaaaaaaaaaaa();"); 8059 verifyFormat("a[::b::c];"); 8060 8061 verifyNoCrash("a[,Y?)]", getLLVMStyleWithColumns(10)); 8062 8063 FormatStyle NoColumnLimit = getLLVMStyleWithColumns(0); 8064 verifyFormat("aaaaa[bbbbbb].cccccc()", NoColumnLimit); 8065 } 8066 8067 TEST_F(FormatTest, LineStartsWithSpecialCharacter) { 8068 verifyFormat("(a)->b();"); 8069 verifyFormat("--a;"); 8070 } 8071 8072 TEST_F(FormatTest, HandlesIncludeDirectives) { 8073 verifyFormat("#include <string>\n" 8074 "#include <a/b/c.h>\n" 8075 "#include \"a/b/string\"\n" 8076 "#include \"string.h\"\n" 8077 "#include \"string.h\"\n" 8078 "#include <a-a>\n" 8079 "#include < path with space >\n" 8080 "#include_next <test.h>" 8081 "#include \"abc.h\" // this is included for ABC\n" 8082 "#include \"some long include\" // with a comment\n" 8083 "#include \"some very long include path\"\n" 8084 "#include <some/very/long/include/path>\n", 8085 getLLVMStyleWithColumns(35)); 8086 EXPECT_EQ("#include \"a.h\"", format("#include \"a.h\"")); 8087 EXPECT_EQ("#include <a>", format("#include<a>")); 8088 8089 verifyFormat("#import <string>"); 8090 verifyFormat("#import <a/b/c.h>"); 8091 verifyFormat("#import \"a/b/string\""); 8092 verifyFormat("#import \"string.h\""); 8093 verifyFormat("#import \"string.h\""); 8094 verifyFormat("#if __has_include(<strstream>)\n" 8095 "#include <strstream>\n" 8096 "#endif"); 8097 8098 verifyFormat("#define MY_IMPORT <a/b>"); 8099 8100 verifyFormat("#if __has_include(<a/b>)"); 8101 verifyFormat("#if __has_include_next(<a/b>)"); 8102 verifyFormat("#define F __has_include(<a/b>)"); 8103 verifyFormat("#define F __has_include_next(<a/b>)"); 8104 8105 // Protocol buffer definition or missing "#". 8106 verifyFormat("import \"aaaaaaaaaaaaaaaaa/aaaaaaaaaaaaaaa\";", 8107 getLLVMStyleWithColumns(30)); 8108 8109 FormatStyle Style = getLLVMStyle(); 8110 Style.AlwaysBreakBeforeMultilineStrings = true; 8111 Style.ColumnLimit = 0; 8112 verifyFormat("#import \"abc.h\"", Style); 8113 8114 // But 'import' might also be a regular C++ namespace. 8115 verifyFormat("import::SomeFunction(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8116 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 8117 } 8118 8119 //===----------------------------------------------------------------------===// 8120 // Error recovery tests. 8121 //===----------------------------------------------------------------------===// 8122 8123 TEST_F(FormatTest, IncompleteParameterLists) { 8124 FormatStyle NoBinPacking = getLLVMStyle(); 8125 NoBinPacking.BinPackParameters = false; 8126 verifyFormat("void aaaaaaaaaaaaaaaaaa(int level,\n" 8127 " double *min_x,\n" 8128 " double *max_x,\n" 8129 " double *min_y,\n" 8130 " double *max_y,\n" 8131 " double *min_z,\n" 8132 " double *max_z, ) {}", 8133 NoBinPacking); 8134 } 8135 8136 TEST_F(FormatTest, IncorrectCodeTrailingStuff) { 8137 verifyFormat("void f() { return; }\n42"); 8138 verifyFormat("void f() {\n" 8139 " if (0)\n" 8140 " return;\n" 8141 "}\n" 8142 "42"); 8143 verifyFormat("void f() { return }\n42"); 8144 verifyFormat("void f() {\n" 8145 " if (0)\n" 8146 " return\n" 8147 "}\n" 8148 "42"); 8149 } 8150 8151 TEST_F(FormatTest, IncorrectCodeMissingSemicolon) { 8152 EXPECT_EQ("void f() { return }", format("void f ( ) { return }")); 8153 EXPECT_EQ("void f() {\n" 8154 " if (a)\n" 8155 " return\n" 8156 "}", 8157 format("void f ( ) { if ( a ) return }")); 8158 EXPECT_EQ("namespace N {\n" 8159 "void f()\n" 8160 "}", 8161 format("namespace N { void f() }")); 8162 EXPECT_EQ("namespace N {\n" 8163 "void f() {}\n" 8164 "void g()\n" 8165 "} // namespace N", 8166 format("namespace N { void f( ) { } void g( ) }")); 8167 } 8168 8169 TEST_F(FormatTest, IndentationWithinColumnLimitNotPossible) { 8170 verifyFormat("int aaaaaaaa =\n" 8171 " // Overlylongcomment\n" 8172 " b;", 8173 getLLVMStyleWithColumns(20)); 8174 verifyFormat("function(\n" 8175 " ShortArgument,\n" 8176 " LoooooooooooongArgument);\n", 8177 getLLVMStyleWithColumns(20)); 8178 } 8179 8180 TEST_F(FormatTest, IncorrectAccessSpecifier) { 8181 verifyFormat("public:"); 8182 verifyFormat("class A {\n" 8183 "public\n" 8184 " void f() {}\n" 8185 "};"); 8186 verifyFormat("public\n" 8187 "int qwerty;"); 8188 verifyFormat("public\n" 8189 "B {}"); 8190 verifyFormat("public\n" 8191 "{}"); 8192 verifyFormat("public\n" 8193 "B { int x; }"); 8194 } 8195 8196 TEST_F(FormatTest, IncorrectCodeUnbalancedBraces) { 8197 verifyFormat("{"); 8198 verifyFormat("#})"); 8199 verifyNoCrash("(/**/[:!] ?[)."); 8200 } 8201 8202 TEST_F(FormatTest, IncorrectUnbalancedBracesInMacrosWithUnicode) { 8203 // Found by oss-fuzz: 8204 // https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=8212 8205 FormatStyle Style = getGoogleStyle(FormatStyle::LK_Cpp); 8206 Style.ColumnLimit = 60; 8207 verifyNoCrash( 8208 "\x23\x47\xff\x20\x28\xff\x3c\xff\x3f\xff\x20\x2f\x7b\x7a\xff\x20" 8209 "\xff\xff\xff\xca\xb5\xff\xff\xff\xff\x3a\x7b\x7d\xff\x20\xff\x20" 8210 "\xff\x74\xff\x20\x7d\x7d\xff\x7b\x3a\xff\x20\x71\xff\x20\xff\x0a", 8211 Style); 8212 } 8213 8214 TEST_F(FormatTest, IncorrectCodeDoNoWhile) { 8215 verifyFormat("do {\n}"); 8216 verifyFormat("do {\n}\n" 8217 "f();"); 8218 verifyFormat("do {\n}\n" 8219 "wheeee(fun);"); 8220 verifyFormat("do {\n" 8221 " f();\n" 8222 "}"); 8223 } 8224 8225 TEST_F(FormatTest, IncorrectCodeMissingParens) { 8226 verifyFormat("if {\n foo;\n foo();\n}"); 8227 verifyFormat("switch {\n foo;\n foo();\n}"); 8228 verifyIncompleteFormat("for {\n foo;\n foo();\n}"); 8229 verifyFormat("while {\n foo;\n foo();\n}"); 8230 verifyFormat("do {\n foo;\n foo();\n} while;"); 8231 } 8232 8233 TEST_F(FormatTest, DoesNotTouchUnwrappedLinesWithErrors) { 8234 verifyIncompleteFormat("namespace {\n" 8235 "class Foo { Foo (\n" 8236 "};\n" 8237 "} // namespace"); 8238 } 8239 8240 TEST_F(FormatTest, IncorrectCodeErrorDetection) { 8241 EXPECT_EQ("{\n {}\n", format("{\n{\n}\n")); 8242 EXPECT_EQ("{\n {}\n", format("{\n {\n}\n")); 8243 EXPECT_EQ("{\n {}\n", format("{\n {\n }\n")); 8244 EXPECT_EQ("{\n {}\n}\n}\n", format("{\n {\n }\n }\n}\n")); 8245 8246 EXPECT_EQ("{\n" 8247 " {\n" 8248 " breakme(\n" 8249 " qwe);\n" 8250 " }\n", 8251 format("{\n" 8252 " {\n" 8253 " breakme(qwe);\n" 8254 "}\n", 8255 getLLVMStyleWithColumns(10))); 8256 } 8257 8258 TEST_F(FormatTest, LayoutCallsInsideBraceInitializers) { 8259 verifyFormat("int x = {\n" 8260 " avariable,\n" 8261 " b(alongervariable)};", 8262 getLLVMStyleWithColumns(25)); 8263 } 8264 8265 TEST_F(FormatTest, LayoutBraceInitializersInReturnStatement) { 8266 verifyFormat("return (a)(b){1, 2, 3};"); 8267 } 8268 8269 TEST_F(FormatTest, LayoutCxx11BraceInitializers) { 8270 verifyFormat("vector<int> x{1, 2, 3, 4};"); 8271 verifyFormat("vector<int> x{\n" 8272 " 1,\n" 8273 " 2,\n" 8274 " 3,\n" 8275 " 4,\n" 8276 "};"); 8277 verifyFormat("vector<T> x{{}, {}, {}, {}};"); 8278 verifyFormat("f({1, 2});"); 8279 verifyFormat("auto v = Foo{-1};"); 8280 verifyFormat("f({1, 2}, {{2, 3}, {4, 5}}, c, {d});"); 8281 verifyFormat("Class::Class : member{1, 2, 3} {}"); 8282 verifyFormat("new vector<int>{1, 2, 3};"); 8283 verifyFormat("new int[3]{1, 2, 3};"); 8284 verifyFormat("new int{1};"); 8285 verifyFormat("return {arg1, arg2};"); 8286 verifyFormat("return {arg1, SomeType{parameter}};"); 8287 verifyFormat("int count = set<int>{f(), g(), h()}.size();"); 8288 verifyFormat("new T{arg1, arg2};"); 8289 verifyFormat("f(MyMap[{composite, key}]);"); 8290 verifyFormat("class Class {\n" 8291 " T member = {arg1, arg2};\n" 8292 "};"); 8293 verifyFormat("vector<int> foo = {::SomeGlobalFunction()};"); 8294 verifyFormat("const struct A a = {.a = 1, .b = 2};"); 8295 verifyFormat("const struct A a = {[0] = 1, [1] = 2};"); 8296 verifyFormat("static_assert(std::is_integral<int>{} + 0, \"\");"); 8297 verifyFormat("int a = std::is_integral<int>{} + 0;"); 8298 8299 verifyFormat("int foo(int i) { return fo1{}(i); }"); 8300 verifyFormat("int foo(int i) { return fo1{}(i); }"); 8301 verifyFormat("auto i = decltype(x){};"); 8302 verifyFormat("std::vector<int> v = {1, 0 /* comment */};"); 8303 verifyFormat("Node n{1, Node{1000}, //\n" 8304 " 2};"); 8305 verifyFormat("Aaaa aaaaaaa{\n" 8306 " {\n" 8307 " aaaa,\n" 8308 " },\n" 8309 "};"); 8310 verifyFormat("class C : public D {\n" 8311 " SomeClass SC{2};\n" 8312 "};"); 8313 verifyFormat("class C : public A {\n" 8314 " class D : public B {\n" 8315 " void f() { int i{2}; }\n" 8316 " };\n" 8317 "};"); 8318 verifyFormat("#define A {a, a},"); 8319 8320 // Avoid breaking between equal sign and opening brace 8321 FormatStyle AvoidBreakingFirstArgument = getLLVMStyle(); 8322 AvoidBreakingFirstArgument.PenaltyBreakBeforeFirstCallParameter = 200; 8323 verifyFormat("const std::unordered_map<std::string, int> MyHashTable =\n" 8324 " {{\"aaaaaaaaaaaaaaaaaaaaa\", 0},\n" 8325 " {\"bbbbbbbbbbbbbbbbbbbbb\", 1},\n" 8326 " {\"ccccccccccccccccccccc\", 2}};", 8327 AvoidBreakingFirstArgument); 8328 8329 // Binpacking only if there is no trailing comma 8330 verifyFormat("const Aaaaaa aaaaa = {aaaaaaaaaa, bbbbbbbbbb,\n" 8331 " cccccccccc, dddddddddd};", 8332 getLLVMStyleWithColumns(50)); 8333 verifyFormat("const Aaaaaa aaaaa = {\n" 8334 " aaaaaaaaaaa,\n" 8335 " bbbbbbbbbbb,\n" 8336 " ccccccccccc,\n" 8337 " ddddddddddd,\n" 8338 "};", 8339 getLLVMStyleWithColumns(50)); 8340 8341 // Cases where distinguising braced lists and blocks is hard. 8342 verifyFormat("vector<int> v{12} GUARDED_BY(mutex);"); 8343 verifyFormat("void f() {\n" 8344 " return; // comment\n" 8345 "}\n" 8346 "SomeType t;"); 8347 verifyFormat("void f() {\n" 8348 " if (a) {\n" 8349 " f();\n" 8350 " }\n" 8351 "}\n" 8352 "SomeType t;"); 8353 8354 // In combination with BinPackArguments = false. 8355 FormatStyle NoBinPacking = getLLVMStyle(); 8356 NoBinPacking.BinPackArguments = false; 8357 verifyFormat("const Aaaaaa aaaaa = {aaaaa,\n" 8358 " bbbbb,\n" 8359 " ccccc,\n" 8360 " ddddd,\n" 8361 " eeeee,\n" 8362 " ffffff,\n" 8363 " ggggg,\n" 8364 " hhhhhh,\n" 8365 " iiiiii,\n" 8366 " jjjjjj,\n" 8367 " kkkkkk};", 8368 NoBinPacking); 8369 verifyFormat("const Aaaaaa aaaaa = {\n" 8370 " aaaaa,\n" 8371 " bbbbb,\n" 8372 " ccccc,\n" 8373 " ddddd,\n" 8374 " eeeee,\n" 8375 " ffffff,\n" 8376 " ggggg,\n" 8377 " hhhhhh,\n" 8378 " iiiiii,\n" 8379 " jjjjjj,\n" 8380 " kkkkkk,\n" 8381 "};", 8382 NoBinPacking); 8383 verifyFormat( 8384 "const Aaaaaa aaaaa = {\n" 8385 " aaaaa, bbbbb, ccccc, ddddd, eeeee, ffffff, ggggg, hhhhhh,\n" 8386 " iiiiii, jjjjjj, kkkkkk, aaaaa, bbbbb, ccccc, ddddd, eeeee,\n" 8387 " ffffff, ggggg, hhhhhh, iiiiii, jjjjjj, kkkkkk,\n" 8388 "};", 8389 NoBinPacking); 8390 8391 NoBinPacking.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 8392 EXPECT_EQ("static uint8 CddDp83848Reg[] = {\n" 8393 " CDDDP83848_BMCR_REGISTER,\n" 8394 " CDDDP83848_BMSR_REGISTER,\n" 8395 " CDDDP83848_RBR_REGISTER};", 8396 format("static uint8 CddDp83848Reg[] = {CDDDP83848_BMCR_REGISTER,\n" 8397 " CDDDP83848_BMSR_REGISTER,\n" 8398 " CDDDP83848_RBR_REGISTER};", 8399 NoBinPacking)); 8400 8401 // FIXME: The alignment of these trailing comments might be bad. Then again, 8402 // this might be utterly useless in real code. 8403 verifyFormat("Constructor::Constructor()\n" 8404 " : some_value{ //\n" 8405 " aaaaaaa, //\n" 8406 " bbbbbbb} {}"); 8407 8408 // In braced lists, the first comment is always assumed to belong to the 8409 // first element. Thus, it can be moved to the next or previous line as 8410 // appropriate. 8411 EXPECT_EQ("function({// First element:\n" 8412 " 1,\n" 8413 " // Second element:\n" 8414 " 2});", 8415 format("function({\n" 8416 " // First element:\n" 8417 " 1,\n" 8418 " // Second element:\n" 8419 " 2});")); 8420 EXPECT_EQ("std::vector<int> MyNumbers{\n" 8421 " // First element:\n" 8422 " 1,\n" 8423 " // Second element:\n" 8424 " 2};", 8425 format("std::vector<int> MyNumbers{// First element:\n" 8426 " 1,\n" 8427 " // Second element:\n" 8428 " 2};", 8429 getLLVMStyleWithColumns(30))); 8430 // A trailing comma should still lead to an enforced line break and no 8431 // binpacking. 8432 EXPECT_EQ("vector<int> SomeVector = {\n" 8433 " // aaa\n" 8434 " 1,\n" 8435 " 2,\n" 8436 "};", 8437 format("vector<int> SomeVector = { // aaa\n" 8438 " 1, 2, };")); 8439 8440 // C++11 brace initializer list l-braces should not be treated any differently 8441 // when breaking before lambda bodies is enabled 8442 FormatStyle BreakBeforeLambdaBody = getLLVMStyle(); 8443 BreakBeforeLambdaBody.BreakBeforeBraces = FormatStyle::BS_Custom; 8444 BreakBeforeLambdaBody.BraceWrapping.BeforeLambdaBody = true; 8445 BreakBeforeLambdaBody.AlwaysBreakBeforeMultilineStrings = true; 8446 verifyFormat( 8447 "std::runtime_error{\n" 8448 " \"Long string which will force a break onto the next line...\"};", 8449 BreakBeforeLambdaBody); 8450 8451 FormatStyle ExtraSpaces = getLLVMStyle(); 8452 ExtraSpaces.Cpp11BracedListStyle = false; 8453 ExtraSpaces.ColumnLimit = 75; 8454 verifyFormat("vector<int> x{ 1, 2, 3, 4 };", ExtraSpaces); 8455 verifyFormat("vector<T> x{ {}, {}, {}, {} };", ExtraSpaces); 8456 verifyFormat("f({ 1, 2 });", ExtraSpaces); 8457 verifyFormat("auto v = Foo{ 1 };", ExtraSpaces); 8458 verifyFormat("f({ 1, 2 }, { { 2, 3 }, { 4, 5 } }, c, { d });", ExtraSpaces); 8459 verifyFormat("Class::Class : member{ 1, 2, 3 } {}", ExtraSpaces); 8460 verifyFormat("new vector<int>{ 1, 2, 3 };", ExtraSpaces); 8461 verifyFormat("new int[3]{ 1, 2, 3 };", ExtraSpaces); 8462 verifyFormat("return { arg1, arg2 };", ExtraSpaces); 8463 verifyFormat("return { arg1, SomeType{ parameter } };", ExtraSpaces); 8464 verifyFormat("int count = set<int>{ f(), g(), h() }.size();", ExtraSpaces); 8465 verifyFormat("new T{ arg1, arg2 };", ExtraSpaces); 8466 verifyFormat("f(MyMap[{ composite, key }]);", ExtraSpaces); 8467 verifyFormat("class Class {\n" 8468 " T member = { arg1, arg2 };\n" 8469 "};", 8470 ExtraSpaces); 8471 verifyFormat( 8472 "foo = aaaaaaaaaaa ? vector<int>{ aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8473 " aaaaaaaaaaaaaaaaaaaa, aaaaa }\n" 8474 " : vector<int>{ bbbbbbbbbbbbbbbbbbbbbbbbbbb,\n" 8475 " bbbbbbbbbbbbbbbbbbbb, bbbbb };", 8476 ExtraSpaces); 8477 verifyFormat("DoSomethingWithVector({} /* No data */);", ExtraSpaces); 8478 verifyFormat("DoSomethingWithVector({ {} /* No data */ }, { { 1, 2 } });", 8479 ExtraSpaces); 8480 verifyFormat( 8481 "someFunction(OtherParam,\n" 8482 " BracedList{ // comment 1 (Forcing interesting break)\n" 8483 " param1, param2,\n" 8484 " // comment 2\n" 8485 " param3, param4 });", 8486 ExtraSpaces); 8487 verifyFormat( 8488 "std::this_thread::sleep_for(\n" 8489 " std::chrono::nanoseconds{ std::chrono::seconds{ 1 } } / 5);", 8490 ExtraSpaces); 8491 verifyFormat("std::vector<MyValues> aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa{\n" 8492 " aaaaaaa,\n" 8493 " aaaaaaaaaa,\n" 8494 " aaaaa,\n" 8495 " aaaaaaaaaaaaaaa,\n" 8496 " aaa,\n" 8497 " aaaaaaaaaa,\n" 8498 " a,\n" 8499 " aaaaaaaaaaaaaaaaaaaaa,\n" 8500 " aaaaaaaaaaaa,\n" 8501 " aaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaa,\n" 8502 " aaaaaaa,\n" 8503 " a};"); 8504 verifyFormat("vector<int> foo = { ::SomeGlobalFunction() };", ExtraSpaces); 8505 verifyFormat("const struct A a = { .a = 1, .b = 2 };", ExtraSpaces); 8506 verifyFormat("const struct A a = { [0] = 1, [1] = 2 };", ExtraSpaces); 8507 8508 // Avoid breaking between initializer/equal sign and opening brace 8509 ExtraSpaces.PenaltyBreakBeforeFirstCallParameter = 200; 8510 verifyFormat("const std::unordered_map<std::string, int> MyHashTable = {\n" 8511 " { \"aaaaaaaaaaaaaaaaaaaaa\", 0 },\n" 8512 " { \"bbbbbbbbbbbbbbbbbbbbb\", 1 },\n" 8513 " { \"ccccccccccccccccccccc\", 2 }\n" 8514 "};", 8515 ExtraSpaces); 8516 verifyFormat("const std::unordered_map<std::string, int> MyHashTable{\n" 8517 " { \"aaaaaaaaaaaaaaaaaaaaa\", 0 },\n" 8518 " { \"bbbbbbbbbbbbbbbbbbbbb\", 1 },\n" 8519 " { \"ccccccccccccccccccccc\", 2 }\n" 8520 "};", 8521 ExtraSpaces); 8522 8523 FormatStyle SpaceBeforeBrace = getLLVMStyle(); 8524 SpaceBeforeBrace.SpaceBeforeCpp11BracedList = true; 8525 verifyFormat("vector<int> x {1, 2, 3, 4};", SpaceBeforeBrace); 8526 verifyFormat("f({}, {{}, {}}, MyMap[{k, v}]);", SpaceBeforeBrace); 8527 8528 FormatStyle SpaceBetweenBraces = getLLVMStyle(); 8529 SpaceBetweenBraces.SpacesInAngles = true; 8530 SpaceBetweenBraces.SpacesInParentheses = true; 8531 SpaceBetweenBraces.SpacesInSquareBrackets = true; 8532 verifyFormat("vector< int > x{ 1, 2, 3, 4 };", SpaceBetweenBraces); 8533 verifyFormat("f( {}, { {}, {} }, MyMap[ { k, v } ] );", SpaceBetweenBraces); 8534 verifyFormat("vector< int > x{ // comment 1\n" 8535 " 1, 2, 3, 4 };", 8536 SpaceBetweenBraces); 8537 SpaceBetweenBraces.ColumnLimit = 20; 8538 EXPECT_EQ("vector< int > x{\n" 8539 " 1, 2, 3, 4 };", 8540 format("vector<int>x{1,2,3,4};", SpaceBetweenBraces)); 8541 SpaceBetweenBraces.ColumnLimit = 24; 8542 EXPECT_EQ("vector< int > x{ 1, 2,\n" 8543 " 3, 4 };", 8544 format("vector<int>x{1,2,3,4};", SpaceBetweenBraces)); 8545 EXPECT_EQ("vector< int > x{\n" 8546 " 1,\n" 8547 " 2,\n" 8548 " 3,\n" 8549 " 4,\n" 8550 "};", 8551 format("vector<int>x{1,2,3,4,};", SpaceBetweenBraces)); 8552 verifyFormat("vector< int > x{};", SpaceBetweenBraces); 8553 SpaceBetweenBraces.SpaceInEmptyParentheses = true; 8554 verifyFormat("vector< int > x{ };", SpaceBetweenBraces); 8555 } 8556 8557 TEST_F(FormatTest, FormatSpacesInAngles) { 8558 FormatStyle SpaceInAngles = getLLVMStyle(); 8559 SpaceInAngles.SpacesInAngles = true; 8560 verifyFormat("vector< ::std::string > x1;", SpaceInAngles); 8561 verifyFormat("Foo< int, Bar > x2;", SpaceInAngles); 8562 verifyFormat("Foo< ::int, ::Bar > x3;", SpaceInAngles); 8563 8564 SpaceInAngles.SpacesInAngles = false; 8565 verifyFormat("vector<::std::string> x4;", SpaceInAngles); 8566 verifyFormat("vector<int> x5;", SpaceInAngles); 8567 verifyFormat("Foo<int, Bar> x6;", SpaceInAngles); 8568 verifyFormat("Foo<::int, ::Bar> x7;", SpaceInAngles); 8569 } 8570 8571 TEST_F(FormatTest, FormatsBracedListsInColumnLayout) { 8572 verifyFormat("vector<int> x = {1, 22, 333, 4444, 55555, 666666, 7777777,\n" 8573 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 8574 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 8575 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 8576 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 8577 " 1, 22, 333, 4444, 55555, 666666, 7777777};"); 8578 verifyFormat("vector<int> x = {1, 22, 333, 4444, 55555, 666666, 7777777, //\n" 8579 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 8580 " 1, 22, 333, 4444, 55555, //\n" 8581 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 8582 " 1, 22, 333, 4444, 55555, 666666, 7777777};"); 8583 verifyFormat( 8584 "vector<int> x = {1, 22, 333, 4444, 55555, 666666, 7777777,\n" 8585 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 8586 " 1, 22, 333, 4444, 55555, 666666, // comment\n" 8587 " 7777777, 1, 22, 333, 4444, 55555, 666666,\n" 8588 " 7777777, 1, 22, 333, 4444, 55555, 666666,\n" 8589 " 7777777, 1, 22, 333, 4444, 55555, 666666,\n" 8590 " 7777777};"); 8591 verifyFormat("static const uint16_t CallerSavedRegs64Bittttt[] = {\n" 8592 " X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,\n" 8593 " X86::R8, X86::R9, X86::R10, X86::R11, 0};"); 8594 verifyFormat("static const uint16_t CallerSavedRegs64Bittttt[] = {\n" 8595 " X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,\n" 8596 " // Separating comment.\n" 8597 " X86::R8, X86::R9, X86::R10, X86::R11, 0};"); 8598 verifyFormat("static const uint16_t CallerSavedRegs64Bittttt[] = {\n" 8599 " // Leading comment\n" 8600 " X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,\n" 8601 " X86::R8, X86::R9, X86::R10, X86::R11, 0};"); 8602 verifyFormat("vector<int> x = {1, 1, 1, 1,\n" 8603 " 1, 1, 1, 1};", 8604 getLLVMStyleWithColumns(39)); 8605 verifyFormat("vector<int> x = {1, 1, 1, 1,\n" 8606 " 1, 1, 1, 1};", 8607 getLLVMStyleWithColumns(38)); 8608 verifyFormat("vector<int> aaaaaaaaaaaaaaaaaaaaaa = {\n" 8609 " 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1};", 8610 getLLVMStyleWithColumns(43)); 8611 verifyFormat( 8612 "static unsigned SomeValues[10][3] = {\n" 8613 " {1, 4, 0}, {4, 9, 0}, {4, 5, 9}, {8, 5, 4}, {1, 8, 4},\n" 8614 " {10, 1, 6}, {11, 0, 9}, {2, 11, 9}, {5, 2, 9}, {11, 2, 7}};"); 8615 verifyFormat("static auto fields = new vector<string>{\n" 8616 " \"aaaaaaaaaaaaa\",\n" 8617 " \"aaaaaaaaaaaaa\",\n" 8618 " \"aaaaaaaaaaaa\",\n" 8619 " \"aaaaaaaaaaaaaa\",\n" 8620 " \"aaaaaaaaaaaaaaaaaaaaaaaaa\",\n" 8621 " \"aaaaaaaaaaaa\",\n" 8622 " \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\n" 8623 "};"); 8624 verifyFormat("vector<int> x = {1, 2, 3, 4, aaaaaaaaaaaaaaaaa, 6};"); 8625 verifyFormat("vector<int> x = {1, aaaaaaaaaaaaaaaaaaaaaa,\n" 8626 " 2, bbbbbbbbbbbbbbbbbbbbbb,\n" 8627 " 3, cccccccccccccccccccccc};", 8628 getLLVMStyleWithColumns(60)); 8629 8630 // Trailing commas. 8631 verifyFormat("vector<int> x = {\n" 8632 " 1, 1, 1, 1, 1, 1, 1, 1,\n" 8633 "};", 8634 getLLVMStyleWithColumns(39)); 8635 verifyFormat("vector<int> x = {\n" 8636 " 1, 1, 1, 1, 1, 1, 1, 1, //\n" 8637 "};", 8638 getLLVMStyleWithColumns(39)); 8639 verifyFormat("vector<int> x = {1, 1, 1, 1,\n" 8640 " 1, 1, 1, 1,\n" 8641 " /**/ /**/};", 8642 getLLVMStyleWithColumns(39)); 8643 8644 // Trailing comment in the first line. 8645 verifyFormat("vector<int> iiiiiiiiiiiiiii = { //\n" 8646 " 1111111111, 2222222222, 33333333333, 4444444444, //\n" 8647 " 111111111, 222222222, 3333333333, 444444444, //\n" 8648 " 11111111, 22222222, 333333333, 44444444};"); 8649 // Trailing comment in the last line. 8650 verifyFormat("int aaaaa[] = {\n" 8651 " 1, 2, 3, // comment\n" 8652 " 4, 5, 6 // comment\n" 8653 "};"); 8654 8655 // With nested lists, we should either format one item per line or all nested 8656 // lists one on line. 8657 // FIXME: For some nested lists, we can do better. 8658 verifyFormat("return {{aaaaaaaaaaaaaaaaaaaaa},\n" 8659 " {aaaaaaaaaaaaaaaaaaa},\n" 8660 " {aaaaaaaaaaaaaaaaaaaaa},\n" 8661 " {aaaaaaaaaaaaaaaaa}};", 8662 getLLVMStyleWithColumns(60)); 8663 verifyFormat( 8664 "SomeStruct my_struct_array = {\n" 8665 " {aaaaaa, aaaaaaaa, aaaaaaaaaa, aaaaaaaaa, aaaaaaaaa, aaaaaaaaaa,\n" 8666 " aaaaaaaaaaaaa, aaaaaaa, aaa},\n" 8667 " {aaa, aaa},\n" 8668 " {aaa, aaa},\n" 8669 " {aaaa, aaaa, aaaa, aaaa, aaaa, aaaa, aaaa, aaa},\n" 8670 " {aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaa,\n" 8671 " aaaaaaaaaaaa, a, aaaaaaaaaa, aaaaaaaaa, aaa}};"); 8672 8673 // No column layout should be used here. 8674 verifyFormat("aaaaaaaaaaaaaaa = {aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, 0, 0,\n" 8675 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb};"); 8676 8677 verifyNoCrash("a<,"); 8678 8679 // No braced initializer here. 8680 verifyFormat("void f() {\n" 8681 " struct Dummy {};\n" 8682 " f(v);\n" 8683 "}"); 8684 8685 // Long lists should be formatted in columns even if they are nested. 8686 verifyFormat( 8687 "vector<int> x = function({1, 22, 333, 4444, 55555, 666666, 7777777,\n" 8688 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 8689 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 8690 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 8691 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 8692 " 1, 22, 333, 4444, 55555, 666666, 7777777});"); 8693 8694 // Allow "single-column" layout even if that violates the column limit. There 8695 // isn't going to be a better way. 8696 verifyFormat("std::vector<int> a = {\n" 8697 " aaaaaaaa,\n" 8698 " aaaaaaaa,\n" 8699 " aaaaaaaa,\n" 8700 " aaaaaaaa,\n" 8701 " aaaaaaaaaa,\n" 8702 " aaaaaaaa,\n" 8703 " aaaaaaaaaaaaaaaaaaaaaaaaaaa};", 8704 getLLVMStyleWithColumns(30)); 8705 verifyFormat("vector<int> aaaa = {\n" 8706 " aaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8707 " aaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8708 " aaaaaa.aaaaaaa,\n" 8709 " aaaaaa.aaaaaaa,\n" 8710 " aaaaaa.aaaaaaa,\n" 8711 " aaaaaa.aaaaaaa,\n" 8712 "};"); 8713 8714 // Don't create hanging lists. 8715 verifyFormat("someFunction(Param, {List1, List2,\n" 8716 " List3});", 8717 getLLVMStyleWithColumns(35)); 8718 verifyFormat("someFunction(Param, Param,\n" 8719 " {List1, List2,\n" 8720 " List3});", 8721 getLLVMStyleWithColumns(35)); 8722 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaa, {},\n" 8723 " aaaaaaaaaaaaaaaaaaaaaaa);"); 8724 } 8725 8726 TEST_F(FormatTest, PullTrivialFunctionDefinitionsIntoSingleLine) { 8727 FormatStyle DoNotMerge = getLLVMStyle(); 8728 DoNotMerge.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 8729 8730 verifyFormat("void f() { return 42; }"); 8731 verifyFormat("void f() {\n" 8732 " return 42;\n" 8733 "}", 8734 DoNotMerge); 8735 verifyFormat("void f() {\n" 8736 " // Comment\n" 8737 "}"); 8738 verifyFormat("{\n" 8739 "#error {\n" 8740 " int a;\n" 8741 "}"); 8742 verifyFormat("{\n" 8743 " int a;\n" 8744 "#error {\n" 8745 "}"); 8746 verifyFormat("void f() {} // comment"); 8747 verifyFormat("void f() { int a; } // comment"); 8748 verifyFormat("void f() {\n" 8749 "} // comment", 8750 DoNotMerge); 8751 verifyFormat("void f() {\n" 8752 " int a;\n" 8753 "} // comment", 8754 DoNotMerge); 8755 verifyFormat("void f() {\n" 8756 "} // comment", 8757 getLLVMStyleWithColumns(15)); 8758 8759 verifyFormat("void f() { return 42; }", getLLVMStyleWithColumns(23)); 8760 verifyFormat("void f() {\n return 42;\n}", getLLVMStyleWithColumns(22)); 8761 8762 verifyFormat("void f() {}", getLLVMStyleWithColumns(11)); 8763 verifyFormat("void f() {\n}", getLLVMStyleWithColumns(10)); 8764 verifyFormat("class C {\n" 8765 " C()\n" 8766 " : iiiiiiii(nullptr),\n" 8767 " kkkkkkk(nullptr),\n" 8768 " mmmmmmm(nullptr),\n" 8769 " nnnnnnn(nullptr) {}\n" 8770 "};", 8771 getGoogleStyle()); 8772 8773 FormatStyle NoColumnLimit = getLLVMStyle(); 8774 NoColumnLimit.ColumnLimit = 0; 8775 EXPECT_EQ("A() : b(0) {}", format("A():b(0){}", NoColumnLimit)); 8776 EXPECT_EQ("class C {\n" 8777 " A() : b(0) {}\n" 8778 "};", 8779 format("class C{A():b(0){}};", NoColumnLimit)); 8780 EXPECT_EQ("A()\n" 8781 " : b(0) {\n" 8782 "}", 8783 format("A()\n:b(0)\n{\n}", NoColumnLimit)); 8784 8785 FormatStyle DoNotMergeNoColumnLimit = NoColumnLimit; 8786 DoNotMergeNoColumnLimit.AllowShortFunctionsOnASingleLine = 8787 FormatStyle::SFS_None; 8788 EXPECT_EQ("A()\n" 8789 " : b(0) {\n" 8790 "}", 8791 format("A():b(0){}", DoNotMergeNoColumnLimit)); 8792 EXPECT_EQ("A()\n" 8793 " : b(0) {\n" 8794 "}", 8795 format("A()\n:b(0)\n{\n}", DoNotMergeNoColumnLimit)); 8796 8797 verifyFormat("#define A \\\n" 8798 " void f() { \\\n" 8799 " int i; \\\n" 8800 " }", 8801 getLLVMStyleWithColumns(20)); 8802 verifyFormat("#define A \\\n" 8803 " void f() { int i; }", 8804 getLLVMStyleWithColumns(21)); 8805 verifyFormat("#define A \\\n" 8806 " void f() { \\\n" 8807 " int i; \\\n" 8808 " } \\\n" 8809 " int j;", 8810 getLLVMStyleWithColumns(22)); 8811 verifyFormat("#define A \\\n" 8812 " void f() { int i; } \\\n" 8813 " int j;", 8814 getLLVMStyleWithColumns(23)); 8815 } 8816 8817 TEST_F(FormatTest, PullEmptyFunctionDefinitionsIntoSingleLine) { 8818 FormatStyle MergeEmptyOnly = getLLVMStyle(); 8819 MergeEmptyOnly.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty; 8820 verifyFormat("class C {\n" 8821 " int f() {}\n" 8822 "};", 8823 MergeEmptyOnly); 8824 verifyFormat("class C {\n" 8825 " int f() {\n" 8826 " return 42;\n" 8827 " }\n" 8828 "};", 8829 MergeEmptyOnly); 8830 verifyFormat("int f() {}", MergeEmptyOnly); 8831 verifyFormat("int f() {\n" 8832 " return 42;\n" 8833 "}", 8834 MergeEmptyOnly); 8835 8836 // Also verify behavior when BraceWrapping.AfterFunction = true 8837 MergeEmptyOnly.BreakBeforeBraces = FormatStyle::BS_Custom; 8838 MergeEmptyOnly.BraceWrapping.AfterFunction = true; 8839 verifyFormat("int f() {}", MergeEmptyOnly); 8840 verifyFormat("class C {\n" 8841 " int f() {}\n" 8842 "};", 8843 MergeEmptyOnly); 8844 } 8845 8846 TEST_F(FormatTest, PullInlineFunctionDefinitionsIntoSingleLine) { 8847 FormatStyle MergeInlineOnly = getLLVMStyle(); 8848 MergeInlineOnly.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline; 8849 verifyFormat("class C {\n" 8850 " int f() { return 42; }\n" 8851 "};", 8852 MergeInlineOnly); 8853 verifyFormat("int f() {\n" 8854 " return 42;\n" 8855 "}", 8856 MergeInlineOnly); 8857 8858 // SFS_Inline implies SFS_Empty 8859 verifyFormat("class C {\n" 8860 " int f() {}\n" 8861 "};", 8862 MergeInlineOnly); 8863 verifyFormat("int f() {}", MergeInlineOnly); 8864 8865 // Also verify behavior when BraceWrapping.AfterFunction = true 8866 MergeInlineOnly.BreakBeforeBraces = FormatStyle::BS_Custom; 8867 MergeInlineOnly.BraceWrapping.AfterFunction = true; 8868 verifyFormat("class C {\n" 8869 " int f() { return 42; }\n" 8870 "};", 8871 MergeInlineOnly); 8872 verifyFormat("int f()\n" 8873 "{\n" 8874 " return 42;\n" 8875 "}", 8876 MergeInlineOnly); 8877 8878 // SFS_Inline implies SFS_Empty 8879 verifyFormat("int f() {}", MergeInlineOnly); 8880 verifyFormat("class C {\n" 8881 " int f() {}\n" 8882 "};", 8883 MergeInlineOnly); 8884 } 8885 8886 TEST_F(FormatTest, PullInlineOnlyFunctionDefinitionsIntoSingleLine) { 8887 FormatStyle MergeInlineOnly = getLLVMStyle(); 8888 MergeInlineOnly.AllowShortFunctionsOnASingleLine = 8889 FormatStyle::SFS_InlineOnly; 8890 verifyFormat("class C {\n" 8891 " int f() { return 42; }\n" 8892 "};", 8893 MergeInlineOnly); 8894 verifyFormat("int f() {\n" 8895 " return 42;\n" 8896 "}", 8897 MergeInlineOnly); 8898 8899 // SFS_InlineOnly does not imply SFS_Empty 8900 verifyFormat("class C {\n" 8901 " int f() {}\n" 8902 "};", 8903 MergeInlineOnly); 8904 verifyFormat("int f() {\n" 8905 "}", 8906 MergeInlineOnly); 8907 8908 // Also verify behavior when BraceWrapping.AfterFunction = true 8909 MergeInlineOnly.BreakBeforeBraces = FormatStyle::BS_Custom; 8910 MergeInlineOnly.BraceWrapping.AfterFunction = true; 8911 verifyFormat("class C {\n" 8912 " int f() { return 42; }\n" 8913 "};", 8914 MergeInlineOnly); 8915 verifyFormat("int f()\n" 8916 "{\n" 8917 " return 42;\n" 8918 "}", 8919 MergeInlineOnly); 8920 8921 // SFS_InlineOnly does not imply SFS_Empty 8922 verifyFormat("int f()\n" 8923 "{\n" 8924 "}", 8925 MergeInlineOnly); 8926 verifyFormat("class C {\n" 8927 " int f() {}\n" 8928 "};", 8929 MergeInlineOnly); 8930 } 8931 8932 TEST_F(FormatTest, SplitEmptyFunction) { 8933 FormatStyle Style = getLLVMStyle(); 8934 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 8935 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 8936 Style.BraceWrapping.AfterFunction = true; 8937 Style.BraceWrapping.SplitEmptyFunction = false; 8938 Style.ColumnLimit = 40; 8939 8940 verifyFormat("int f()\n" 8941 "{}", 8942 Style); 8943 verifyFormat("int f()\n" 8944 "{\n" 8945 " return 42;\n" 8946 "}", 8947 Style); 8948 verifyFormat("int f()\n" 8949 "{\n" 8950 " // some comment\n" 8951 "}", 8952 Style); 8953 8954 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty; 8955 verifyFormat("int f() {}", Style); 8956 verifyFormat("int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n" 8957 "{}", 8958 Style); 8959 verifyFormat("int f()\n" 8960 "{\n" 8961 " return 0;\n" 8962 "}", 8963 Style); 8964 8965 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline; 8966 verifyFormat("class Foo {\n" 8967 " int f() {}\n" 8968 "};\n", 8969 Style); 8970 verifyFormat("class Foo {\n" 8971 " int f() { return 0; }\n" 8972 "};\n", 8973 Style); 8974 verifyFormat("class Foo {\n" 8975 " int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n" 8976 " {}\n" 8977 "};\n", 8978 Style); 8979 verifyFormat("class Foo {\n" 8980 " int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n" 8981 " {\n" 8982 " return 0;\n" 8983 " }\n" 8984 "};\n", 8985 Style); 8986 8987 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All; 8988 verifyFormat("int f() {}", Style); 8989 verifyFormat("int f() { return 0; }", Style); 8990 verifyFormat("int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n" 8991 "{}", 8992 Style); 8993 verifyFormat("int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n" 8994 "{\n" 8995 " return 0;\n" 8996 "}", 8997 Style); 8998 } 8999 TEST_F(FormatTest, KeepShortFunctionAfterPPElse) { 9000 FormatStyle Style = getLLVMStyle(); 9001 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All; 9002 verifyFormat("#ifdef A\n" 9003 "int f() {}\n" 9004 "#else\n" 9005 "int g() {}\n" 9006 "#endif", 9007 Style); 9008 } 9009 9010 TEST_F(FormatTest, SplitEmptyClass) { 9011 FormatStyle Style = getLLVMStyle(); 9012 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 9013 Style.BraceWrapping.AfterClass = true; 9014 Style.BraceWrapping.SplitEmptyRecord = false; 9015 9016 verifyFormat("class Foo\n" 9017 "{};", 9018 Style); 9019 verifyFormat("/* something */ class Foo\n" 9020 "{};", 9021 Style); 9022 verifyFormat("template <typename X> class Foo\n" 9023 "{};", 9024 Style); 9025 verifyFormat("class Foo\n" 9026 "{\n" 9027 " Foo();\n" 9028 "};", 9029 Style); 9030 verifyFormat("typedef class Foo\n" 9031 "{\n" 9032 "} Foo_t;", 9033 Style); 9034 } 9035 9036 TEST_F(FormatTest, SplitEmptyStruct) { 9037 FormatStyle Style = getLLVMStyle(); 9038 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 9039 Style.BraceWrapping.AfterStruct = true; 9040 Style.BraceWrapping.SplitEmptyRecord = false; 9041 9042 verifyFormat("struct Foo\n" 9043 "{};", 9044 Style); 9045 verifyFormat("/* something */ struct Foo\n" 9046 "{};", 9047 Style); 9048 verifyFormat("template <typename X> struct Foo\n" 9049 "{};", 9050 Style); 9051 verifyFormat("struct Foo\n" 9052 "{\n" 9053 " Foo();\n" 9054 "};", 9055 Style); 9056 verifyFormat("typedef struct Foo\n" 9057 "{\n" 9058 "} Foo_t;", 9059 Style); 9060 // typedef struct Bar {} Bar_t; 9061 } 9062 9063 TEST_F(FormatTest, SplitEmptyUnion) { 9064 FormatStyle Style = getLLVMStyle(); 9065 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 9066 Style.BraceWrapping.AfterUnion = true; 9067 Style.BraceWrapping.SplitEmptyRecord = false; 9068 9069 verifyFormat("union Foo\n" 9070 "{};", 9071 Style); 9072 verifyFormat("/* something */ union Foo\n" 9073 "{};", 9074 Style); 9075 verifyFormat("union Foo\n" 9076 "{\n" 9077 " A,\n" 9078 "};", 9079 Style); 9080 verifyFormat("typedef union Foo\n" 9081 "{\n" 9082 "} Foo_t;", 9083 Style); 9084 } 9085 9086 TEST_F(FormatTest, SplitEmptyNamespace) { 9087 FormatStyle Style = getLLVMStyle(); 9088 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 9089 Style.BraceWrapping.AfterNamespace = true; 9090 Style.BraceWrapping.SplitEmptyNamespace = false; 9091 9092 verifyFormat("namespace Foo\n" 9093 "{};", 9094 Style); 9095 verifyFormat("/* something */ namespace Foo\n" 9096 "{};", 9097 Style); 9098 verifyFormat("inline namespace Foo\n" 9099 "{};", 9100 Style); 9101 verifyFormat("/* something */ inline namespace Foo\n" 9102 "{};", 9103 Style); 9104 verifyFormat("export namespace Foo\n" 9105 "{};", 9106 Style); 9107 verifyFormat("namespace Foo\n" 9108 "{\n" 9109 "void Bar();\n" 9110 "};", 9111 Style); 9112 } 9113 9114 TEST_F(FormatTest, NeverMergeShortRecords) { 9115 FormatStyle Style = getLLVMStyle(); 9116 9117 verifyFormat("class Foo {\n" 9118 " Foo();\n" 9119 "};", 9120 Style); 9121 verifyFormat("typedef class Foo {\n" 9122 " Foo();\n" 9123 "} Foo_t;", 9124 Style); 9125 verifyFormat("struct Foo {\n" 9126 " Foo();\n" 9127 "};", 9128 Style); 9129 verifyFormat("typedef struct Foo {\n" 9130 " Foo();\n" 9131 "} Foo_t;", 9132 Style); 9133 verifyFormat("union Foo {\n" 9134 " A,\n" 9135 "};", 9136 Style); 9137 verifyFormat("typedef union Foo {\n" 9138 " A,\n" 9139 "} Foo_t;", 9140 Style); 9141 verifyFormat("namespace Foo {\n" 9142 "void Bar();\n" 9143 "};", 9144 Style); 9145 9146 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 9147 Style.BraceWrapping.AfterClass = true; 9148 Style.BraceWrapping.AfterStruct = true; 9149 Style.BraceWrapping.AfterUnion = true; 9150 Style.BraceWrapping.AfterNamespace = true; 9151 verifyFormat("class Foo\n" 9152 "{\n" 9153 " Foo();\n" 9154 "};", 9155 Style); 9156 verifyFormat("typedef class Foo\n" 9157 "{\n" 9158 " Foo();\n" 9159 "} Foo_t;", 9160 Style); 9161 verifyFormat("struct Foo\n" 9162 "{\n" 9163 " Foo();\n" 9164 "};", 9165 Style); 9166 verifyFormat("typedef struct Foo\n" 9167 "{\n" 9168 " Foo();\n" 9169 "} Foo_t;", 9170 Style); 9171 verifyFormat("union Foo\n" 9172 "{\n" 9173 " A,\n" 9174 "};", 9175 Style); 9176 verifyFormat("typedef union Foo\n" 9177 "{\n" 9178 " A,\n" 9179 "} Foo_t;", 9180 Style); 9181 verifyFormat("namespace Foo\n" 9182 "{\n" 9183 "void Bar();\n" 9184 "};", 9185 Style); 9186 } 9187 9188 TEST_F(FormatTest, UnderstandContextOfRecordTypeKeywords) { 9189 // Elaborate type variable declarations. 9190 verifyFormat("struct foo a = {bar};\nint n;"); 9191 verifyFormat("class foo a = {bar};\nint n;"); 9192 verifyFormat("union foo a = {bar};\nint n;"); 9193 9194 // Elaborate types inside function definitions. 9195 verifyFormat("struct foo f() {}\nint n;"); 9196 verifyFormat("class foo f() {}\nint n;"); 9197 verifyFormat("union foo f() {}\nint n;"); 9198 9199 // Templates. 9200 verifyFormat("template <class X> void f() {}\nint n;"); 9201 verifyFormat("template <struct X> void f() {}\nint n;"); 9202 verifyFormat("template <union X> void f() {}\nint n;"); 9203 9204 // Actual definitions... 9205 verifyFormat("struct {\n} n;"); 9206 verifyFormat( 9207 "template <template <class T, class Y>, class Z> class X {\n} n;"); 9208 verifyFormat("union Z {\n int n;\n} x;"); 9209 verifyFormat("class MACRO Z {\n} n;"); 9210 verifyFormat("class MACRO(X) Z {\n} n;"); 9211 verifyFormat("class __attribute__(X) Z {\n} n;"); 9212 verifyFormat("class __declspec(X) Z {\n} n;"); 9213 verifyFormat("class A##B##C {\n} n;"); 9214 verifyFormat("class alignas(16) Z {\n} n;"); 9215 verifyFormat("class MACRO(X) alignas(16) Z {\n} n;"); 9216 verifyFormat("class MACROA MACRO(X) Z {\n} n;"); 9217 9218 // Redefinition from nested context: 9219 verifyFormat("class A::B::C {\n} n;"); 9220 9221 // Template definitions. 9222 verifyFormat( 9223 "template <typename F>\n" 9224 "Matcher(const Matcher<F> &Other,\n" 9225 " typename enable_if_c<is_base_of<F, T>::value &&\n" 9226 " !is_same<F, T>::value>::type * = 0)\n" 9227 " : Implementation(new ImplicitCastMatcher<F>(Other)) {}"); 9228 9229 // FIXME: This is still incorrectly handled at the formatter side. 9230 verifyFormat("template <> struct X < 15, i<3 && 42 < 50 && 33 < 28> {};"); 9231 verifyFormat("int i = SomeFunction(a<b, a> b);"); 9232 9233 // FIXME: 9234 // This now gets parsed incorrectly as class definition. 9235 // verifyFormat("class A<int> f() {\n}\nint n;"); 9236 9237 // Elaborate types where incorrectly parsing the structural element would 9238 // break the indent. 9239 verifyFormat("if (true)\n" 9240 " class X x;\n" 9241 "else\n" 9242 " f();\n"); 9243 9244 // This is simply incomplete. Formatting is not important, but must not crash. 9245 verifyFormat("class A:"); 9246 } 9247 9248 TEST_F(FormatTest, DoNotInterfereWithErrorAndWarning) { 9249 EXPECT_EQ("#error Leave all white!!!!! space* alone!\n", 9250 format("#error Leave all white!!!!! space* alone!\n")); 9251 EXPECT_EQ( 9252 "#warning Leave all white!!!!! space* alone!\n", 9253 format("#warning Leave all white!!!!! space* alone!\n")); 9254 EXPECT_EQ("#error 1", format(" # error 1")); 9255 EXPECT_EQ("#warning 1", format(" # warning 1")); 9256 } 9257 9258 TEST_F(FormatTest, FormatHashIfExpressions) { 9259 verifyFormat("#if AAAA && BBBB"); 9260 verifyFormat("#if (AAAA && BBBB)"); 9261 verifyFormat("#elif (AAAA && BBBB)"); 9262 // FIXME: Come up with a better indentation for #elif. 9263 verifyFormat( 9264 "#if !defined(AAAAAAA) && (defined CCCCCC || defined DDDDDD) && \\\n" 9265 " defined(BBBBBBBB)\n" 9266 "#elif !defined(AAAAAA) && (defined CCCCC || defined DDDDDD) && \\\n" 9267 " defined(BBBBBBBB)\n" 9268 "#endif", 9269 getLLVMStyleWithColumns(65)); 9270 } 9271 9272 TEST_F(FormatTest, MergeHandlingInTheFaceOfPreprocessorDirectives) { 9273 FormatStyle AllowsMergedIf = getGoogleStyle(); 9274 AllowsMergedIf.AllowShortIfStatementsOnASingleLine = 9275 FormatStyle::SIS_WithoutElse; 9276 verifyFormat("void f() { f(); }\n#error E", AllowsMergedIf); 9277 verifyFormat("if (true) return 42;\n#error E", AllowsMergedIf); 9278 verifyFormat("if (true)\n#error E\n return 42;", AllowsMergedIf); 9279 EXPECT_EQ("if (true) return 42;", 9280 format("if (true)\nreturn 42;", AllowsMergedIf)); 9281 FormatStyle ShortMergedIf = AllowsMergedIf; 9282 ShortMergedIf.ColumnLimit = 25; 9283 verifyFormat("#define A \\\n" 9284 " if (true) return 42;", 9285 ShortMergedIf); 9286 verifyFormat("#define A \\\n" 9287 " f(); \\\n" 9288 " if (true)\n" 9289 "#define B", 9290 ShortMergedIf); 9291 verifyFormat("#define A \\\n" 9292 " f(); \\\n" 9293 " if (true)\n" 9294 "g();", 9295 ShortMergedIf); 9296 verifyFormat("{\n" 9297 "#ifdef A\n" 9298 " // Comment\n" 9299 " if (true) continue;\n" 9300 "#endif\n" 9301 " // Comment\n" 9302 " if (true) continue;\n" 9303 "}", 9304 ShortMergedIf); 9305 ShortMergedIf.ColumnLimit = 33; 9306 verifyFormat("#define A \\\n" 9307 " if constexpr (true) return 42;", 9308 ShortMergedIf); 9309 verifyFormat("#define A \\\n" 9310 " if CONSTEXPR (true) return 42;", 9311 ShortMergedIf); 9312 ShortMergedIf.ColumnLimit = 29; 9313 verifyFormat("#define A \\\n" 9314 " if (aaaaaaaaaa) return 1; \\\n" 9315 " return 2;", 9316 ShortMergedIf); 9317 ShortMergedIf.ColumnLimit = 28; 9318 verifyFormat("#define A \\\n" 9319 " if (aaaaaaaaaa) \\\n" 9320 " return 1; \\\n" 9321 " return 2;", 9322 ShortMergedIf); 9323 verifyFormat("#define A \\\n" 9324 " if constexpr (aaaaaaa) \\\n" 9325 " return 1; \\\n" 9326 " return 2;", 9327 ShortMergedIf); 9328 verifyFormat("#define A \\\n" 9329 " if CONSTEXPR (aaaaaaa) \\\n" 9330 " return 1; \\\n" 9331 " return 2;", 9332 ShortMergedIf); 9333 } 9334 9335 TEST_F(FormatTest, FormatStarDependingOnContext) { 9336 verifyFormat("void f(int *a);"); 9337 verifyFormat("void f() { f(fint * b); }"); 9338 verifyFormat("class A {\n void f(int *a);\n};"); 9339 verifyFormat("class A {\n int *a;\n};"); 9340 verifyFormat("namespace a {\n" 9341 "namespace b {\n" 9342 "class A {\n" 9343 " void f() {}\n" 9344 " int *a;\n" 9345 "};\n" 9346 "} // namespace b\n" 9347 "} // namespace a"); 9348 } 9349 9350 TEST_F(FormatTest, SpecialTokensAtEndOfLine) { 9351 verifyFormat("while"); 9352 verifyFormat("operator"); 9353 } 9354 9355 TEST_F(FormatTest, SkipsDeeplyNestedLines) { 9356 // This code would be painfully slow to format if we didn't skip it. 9357 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 9358 "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n" 9359 "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n" 9360 "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n" 9361 "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n" 9362 "A(1, 1)\n" 9363 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" // 10x 9364 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 9365 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 9366 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 9367 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 9368 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 9369 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 9370 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 9371 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 9372 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1);\n"); 9373 // Deeply nested part is untouched, rest is formatted. 9374 EXPECT_EQ(std::string("int i;\n") + Code + "int j;\n", 9375 format(std::string("int i;\n") + Code + "int j;\n", 9376 getLLVMStyle(), SC_ExpectIncomplete)); 9377 } 9378 9379 //===----------------------------------------------------------------------===// 9380 // Objective-C tests. 9381 //===----------------------------------------------------------------------===// 9382 9383 TEST_F(FormatTest, FormatForObjectiveCMethodDecls) { 9384 verifyFormat("- (void)sendAction:(SEL)aSelector to:(BOOL)anObject;"); 9385 EXPECT_EQ("- (NSUInteger)indexOfObject:(id)anObject;", 9386 format("-(NSUInteger)indexOfObject:(id)anObject;")); 9387 EXPECT_EQ("- (NSInteger)Mthod1;", format("-(NSInteger)Mthod1;")); 9388 EXPECT_EQ("+ (id)Mthod2;", format("+(id)Mthod2;")); 9389 EXPECT_EQ("- (NSInteger)Method3:(id)anObject;", 9390 format("-(NSInteger)Method3:(id)anObject;")); 9391 EXPECT_EQ("- (NSInteger)Method4:(id)anObject;", 9392 format("-(NSInteger)Method4:(id)anObject;")); 9393 EXPECT_EQ("- (NSInteger)Method5:(id)anObject:(id)AnotherObject;", 9394 format("-(NSInteger)Method5:(id)anObject:(id)AnotherObject;")); 9395 EXPECT_EQ("- (id)Method6:(id)A:(id)B:(id)C:(id)D;", 9396 format("- (id)Method6:(id)A:(id)B:(id)C:(id)D;")); 9397 EXPECT_EQ("- (void)sendAction:(SEL)aSelector to:(id)anObject " 9398 "forAllCells:(BOOL)flag;", 9399 format("- (void)sendAction:(SEL)aSelector to:(id)anObject " 9400 "forAllCells:(BOOL)flag;")); 9401 9402 // Very long objectiveC method declaration. 9403 verifyFormat("- (void)aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa:\n" 9404 " (SoooooooooooooooooooooomeType *)bbbbbbbbbb;"); 9405 verifyFormat("- (NSUInteger)indexOfObject:(id)anObject\n" 9406 " inRange:(NSRange)range\n" 9407 " outRange:(NSRange)out_range\n" 9408 " outRange1:(NSRange)out_range1\n" 9409 " outRange2:(NSRange)out_range2\n" 9410 " outRange3:(NSRange)out_range3\n" 9411 " outRange4:(NSRange)out_range4\n" 9412 " outRange5:(NSRange)out_range5\n" 9413 " outRange6:(NSRange)out_range6\n" 9414 " outRange7:(NSRange)out_range7\n" 9415 " outRange8:(NSRange)out_range8\n" 9416 " outRange9:(NSRange)out_range9;"); 9417 9418 // When the function name has to be wrapped. 9419 FormatStyle Style = getLLVMStyle(); 9420 // ObjC ignores IndentWrappedFunctionNames when wrapping methods 9421 // and always indents instead. 9422 Style.IndentWrappedFunctionNames = false; 9423 verifyFormat("- (SomeLooooooooooooooooooooongType *)\n" 9424 " veryLooooooooooongName:(NSString)aaaaaaaaaaaaaa\n" 9425 " anotherName:(NSString)bbbbbbbbbbbbbb {\n" 9426 "}", 9427 Style); 9428 Style.IndentWrappedFunctionNames = true; 9429 verifyFormat("- (SomeLooooooooooooooooooooongType *)\n" 9430 " veryLooooooooooongName:(NSString)cccccccccccccc\n" 9431 " anotherName:(NSString)dddddddddddddd {\n" 9432 "}", 9433 Style); 9434 9435 verifyFormat("- (int)sum:(vector<int>)numbers;"); 9436 verifyGoogleFormat("- (void)setDelegate:(id<Protocol>)delegate;"); 9437 // FIXME: In LLVM style, there should be a space in front of a '<' for ObjC 9438 // protocol lists (but not for template classes): 9439 // verifyFormat("- (void)setDelegate:(id <Protocol>)delegate;"); 9440 9441 verifyFormat("- (int (*)())foo:(int (*)())f;"); 9442 verifyGoogleFormat("- (int (*)())foo:(int (*)())foo;"); 9443 9444 // If there's no return type (very rare in practice!), LLVM and Google style 9445 // agree. 9446 verifyFormat("- foo;"); 9447 verifyFormat("- foo:(int)f;"); 9448 verifyGoogleFormat("- foo:(int)foo;"); 9449 } 9450 9451 TEST_F(FormatTest, BreaksStringLiterals) { 9452 EXPECT_EQ("\"some text \"\n" 9453 "\"other\";", 9454 format("\"some text other\";", getLLVMStyleWithColumns(12))); 9455 EXPECT_EQ("\"some text \"\n" 9456 "\"other\";", 9457 format("\\\n\"some text other\";", getLLVMStyleWithColumns(12))); 9458 EXPECT_EQ( 9459 "#define A \\\n" 9460 " \"some \" \\\n" 9461 " \"text \" \\\n" 9462 " \"other\";", 9463 format("#define A \"some text other\";", getLLVMStyleWithColumns(12))); 9464 EXPECT_EQ( 9465 "#define A \\\n" 9466 " \"so \" \\\n" 9467 " \"text \" \\\n" 9468 " \"other\";", 9469 format("#define A \"so text other\";", getLLVMStyleWithColumns(12))); 9470 9471 EXPECT_EQ("\"some text\"", 9472 format("\"some text\"", getLLVMStyleWithColumns(1))); 9473 EXPECT_EQ("\"some text\"", 9474 format("\"some text\"", getLLVMStyleWithColumns(11))); 9475 EXPECT_EQ("\"some \"\n" 9476 "\"text\"", 9477 format("\"some text\"", getLLVMStyleWithColumns(10))); 9478 EXPECT_EQ("\"some \"\n" 9479 "\"text\"", 9480 format("\"some text\"", getLLVMStyleWithColumns(7))); 9481 EXPECT_EQ("\"some\"\n" 9482 "\" tex\"\n" 9483 "\"t\"", 9484 format("\"some text\"", getLLVMStyleWithColumns(6))); 9485 EXPECT_EQ("\"some\"\n" 9486 "\" tex\"\n" 9487 "\" and\"", 9488 format("\"some tex and\"", getLLVMStyleWithColumns(6))); 9489 EXPECT_EQ("\"some\"\n" 9490 "\"/tex\"\n" 9491 "\"/and\"", 9492 format("\"some/tex/and\"", getLLVMStyleWithColumns(6))); 9493 9494 EXPECT_EQ("variable =\n" 9495 " \"long string \"\n" 9496 " \"literal\";", 9497 format("variable = \"long string literal\";", 9498 getLLVMStyleWithColumns(20))); 9499 9500 EXPECT_EQ("variable = f(\n" 9501 " \"long string \"\n" 9502 " \"literal\",\n" 9503 " short,\n" 9504 " loooooooooooooooooooong);", 9505 format("variable = f(\"long string literal\", short, " 9506 "loooooooooooooooooooong);", 9507 getLLVMStyleWithColumns(20))); 9508 9509 EXPECT_EQ( 9510 "f(g(\"long string \"\n" 9511 " \"literal\"),\n" 9512 " b);", 9513 format("f(g(\"long string literal\"), b);", getLLVMStyleWithColumns(20))); 9514 EXPECT_EQ("f(g(\"long string \"\n" 9515 " \"literal\",\n" 9516 " a),\n" 9517 " b);", 9518 format("f(g(\"long string literal\", a), b);", 9519 getLLVMStyleWithColumns(20))); 9520 EXPECT_EQ( 9521 "f(\"one two\".split(\n" 9522 " variable));", 9523 format("f(\"one two\".split(variable));", getLLVMStyleWithColumns(20))); 9524 EXPECT_EQ("f(\"one two three four five six \"\n" 9525 " \"seven\".split(\n" 9526 " really_looooong_variable));", 9527 format("f(\"one two three four five six seven\"." 9528 "split(really_looooong_variable));", 9529 getLLVMStyleWithColumns(33))); 9530 9531 EXPECT_EQ("f(\"some \"\n" 9532 " \"text\",\n" 9533 " other);", 9534 format("f(\"some text\", other);", getLLVMStyleWithColumns(10))); 9535 9536 // Only break as a last resort. 9537 verifyFormat( 9538 "aaaaaaaaaaaaaaaaaaaa(\n" 9539 " aaaaaaaaaaaaaaaaaaaa,\n" 9540 " aaaaaa(\"aaa aaaaa aaa aaa aaaaa aaa aaaaa aaa aaa aaaaaa\"));"); 9541 9542 EXPECT_EQ("\"splitmea\"\n" 9543 "\"trandomp\"\n" 9544 "\"oint\"", 9545 format("\"splitmeatrandompoint\"", getLLVMStyleWithColumns(10))); 9546 9547 EXPECT_EQ("\"split/\"\n" 9548 "\"pathat/\"\n" 9549 "\"slashes\"", 9550 format("\"split/pathat/slashes\"", getLLVMStyleWithColumns(10))); 9551 9552 EXPECT_EQ("\"split/\"\n" 9553 "\"pathat/\"\n" 9554 "\"slashes\"", 9555 format("\"split/pathat/slashes\"", getLLVMStyleWithColumns(10))); 9556 EXPECT_EQ("\"split at \"\n" 9557 "\"spaces/at/\"\n" 9558 "\"slashes.at.any$\"\n" 9559 "\"non-alphanumeric%\"\n" 9560 "\"1111111111characte\"\n" 9561 "\"rs\"", 9562 format("\"split at " 9563 "spaces/at/" 9564 "slashes.at." 9565 "any$non-" 9566 "alphanumeric%" 9567 "1111111111characte" 9568 "rs\"", 9569 getLLVMStyleWithColumns(20))); 9570 9571 // Verify that splitting the strings understands 9572 // Style::AlwaysBreakBeforeMultilineStrings. 9573 EXPECT_EQ("aaaaaaaaaaaa(\n" 9574 " \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa \"\n" 9575 " \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa\");", 9576 format("aaaaaaaaaaaa(\"aaaaaaaaaaaaaaaaaaaaaaaaaa " 9577 "aaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa " 9578 "aaaaaaaaaaaaaaaaaaaaaa\");", 9579 getGoogleStyle())); 9580 EXPECT_EQ("return \"aaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa \"\n" 9581 " \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa\";", 9582 format("return \"aaaaaaaaaaaaaaaaaaaaaa " 9583 "aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa " 9584 "aaaaaaaaaaaaaaaaaaaaaa\";", 9585 getGoogleStyle())); 9586 EXPECT_EQ("llvm::outs() << \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n" 9587 " \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";", 9588 format("llvm::outs() << " 9589 "\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaa" 9590 "aaaaaaaaaaaaaaaaaaa\";")); 9591 EXPECT_EQ("ffff(\n" 9592 " {\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n" 9593 " \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"});", 9594 format("ffff({\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa " 9595 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"});", 9596 getGoogleStyle())); 9597 9598 FormatStyle Style = getLLVMStyleWithColumns(12); 9599 Style.BreakStringLiterals = false; 9600 EXPECT_EQ("\"some text other\";", format("\"some text other\";", Style)); 9601 9602 FormatStyle AlignLeft = getLLVMStyleWithColumns(12); 9603 AlignLeft.AlignEscapedNewlines = FormatStyle::ENAS_Left; 9604 EXPECT_EQ("#define A \\\n" 9605 " \"some \" \\\n" 9606 " \"text \" \\\n" 9607 " \"other\";", 9608 format("#define A \"some text other\";", AlignLeft)); 9609 } 9610 9611 TEST_F(FormatTest, BreaksStringLiteralsAtColumnLimit) { 9612 EXPECT_EQ("C a = \"some more \"\n" 9613 " \"text\";", 9614 format("C a = \"some more text\";", getLLVMStyleWithColumns(18))); 9615 } 9616 9617 TEST_F(FormatTest, FullyRemoveEmptyLines) { 9618 FormatStyle NoEmptyLines = getLLVMStyleWithColumns(80); 9619 NoEmptyLines.MaxEmptyLinesToKeep = 0; 9620 EXPECT_EQ("int i = a(b());", 9621 format("int i=a(\n\n b(\n\n\n )\n\n);", NoEmptyLines)); 9622 } 9623 9624 TEST_F(FormatTest, BreaksStringLiteralsWithTabs) { 9625 EXPECT_EQ( 9626 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" 9627 "(\n" 9628 " \"x\t\");", 9629 format("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" 9630 "aaaaaaa(" 9631 "\"x\t\");")); 9632 } 9633 9634 TEST_F(FormatTest, BreaksWideAndNSStringLiterals) { 9635 EXPECT_EQ( 9636 "u8\"utf8 string \"\n" 9637 "u8\"literal\";", 9638 format("u8\"utf8 string literal\";", getGoogleStyleWithColumns(16))); 9639 EXPECT_EQ( 9640 "u\"utf16 string \"\n" 9641 "u\"literal\";", 9642 format("u\"utf16 string literal\";", getGoogleStyleWithColumns(16))); 9643 EXPECT_EQ( 9644 "U\"utf32 string \"\n" 9645 "U\"literal\";", 9646 format("U\"utf32 string literal\";", getGoogleStyleWithColumns(16))); 9647 EXPECT_EQ("L\"wide string \"\n" 9648 "L\"literal\";", 9649 format("L\"wide string literal\";", getGoogleStyleWithColumns(16))); 9650 EXPECT_EQ("@\"NSString \"\n" 9651 "@\"literal\";", 9652 format("@\"NSString literal\";", getGoogleStyleWithColumns(19))); 9653 verifyFormat(R"(NSString *s = @"那那那那";)", getLLVMStyleWithColumns(26)); 9654 9655 // This input makes clang-format try to split the incomplete unicode escape 9656 // sequence, which used to lead to a crasher. 9657 verifyNoCrash( 9658 "aaaaaaaaaaaaaaaaaaaa = L\"\\udff\"'; // aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", 9659 getLLVMStyleWithColumns(60)); 9660 } 9661 9662 TEST_F(FormatTest, DoesNotBreakRawStringLiterals) { 9663 FormatStyle Style = getGoogleStyleWithColumns(15); 9664 EXPECT_EQ("R\"x(raw literal)x\";", format("R\"x(raw literal)x\";", Style)); 9665 EXPECT_EQ("uR\"x(raw literal)x\";", format("uR\"x(raw literal)x\";", Style)); 9666 EXPECT_EQ("LR\"x(raw literal)x\";", format("LR\"x(raw literal)x\";", Style)); 9667 EXPECT_EQ("UR\"x(raw literal)x\";", format("UR\"x(raw literal)x\";", Style)); 9668 EXPECT_EQ("u8R\"x(raw literal)x\";", 9669 format("u8R\"x(raw literal)x\";", Style)); 9670 } 9671 9672 TEST_F(FormatTest, BreaksStringLiteralsWithin_TMacro) { 9673 FormatStyle Style = getLLVMStyleWithColumns(20); 9674 EXPECT_EQ( 9675 "_T(\"aaaaaaaaaaaaaa\")\n" 9676 "_T(\"aaaaaaaaaaaaaa\")\n" 9677 "_T(\"aaaaaaaaaaaa\")", 9678 format(" _T(\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\")", Style)); 9679 EXPECT_EQ("f(x,\n" 9680 " _T(\"aaaaaaaaaaaa\")\n" 9681 " _T(\"aaa\"),\n" 9682 " z);", 9683 format("f(x, _T(\"aaaaaaaaaaaaaaa\"), z);", Style)); 9684 9685 // FIXME: Handle embedded spaces in one iteration. 9686 // EXPECT_EQ("_T(\"aaaaaaaaaaaaa\")\n" 9687 // "_T(\"aaaaaaaaaaaaa\")\n" 9688 // "_T(\"aaaaaaaaaaaaa\")\n" 9689 // "_T(\"a\")", 9690 // format(" _T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )", 9691 // getLLVMStyleWithColumns(20))); 9692 EXPECT_EQ( 9693 "_T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )", 9694 format(" _T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )", Style)); 9695 EXPECT_EQ("f(\n" 9696 "#if !TEST\n" 9697 " _T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\")\n" 9698 "#endif\n" 9699 ");", 9700 format("f(\n" 9701 "#if !TEST\n" 9702 "_T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\")\n" 9703 "#endif\n" 9704 ");")); 9705 EXPECT_EQ("f(\n" 9706 "\n" 9707 " _T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\"));", 9708 format("f(\n" 9709 "\n" 9710 "_T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\"));")); 9711 } 9712 9713 TEST_F(FormatTest, BreaksStringLiteralOperands) { 9714 // In a function call with two operands, the second can be broken with no line 9715 // break before it. 9716 EXPECT_EQ( 9717 "func(a, \"long long \"\n" 9718 " \"long long\");", 9719 format("func(a, \"long long long long\");", getLLVMStyleWithColumns(24))); 9720 // In a function call with three operands, the second must be broken with a 9721 // line break before it. 9722 EXPECT_EQ("func(a,\n" 9723 " \"long long long \"\n" 9724 " \"long\",\n" 9725 " c);", 9726 format("func(a, \"long long long long\", c);", 9727 getLLVMStyleWithColumns(24))); 9728 // In a function call with three operands, the third must be broken with a 9729 // line break before it. 9730 EXPECT_EQ("func(a, b,\n" 9731 " \"long long long \"\n" 9732 " \"long\");", 9733 format("func(a, b, \"long long long long\");", 9734 getLLVMStyleWithColumns(24))); 9735 // In a function call with three operands, both the second and the third must 9736 // be broken with a line break before them. 9737 EXPECT_EQ("func(a,\n" 9738 " \"long long long \"\n" 9739 " \"long\",\n" 9740 " \"long long long \"\n" 9741 " \"long\");", 9742 format("func(a, \"long long long long\", \"long long long long\");", 9743 getLLVMStyleWithColumns(24))); 9744 // In a chain of << with two operands, the second can be broken with no line 9745 // break before it. 9746 EXPECT_EQ("a << \"line line \"\n" 9747 " \"line\";", 9748 format("a << \"line line line\";", getLLVMStyleWithColumns(20))); 9749 // In a chain of << with three operands, the second can be broken with no line 9750 // break before it. 9751 EXPECT_EQ( 9752 "abcde << \"line \"\n" 9753 " \"line line\"\n" 9754 " << c;", 9755 format("abcde << \"line line line\" << c;", getLLVMStyleWithColumns(20))); 9756 // In a chain of << with three operands, the third must be broken with a line 9757 // break before it. 9758 EXPECT_EQ( 9759 "a << b\n" 9760 " << \"line line \"\n" 9761 " \"line\";", 9762 format("a << b << \"line line line\";", getLLVMStyleWithColumns(20))); 9763 // In a chain of << with three operands, the second can be broken with no line 9764 // break before it and the third must be broken with a line break before it. 9765 EXPECT_EQ("abcd << \"line line \"\n" 9766 " \"line\"\n" 9767 " << \"line line \"\n" 9768 " \"line\";", 9769 format("abcd << \"line line line\" << \"line line line\";", 9770 getLLVMStyleWithColumns(20))); 9771 // In a chain of binary operators with two operands, the second can be broken 9772 // with no line break before it. 9773 EXPECT_EQ( 9774 "abcd + \"line line \"\n" 9775 " \"line line\";", 9776 format("abcd + \"line line line line\";", getLLVMStyleWithColumns(20))); 9777 // In a chain of binary operators with three operands, the second must be 9778 // broken with a line break before it. 9779 EXPECT_EQ("abcd +\n" 9780 " \"line line \"\n" 9781 " \"line line\" +\n" 9782 " e;", 9783 format("abcd + \"line line line line\" + e;", 9784 getLLVMStyleWithColumns(20))); 9785 // In a function call with two operands, with AlignAfterOpenBracket enabled, 9786 // the first must be broken with a line break before it. 9787 FormatStyle Style = getLLVMStyleWithColumns(25); 9788 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 9789 EXPECT_EQ("someFunction(\n" 9790 " \"long long long \"\n" 9791 " \"long\",\n" 9792 " a);", 9793 format("someFunction(\"long long long long\", a);", Style)); 9794 } 9795 9796 TEST_F(FormatTest, DontSplitStringLiteralsWithEscapedNewlines) { 9797 EXPECT_EQ( 9798 "aaaaaaaaaaa = \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n" 9799 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n" 9800 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";", 9801 format("aaaaaaaaaaa = \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n" 9802 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n" 9803 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";")); 9804 } 9805 9806 TEST_F(FormatTest, CountsCharactersInMultilineRawStringLiterals) { 9807 EXPECT_EQ("f(g(R\"x(raw literal)x\", a), b);", 9808 format("f(g(R\"x(raw literal)x\", a), b);", getGoogleStyle())); 9809 EXPECT_EQ("fffffffffff(g(R\"x(\n" 9810 "multiline raw string literal xxxxxxxxxxxxxx\n" 9811 ")x\",\n" 9812 " a),\n" 9813 " b);", 9814 format("fffffffffff(g(R\"x(\n" 9815 "multiline raw string literal xxxxxxxxxxxxxx\n" 9816 ")x\", a), b);", 9817 getGoogleStyleWithColumns(20))); 9818 EXPECT_EQ("fffffffffff(\n" 9819 " g(R\"x(qqq\n" 9820 "multiline raw string literal xxxxxxxxxxxxxx\n" 9821 ")x\",\n" 9822 " a),\n" 9823 " b);", 9824 format("fffffffffff(g(R\"x(qqq\n" 9825 "multiline raw string literal xxxxxxxxxxxxxx\n" 9826 ")x\", a), b);", 9827 getGoogleStyleWithColumns(20))); 9828 9829 EXPECT_EQ("fffffffffff(R\"x(\n" 9830 "multiline raw string literal xxxxxxxxxxxxxx\n" 9831 ")x\");", 9832 format("fffffffffff(R\"x(\n" 9833 "multiline raw string literal xxxxxxxxxxxxxx\n" 9834 ")x\");", 9835 getGoogleStyleWithColumns(20))); 9836 EXPECT_EQ("fffffffffff(R\"x(\n" 9837 "multiline raw string literal xxxxxxxxxxxxxx\n" 9838 ")x\" + bbbbbb);", 9839 format("fffffffffff(R\"x(\n" 9840 "multiline raw string literal xxxxxxxxxxxxxx\n" 9841 ")x\" + bbbbbb);", 9842 getGoogleStyleWithColumns(20))); 9843 EXPECT_EQ("fffffffffff(\n" 9844 " R\"x(\n" 9845 "multiline raw string literal xxxxxxxxxxxxxx\n" 9846 ")x\" +\n" 9847 " bbbbbb);", 9848 format("fffffffffff(\n" 9849 " R\"x(\n" 9850 "multiline raw string literal xxxxxxxxxxxxxx\n" 9851 ")x\" + bbbbbb);", 9852 getGoogleStyleWithColumns(20))); 9853 EXPECT_EQ("fffffffffff(R\"(single line raw string)\" + bbbbbb);", 9854 format("fffffffffff(\n" 9855 " R\"(single line raw string)\" + bbbbbb);")); 9856 } 9857 9858 TEST_F(FormatTest, SkipsUnknownStringLiterals) { 9859 verifyFormat("string a = \"unterminated;"); 9860 EXPECT_EQ("function(\"unterminated,\n" 9861 " OtherParameter);", 9862 format("function( \"unterminated,\n" 9863 " OtherParameter);")); 9864 } 9865 9866 TEST_F(FormatTest, DoesNotTryToParseUDLiteralsInPreCpp11Code) { 9867 FormatStyle Style = getLLVMStyle(); 9868 Style.Standard = FormatStyle::LS_Cpp03; 9869 EXPECT_EQ("#define x(_a) printf(\"foo\" _a);", 9870 format("#define x(_a) printf(\"foo\"_a);", Style)); 9871 } 9872 9873 TEST_F(FormatTest, CppLexVersion) { 9874 FormatStyle Style = getLLVMStyle(); 9875 // Formatting of x * y differs if x is a type. 9876 verifyFormat("void foo() { MACRO(a * b); }", Style); 9877 verifyFormat("void foo() { MACRO(int *b); }", Style); 9878 9879 // LLVM style uses latest lexer. 9880 verifyFormat("void foo() { MACRO(char8_t *b); }", Style); 9881 Style.Standard = FormatStyle::LS_Cpp17; 9882 // But in c++17, char8_t isn't a keyword. 9883 verifyFormat("void foo() { MACRO(char8_t * b); }", Style); 9884 } 9885 9886 TEST_F(FormatTest, UnderstandsCpp1y) { verifyFormat("int bi{1'000'000};"); } 9887 9888 TEST_F(FormatTest, BreakStringLiteralsBeforeUnbreakableTokenSequence) { 9889 EXPECT_EQ("someFunction(\"aaabbbcccd\"\n" 9890 " \"ddeeefff\");", 9891 format("someFunction(\"aaabbbcccdddeeefff\");", 9892 getLLVMStyleWithColumns(25))); 9893 EXPECT_EQ("someFunction1234567890(\n" 9894 " \"aaabbbcccdddeeefff\");", 9895 format("someFunction1234567890(\"aaabbbcccdddeeefff\");", 9896 getLLVMStyleWithColumns(26))); 9897 EXPECT_EQ("someFunction1234567890(\n" 9898 " \"aaabbbcccdddeeeff\"\n" 9899 " \"f\");", 9900 format("someFunction1234567890(\"aaabbbcccdddeeefff\");", 9901 getLLVMStyleWithColumns(25))); 9902 EXPECT_EQ("someFunction1234567890(\n" 9903 " \"aaabbbcccdddeeeff\"\n" 9904 " \"f\");", 9905 format("someFunction1234567890(\"aaabbbcccdddeeefff\");", 9906 getLLVMStyleWithColumns(24))); 9907 EXPECT_EQ("someFunction(\n" 9908 " \"aaabbbcc ddde \"\n" 9909 " \"efff\");", 9910 format("someFunction(\"aaabbbcc ddde efff\");", 9911 getLLVMStyleWithColumns(25))); 9912 EXPECT_EQ("someFunction(\"aaabbbccc \"\n" 9913 " \"ddeeefff\");", 9914 format("someFunction(\"aaabbbccc ddeeefff\");", 9915 getLLVMStyleWithColumns(25))); 9916 EXPECT_EQ("someFunction1234567890(\n" 9917 " \"aaabb \"\n" 9918 " \"cccdddeeefff\");", 9919 format("someFunction1234567890(\"aaabb cccdddeeefff\");", 9920 getLLVMStyleWithColumns(25))); 9921 EXPECT_EQ("#define A \\\n" 9922 " string s = \\\n" 9923 " \"123456789\" \\\n" 9924 " \"0\"; \\\n" 9925 " int i;", 9926 format("#define A string s = \"1234567890\"; int i;", 9927 getLLVMStyleWithColumns(20))); 9928 EXPECT_EQ("someFunction(\n" 9929 " \"aaabbbcc \"\n" 9930 " \"dddeeefff\");", 9931 format("someFunction(\"aaabbbcc dddeeefff\");", 9932 getLLVMStyleWithColumns(25))); 9933 } 9934 9935 TEST_F(FormatTest, DoNotBreakStringLiteralsInEscapeSequence) { 9936 EXPECT_EQ("\"\\a\"", format("\"\\a\"", getLLVMStyleWithColumns(3))); 9937 EXPECT_EQ("\"\\\"", format("\"\\\"", getLLVMStyleWithColumns(2))); 9938 EXPECT_EQ("\"test\"\n" 9939 "\"\\n\"", 9940 format("\"test\\n\"", getLLVMStyleWithColumns(7))); 9941 EXPECT_EQ("\"tes\\\\\"\n" 9942 "\"n\"", 9943 format("\"tes\\\\n\"", getLLVMStyleWithColumns(7))); 9944 EXPECT_EQ("\"\\\\\\\\\"\n" 9945 "\"\\n\"", 9946 format("\"\\\\\\\\\\n\"", getLLVMStyleWithColumns(7))); 9947 EXPECT_EQ("\"\\uff01\"", format("\"\\uff01\"", getLLVMStyleWithColumns(7))); 9948 EXPECT_EQ("\"\\uff01\"\n" 9949 "\"test\"", 9950 format("\"\\uff01test\"", getLLVMStyleWithColumns(8))); 9951 EXPECT_EQ("\"\\Uff01ff02\"", 9952 format("\"\\Uff01ff02\"", getLLVMStyleWithColumns(11))); 9953 EXPECT_EQ("\"\\x000000000001\"\n" 9954 "\"next\"", 9955 format("\"\\x000000000001next\"", getLLVMStyleWithColumns(16))); 9956 EXPECT_EQ("\"\\x000000000001next\"", 9957 format("\"\\x000000000001next\"", getLLVMStyleWithColumns(15))); 9958 EXPECT_EQ("\"\\x000000000001\"", 9959 format("\"\\x000000000001\"", getLLVMStyleWithColumns(7))); 9960 EXPECT_EQ("\"test\"\n" 9961 "\"\\000000\"\n" 9962 "\"000001\"", 9963 format("\"test\\000000000001\"", getLLVMStyleWithColumns(9))); 9964 EXPECT_EQ("\"test\\000\"\n" 9965 "\"00000000\"\n" 9966 "\"1\"", 9967 format("\"test\\000000000001\"", getLLVMStyleWithColumns(10))); 9968 } 9969 9970 TEST_F(FormatTest, DoNotCreateUnreasonableUnwrappedLines) { 9971 verifyFormat("void f() {\n" 9972 " return g() {}\n" 9973 " void h() {}"); 9974 verifyFormat("int a[] = {void forgot_closing_brace(){f();\n" 9975 "g();\n" 9976 "}"); 9977 } 9978 9979 TEST_F(FormatTest, DoNotPrematurelyEndUnwrappedLineForReturnStatements) { 9980 verifyFormat( 9981 "void f() { return C{param1, param2}.SomeCall(param1, param2); }"); 9982 } 9983 9984 TEST_F(FormatTest, FormatsClosingBracesInEmptyNestedBlocks) { 9985 verifyFormat("class X {\n" 9986 " void f() {\n" 9987 " }\n" 9988 "};", 9989 getLLVMStyleWithColumns(12)); 9990 } 9991 9992 TEST_F(FormatTest, ConfigurableIndentWidth) { 9993 FormatStyle EightIndent = getLLVMStyleWithColumns(18); 9994 EightIndent.IndentWidth = 8; 9995 EightIndent.ContinuationIndentWidth = 8; 9996 verifyFormat("void f() {\n" 9997 " someFunction();\n" 9998 " if (true) {\n" 9999 " f();\n" 10000 " }\n" 10001 "}", 10002 EightIndent); 10003 verifyFormat("class X {\n" 10004 " void f() {\n" 10005 " }\n" 10006 "};", 10007 EightIndent); 10008 verifyFormat("int x[] = {\n" 10009 " call(),\n" 10010 " call()};", 10011 EightIndent); 10012 } 10013 10014 TEST_F(FormatTest, ConfigurableFunctionDeclarationIndentAfterType) { 10015 verifyFormat("double\n" 10016 "f();", 10017 getLLVMStyleWithColumns(8)); 10018 } 10019 10020 TEST_F(FormatTest, ConfigurableUseOfTab) { 10021 FormatStyle Tab = getLLVMStyleWithColumns(42); 10022 Tab.IndentWidth = 8; 10023 Tab.UseTab = FormatStyle::UT_Always; 10024 Tab.AlignEscapedNewlines = FormatStyle::ENAS_Left; 10025 10026 EXPECT_EQ("if (aaaaaaaa && // q\n" 10027 " bb)\t\t// w\n" 10028 "\t;", 10029 format("if (aaaaaaaa &&// q\n" 10030 "bb)// w\n" 10031 ";", 10032 Tab)); 10033 EXPECT_EQ("if (aaa && bbb) // w\n" 10034 "\t;", 10035 format("if(aaa&&bbb)// w\n" 10036 ";", 10037 Tab)); 10038 10039 verifyFormat("class X {\n" 10040 "\tvoid f() {\n" 10041 "\t\tsomeFunction(parameter1,\n" 10042 "\t\t\t parameter2);\n" 10043 "\t}\n" 10044 "};", 10045 Tab); 10046 verifyFormat("#define A \\\n" 10047 "\tvoid f() { \\\n" 10048 "\t\tsomeFunction( \\\n" 10049 "\t\t parameter1, \\\n" 10050 "\t\t parameter2); \\\n" 10051 "\t}", 10052 Tab); 10053 verifyFormat("int a;\t // x\n" 10054 "int bbbbbbbb; // x\n", 10055 Tab); 10056 10057 Tab.TabWidth = 4; 10058 Tab.IndentWidth = 8; 10059 verifyFormat("class TabWidth4Indent8 {\n" 10060 "\t\tvoid f() {\n" 10061 "\t\t\t\tsomeFunction(parameter1,\n" 10062 "\t\t\t\t\t\t\t parameter2);\n" 10063 "\t\t}\n" 10064 "};", 10065 Tab); 10066 10067 Tab.TabWidth = 4; 10068 Tab.IndentWidth = 4; 10069 verifyFormat("class TabWidth4Indent4 {\n" 10070 "\tvoid f() {\n" 10071 "\t\tsomeFunction(parameter1,\n" 10072 "\t\t\t\t\t parameter2);\n" 10073 "\t}\n" 10074 "};", 10075 Tab); 10076 10077 Tab.TabWidth = 8; 10078 Tab.IndentWidth = 4; 10079 verifyFormat("class TabWidth8Indent4 {\n" 10080 " void f() {\n" 10081 "\tsomeFunction(parameter1,\n" 10082 "\t\t parameter2);\n" 10083 " }\n" 10084 "};", 10085 Tab); 10086 10087 Tab.TabWidth = 8; 10088 Tab.IndentWidth = 8; 10089 EXPECT_EQ("/*\n" 10090 "\t a\t\tcomment\n" 10091 "\t in multiple lines\n" 10092 " */", 10093 format(" /*\t \t \n" 10094 " \t \t a\t\tcomment\t \t\n" 10095 " \t \t in multiple lines\t\n" 10096 " \t */", 10097 Tab)); 10098 10099 Tab.UseTab = FormatStyle::UT_ForIndentation; 10100 verifyFormat("{\n" 10101 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 10102 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 10103 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 10104 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 10105 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 10106 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 10107 "};", 10108 Tab); 10109 verifyFormat("enum AA {\n" 10110 "\ta1, // Force multiple lines\n" 10111 "\ta2,\n" 10112 "\ta3\n" 10113 "};", 10114 Tab); 10115 EXPECT_EQ("if (aaaaaaaa && // q\n" 10116 " bb) // w\n" 10117 "\t;", 10118 format("if (aaaaaaaa &&// q\n" 10119 "bb)// w\n" 10120 ";", 10121 Tab)); 10122 verifyFormat("class X {\n" 10123 "\tvoid f() {\n" 10124 "\t\tsomeFunction(parameter1,\n" 10125 "\t\t parameter2);\n" 10126 "\t}\n" 10127 "};", 10128 Tab); 10129 verifyFormat("{\n" 10130 "\tQ(\n" 10131 "\t {\n" 10132 "\t\t int a;\n" 10133 "\t\t someFunction(aaaaaaaa,\n" 10134 "\t\t bbbbbbb);\n" 10135 "\t },\n" 10136 "\t p);\n" 10137 "}", 10138 Tab); 10139 EXPECT_EQ("{\n" 10140 "\t/* aaaa\n" 10141 "\t bbbb */\n" 10142 "}", 10143 format("{\n" 10144 "/* aaaa\n" 10145 " bbbb */\n" 10146 "}", 10147 Tab)); 10148 EXPECT_EQ("{\n" 10149 "\t/*\n" 10150 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 10151 "\t bbbbbbbbbbbbb\n" 10152 "\t*/\n" 10153 "}", 10154 format("{\n" 10155 "/*\n" 10156 " aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 10157 "*/\n" 10158 "}", 10159 Tab)); 10160 EXPECT_EQ("{\n" 10161 "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 10162 "\t// bbbbbbbbbbbbb\n" 10163 "}", 10164 format("{\n" 10165 "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 10166 "}", 10167 Tab)); 10168 EXPECT_EQ("{\n" 10169 "\t/*\n" 10170 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 10171 "\t bbbbbbbbbbbbb\n" 10172 "\t*/\n" 10173 "}", 10174 format("{\n" 10175 "\t/*\n" 10176 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 10177 "\t*/\n" 10178 "}", 10179 Tab)); 10180 EXPECT_EQ("{\n" 10181 "\t/*\n" 10182 "\n" 10183 "\t*/\n" 10184 "}", 10185 format("{\n" 10186 "\t/*\n" 10187 "\n" 10188 "\t*/\n" 10189 "}", 10190 Tab)); 10191 EXPECT_EQ("{\n" 10192 "\t/*\n" 10193 " asdf\n" 10194 "\t*/\n" 10195 "}", 10196 format("{\n" 10197 "\t/*\n" 10198 " asdf\n" 10199 "\t*/\n" 10200 "}", 10201 Tab)); 10202 10203 Tab.UseTab = FormatStyle::UT_Never; 10204 EXPECT_EQ("/*\n" 10205 " a\t\tcomment\n" 10206 " in multiple lines\n" 10207 " */", 10208 format(" /*\t \t \n" 10209 " \t \t a\t\tcomment\t \t\n" 10210 " \t \t in multiple lines\t\n" 10211 " \t */", 10212 Tab)); 10213 EXPECT_EQ("/* some\n" 10214 " comment */", 10215 format(" \t \t /* some\n" 10216 " \t \t comment */", 10217 Tab)); 10218 EXPECT_EQ("int a; /* some\n" 10219 " comment */", 10220 format(" \t \t int a; /* some\n" 10221 " \t \t comment */", 10222 Tab)); 10223 10224 EXPECT_EQ("int a; /* some\n" 10225 "comment */", 10226 format(" \t \t int\ta; /* some\n" 10227 " \t \t comment */", 10228 Tab)); 10229 EXPECT_EQ("f(\"\t\t\"); /* some\n" 10230 " comment */", 10231 format(" \t \t f(\"\t\t\"); /* some\n" 10232 " \t \t comment */", 10233 Tab)); 10234 EXPECT_EQ("{\n" 10235 " /*\n" 10236 " * Comment\n" 10237 " */\n" 10238 " int i;\n" 10239 "}", 10240 format("{\n" 10241 "\t/*\n" 10242 "\t * Comment\n" 10243 "\t */\n" 10244 "\t int i;\n" 10245 "}", 10246 Tab)); 10247 10248 Tab.UseTab = FormatStyle::UT_ForContinuationAndIndentation; 10249 Tab.TabWidth = 8; 10250 Tab.IndentWidth = 8; 10251 EXPECT_EQ("if (aaaaaaaa && // q\n" 10252 " bb) // w\n" 10253 "\t;", 10254 format("if (aaaaaaaa &&// q\n" 10255 "bb)// w\n" 10256 ";", 10257 Tab)); 10258 EXPECT_EQ("if (aaa && bbb) // w\n" 10259 "\t;", 10260 format("if(aaa&&bbb)// w\n" 10261 ";", 10262 Tab)); 10263 verifyFormat("class X {\n" 10264 "\tvoid f() {\n" 10265 "\t\tsomeFunction(parameter1,\n" 10266 "\t\t\t parameter2);\n" 10267 "\t}\n" 10268 "};", 10269 Tab); 10270 verifyFormat("#define A \\\n" 10271 "\tvoid f() { \\\n" 10272 "\t\tsomeFunction( \\\n" 10273 "\t\t parameter1, \\\n" 10274 "\t\t parameter2); \\\n" 10275 "\t}", 10276 Tab); 10277 Tab.TabWidth = 4; 10278 Tab.IndentWidth = 8; 10279 verifyFormat("class TabWidth4Indent8 {\n" 10280 "\t\tvoid f() {\n" 10281 "\t\t\t\tsomeFunction(parameter1,\n" 10282 "\t\t\t\t\t\t\t parameter2);\n" 10283 "\t\t}\n" 10284 "};", 10285 Tab); 10286 Tab.TabWidth = 4; 10287 Tab.IndentWidth = 4; 10288 verifyFormat("class TabWidth4Indent4 {\n" 10289 "\tvoid f() {\n" 10290 "\t\tsomeFunction(parameter1,\n" 10291 "\t\t\t\t\t parameter2);\n" 10292 "\t}\n" 10293 "};", 10294 Tab); 10295 Tab.TabWidth = 8; 10296 Tab.IndentWidth = 4; 10297 verifyFormat("class TabWidth8Indent4 {\n" 10298 " void f() {\n" 10299 "\tsomeFunction(parameter1,\n" 10300 "\t\t parameter2);\n" 10301 " }\n" 10302 "};", 10303 Tab); 10304 Tab.TabWidth = 8; 10305 Tab.IndentWidth = 8; 10306 EXPECT_EQ("/*\n" 10307 "\t a\t\tcomment\n" 10308 "\t in multiple lines\n" 10309 " */", 10310 format(" /*\t \t \n" 10311 " \t \t a\t\tcomment\t \t\n" 10312 " \t \t in multiple lines\t\n" 10313 " \t */", 10314 Tab)); 10315 verifyFormat("{\n" 10316 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 10317 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 10318 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 10319 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 10320 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 10321 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 10322 "};", 10323 Tab); 10324 verifyFormat("enum AA {\n" 10325 "\ta1, // Force multiple lines\n" 10326 "\ta2,\n" 10327 "\ta3\n" 10328 "};", 10329 Tab); 10330 EXPECT_EQ("if (aaaaaaaa && // q\n" 10331 " bb) // w\n" 10332 "\t;", 10333 format("if (aaaaaaaa &&// q\n" 10334 "bb)// w\n" 10335 ";", 10336 Tab)); 10337 verifyFormat("class X {\n" 10338 "\tvoid f() {\n" 10339 "\t\tsomeFunction(parameter1,\n" 10340 "\t\t\t parameter2);\n" 10341 "\t}\n" 10342 "};", 10343 Tab); 10344 verifyFormat("{\n" 10345 "\tQ(\n" 10346 "\t {\n" 10347 "\t\t int a;\n" 10348 "\t\t someFunction(aaaaaaaa,\n" 10349 "\t\t\t\t bbbbbbb);\n" 10350 "\t },\n" 10351 "\t p);\n" 10352 "}", 10353 Tab); 10354 EXPECT_EQ("{\n" 10355 "\t/* aaaa\n" 10356 "\t bbbb */\n" 10357 "}", 10358 format("{\n" 10359 "/* aaaa\n" 10360 " bbbb */\n" 10361 "}", 10362 Tab)); 10363 EXPECT_EQ("{\n" 10364 "\t/*\n" 10365 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 10366 "\t bbbbbbbbbbbbb\n" 10367 "\t*/\n" 10368 "}", 10369 format("{\n" 10370 "/*\n" 10371 " aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 10372 "*/\n" 10373 "}", 10374 Tab)); 10375 EXPECT_EQ("{\n" 10376 "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 10377 "\t// bbbbbbbbbbbbb\n" 10378 "}", 10379 format("{\n" 10380 "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 10381 "}", 10382 Tab)); 10383 EXPECT_EQ("{\n" 10384 "\t/*\n" 10385 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 10386 "\t bbbbbbbbbbbbb\n" 10387 "\t*/\n" 10388 "}", 10389 format("{\n" 10390 "\t/*\n" 10391 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 10392 "\t*/\n" 10393 "}", 10394 Tab)); 10395 EXPECT_EQ("{\n" 10396 "\t/*\n" 10397 "\n" 10398 "\t*/\n" 10399 "}", 10400 format("{\n" 10401 "\t/*\n" 10402 "\n" 10403 "\t*/\n" 10404 "}", 10405 Tab)); 10406 EXPECT_EQ("{\n" 10407 "\t/*\n" 10408 " asdf\n" 10409 "\t*/\n" 10410 "}", 10411 format("{\n" 10412 "\t/*\n" 10413 " asdf\n" 10414 "\t*/\n" 10415 "}", 10416 Tab)); 10417 EXPECT_EQ("/* some\n" 10418 " comment */", 10419 format(" \t \t /* some\n" 10420 " \t \t comment */", 10421 Tab)); 10422 EXPECT_EQ("int a; /* some\n" 10423 " comment */", 10424 format(" \t \t int a; /* some\n" 10425 " \t \t comment */", 10426 Tab)); 10427 EXPECT_EQ("int a; /* some\n" 10428 "comment */", 10429 format(" \t \t int\ta; /* some\n" 10430 " \t \t comment */", 10431 Tab)); 10432 EXPECT_EQ("f(\"\t\t\"); /* some\n" 10433 " comment */", 10434 format(" \t \t f(\"\t\t\"); /* some\n" 10435 " \t \t comment */", 10436 Tab)); 10437 EXPECT_EQ("{\n" 10438 "\t/*\n" 10439 "\t * Comment\n" 10440 "\t */\n" 10441 "\tint i;\n" 10442 "}", 10443 format("{\n" 10444 "\t/*\n" 10445 "\t * Comment\n" 10446 "\t */\n" 10447 "\t int i;\n" 10448 "}", 10449 Tab)); 10450 Tab.TabWidth = 2; 10451 Tab.IndentWidth = 2; 10452 EXPECT_EQ("{\n" 10453 "\t/* aaaa\n" 10454 "\t\t bbbb */\n" 10455 "}", 10456 format("{\n" 10457 "/* aaaa\n" 10458 "\t bbbb */\n" 10459 "}", 10460 Tab)); 10461 EXPECT_EQ("{\n" 10462 "\t/*\n" 10463 "\t\taaaaaaaaaaaaaaaaaaaaaaaaaa\n" 10464 "\t\tbbbbbbbbbbbbb\n" 10465 "\t*/\n" 10466 "}", 10467 format("{\n" 10468 "/*\n" 10469 "\taaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 10470 "*/\n" 10471 "}", 10472 Tab)); 10473 Tab.AlignConsecutiveAssignments = true; 10474 Tab.AlignConsecutiveDeclarations = true; 10475 Tab.TabWidth = 4; 10476 Tab.IndentWidth = 4; 10477 verifyFormat("class Assign {\n" 10478 "\tvoid f() {\n" 10479 "\t\tint x = 123;\n" 10480 "\t\tint random = 4;\n" 10481 "\t\tstd::string alphabet =\n" 10482 "\t\t\t\"abcdefghijklmnopqrstuvwxyz\";\n" 10483 "\t}\n" 10484 "};", 10485 Tab); 10486 10487 Tab.UseTab = FormatStyle::UT_AlignWithSpaces; 10488 Tab.TabWidth = 8; 10489 Tab.IndentWidth = 8; 10490 EXPECT_EQ("if (aaaaaaaa && // q\n" 10491 " bb) // w\n" 10492 "\t;", 10493 format("if (aaaaaaaa &&// q\n" 10494 "bb)// w\n" 10495 ";", 10496 Tab)); 10497 EXPECT_EQ("if (aaa && bbb) // w\n" 10498 "\t;", 10499 format("if(aaa&&bbb)// w\n" 10500 ";", 10501 Tab)); 10502 verifyFormat("class X {\n" 10503 "\tvoid f() {\n" 10504 "\t\tsomeFunction(parameter1,\n" 10505 "\t\t parameter2);\n" 10506 "\t}\n" 10507 "};", 10508 Tab); 10509 verifyFormat("#define A \\\n" 10510 "\tvoid f() { \\\n" 10511 "\t\tsomeFunction( \\\n" 10512 "\t\t parameter1, \\\n" 10513 "\t\t parameter2); \\\n" 10514 "\t}", 10515 Tab); 10516 Tab.TabWidth = 4; 10517 Tab.IndentWidth = 8; 10518 verifyFormat("class TabWidth4Indent8 {\n" 10519 "\t\tvoid f() {\n" 10520 "\t\t\t\tsomeFunction(parameter1,\n" 10521 "\t\t\t\t parameter2);\n" 10522 "\t\t}\n" 10523 "};", 10524 Tab); 10525 Tab.TabWidth = 4; 10526 Tab.IndentWidth = 4; 10527 verifyFormat("class TabWidth4Indent4 {\n" 10528 "\tvoid f() {\n" 10529 "\t\tsomeFunction(parameter1,\n" 10530 "\t\t parameter2);\n" 10531 "\t}\n" 10532 "};", 10533 Tab); 10534 Tab.TabWidth = 8; 10535 Tab.IndentWidth = 4; 10536 verifyFormat("class TabWidth8Indent4 {\n" 10537 " void f() {\n" 10538 "\tsomeFunction(parameter1,\n" 10539 "\t parameter2);\n" 10540 " }\n" 10541 "};", 10542 Tab); 10543 Tab.TabWidth = 8; 10544 Tab.IndentWidth = 8; 10545 EXPECT_EQ("/*\n" 10546 " a\t\tcomment\n" 10547 " in multiple lines\n" 10548 " */", 10549 format(" /*\t \t \n" 10550 " \t \t a\t\tcomment\t \t\n" 10551 " \t \t in multiple lines\t\n" 10552 " \t */", 10553 Tab)); 10554 verifyFormat("{\n" 10555 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 10556 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 10557 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 10558 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 10559 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 10560 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 10561 "};", 10562 Tab); 10563 verifyFormat("enum AA {\n" 10564 "\ta1, // Force multiple lines\n" 10565 "\ta2,\n" 10566 "\ta3\n" 10567 "};", 10568 Tab); 10569 EXPECT_EQ("if (aaaaaaaa && // q\n" 10570 " bb) // w\n" 10571 "\t;", 10572 format("if (aaaaaaaa &&// q\n" 10573 "bb)// w\n" 10574 ";", 10575 Tab)); 10576 verifyFormat("class X {\n" 10577 "\tvoid f() {\n" 10578 "\t\tsomeFunction(parameter1,\n" 10579 "\t\t parameter2);\n" 10580 "\t}\n" 10581 "};", 10582 Tab); 10583 verifyFormat("{\n" 10584 "\tQ(\n" 10585 "\t {\n" 10586 "\t\t int a;\n" 10587 "\t\t someFunction(aaaaaaaa,\n" 10588 "\t\t bbbbbbb);\n" 10589 "\t },\n" 10590 "\t p);\n" 10591 "}", 10592 Tab); 10593 EXPECT_EQ("{\n" 10594 "\t/* aaaa\n" 10595 "\t bbbb */\n" 10596 "}", 10597 format("{\n" 10598 "/* aaaa\n" 10599 " bbbb */\n" 10600 "}", 10601 Tab)); 10602 EXPECT_EQ("{\n" 10603 "\t/*\n" 10604 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 10605 "\t bbbbbbbbbbbbb\n" 10606 "\t*/\n" 10607 "}", 10608 format("{\n" 10609 "/*\n" 10610 " aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 10611 "*/\n" 10612 "}", 10613 Tab)); 10614 EXPECT_EQ("{\n" 10615 "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 10616 "\t// bbbbbbbbbbbbb\n" 10617 "}", 10618 format("{\n" 10619 "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 10620 "}", 10621 Tab)); 10622 EXPECT_EQ("{\n" 10623 "\t/*\n" 10624 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 10625 "\t bbbbbbbbbbbbb\n" 10626 "\t*/\n" 10627 "}", 10628 format("{\n" 10629 "\t/*\n" 10630 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 10631 "\t*/\n" 10632 "}", 10633 Tab)); 10634 EXPECT_EQ("{\n" 10635 "\t/*\n" 10636 "\n" 10637 "\t*/\n" 10638 "}", 10639 format("{\n" 10640 "\t/*\n" 10641 "\n" 10642 "\t*/\n" 10643 "}", 10644 Tab)); 10645 EXPECT_EQ("{\n" 10646 "\t/*\n" 10647 " asdf\n" 10648 "\t*/\n" 10649 "}", 10650 format("{\n" 10651 "\t/*\n" 10652 " asdf\n" 10653 "\t*/\n" 10654 "}", 10655 Tab)); 10656 EXPECT_EQ("/* some\n" 10657 " comment */", 10658 format(" \t \t /* some\n" 10659 " \t \t comment */", 10660 Tab)); 10661 EXPECT_EQ("int a; /* some\n" 10662 " comment */", 10663 format(" \t \t int a; /* some\n" 10664 " \t \t comment */", 10665 Tab)); 10666 EXPECT_EQ("int a; /* some\n" 10667 "comment */", 10668 format(" \t \t int\ta; /* some\n" 10669 " \t \t comment */", 10670 Tab)); 10671 EXPECT_EQ("f(\"\t\t\"); /* some\n" 10672 " comment */", 10673 format(" \t \t f(\"\t\t\"); /* some\n" 10674 " \t \t comment */", 10675 Tab)); 10676 EXPECT_EQ("{\n" 10677 "\t/*\n" 10678 "\t * Comment\n" 10679 "\t */\n" 10680 "\tint i;\n" 10681 "}", 10682 format("{\n" 10683 "\t/*\n" 10684 "\t * Comment\n" 10685 "\t */\n" 10686 "\t int i;\n" 10687 "}", 10688 Tab)); 10689 Tab.TabWidth = 2; 10690 Tab.IndentWidth = 2; 10691 EXPECT_EQ("{\n" 10692 "\t/* aaaa\n" 10693 "\t bbbb */\n" 10694 "}", 10695 format("{\n" 10696 "/* aaaa\n" 10697 " bbbb */\n" 10698 "}", 10699 Tab)); 10700 EXPECT_EQ("{\n" 10701 "\t/*\n" 10702 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 10703 "\t bbbbbbbbbbbbb\n" 10704 "\t*/\n" 10705 "}", 10706 format("{\n" 10707 "/*\n" 10708 " aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 10709 "*/\n" 10710 "}", 10711 Tab)); 10712 Tab.AlignConsecutiveAssignments = true; 10713 Tab.AlignConsecutiveDeclarations = true; 10714 Tab.TabWidth = 4; 10715 Tab.IndentWidth = 4; 10716 verifyFormat("class Assign {\n" 10717 "\tvoid f() {\n" 10718 "\t\tint x = 123;\n" 10719 "\t\tint random = 4;\n" 10720 "\t\tstd::string alphabet =\n" 10721 "\t\t\t\"abcdefghijklmnopqrstuvwxyz\";\n" 10722 "\t}\n" 10723 "};", 10724 Tab); 10725 } 10726 10727 TEST_F(FormatTest, ZeroTabWidth) { 10728 FormatStyle Tab = getLLVMStyleWithColumns(42); 10729 Tab.IndentWidth = 8; 10730 Tab.UseTab = FormatStyle::UT_Never; 10731 Tab.TabWidth = 0; 10732 EXPECT_EQ("void a(){\n" 10733 " // line starts with '\t'\n" 10734 "};", 10735 format("void a(){\n" 10736 "\t// line starts with '\t'\n" 10737 "};", 10738 Tab)); 10739 10740 EXPECT_EQ("void a(){\n" 10741 " // line starts with '\t'\n" 10742 "};", 10743 format("void a(){\n" 10744 "\t\t// line starts with '\t'\n" 10745 "};", 10746 Tab)); 10747 10748 Tab.UseTab = FormatStyle::UT_ForIndentation; 10749 EXPECT_EQ("void a(){\n" 10750 " // line starts with '\t'\n" 10751 "};", 10752 format("void a(){\n" 10753 "\t// line starts with '\t'\n" 10754 "};", 10755 Tab)); 10756 10757 EXPECT_EQ("void a(){\n" 10758 " // line starts with '\t'\n" 10759 "};", 10760 format("void a(){\n" 10761 "\t\t// line starts with '\t'\n" 10762 "};", 10763 Tab)); 10764 10765 Tab.UseTab = FormatStyle::UT_ForContinuationAndIndentation; 10766 EXPECT_EQ("void a(){\n" 10767 " // line starts with '\t'\n" 10768 "};", 10769 format("void a(){\n" 10770 "\t// line starts with '\t'\n" 10771 "};", 10772 Tab)); 10773 10774 EXPECT_EQ("void a(){\n" 10775 " // line starts with '\t'\n" 10776 "};", 10777 format("void a(){\n" 10778 "\t\t// line starts with '\t'\n" 10779 "};", 10780 Tab)); 10781 10782 Tab.UseTab = FormatStyle::UT_AlignWithSpaces; 10783 EXPECT_EQ("void a(){\n" 10784 " // line starts with '\t'\n" 10785 "};", 10786 format("void a(){\n" 10787 "\t// line starts with '\t'\n" 10788 "};", 10789 Tab)); 10790 10791 EXPECT_EQ("void a(){\n" 10792 " // line starts with '\t'\n" 10793 "};", 10794 format("void a(){\n" 10795 "\t\t// line starts with '\t'\n" 10796 "};", 10797 Tab)); 10798 10799 Tab.UseTab = FormatStyle::UT_Always; 10800 EXPECT_EQ("void a(){\n" 10801 "// line starts with '\t'\n" 10802 "};", 10803 format("void a(){\n" 10804 "\t// line starts with '\t'\n" 10805 "};", 10806 Tab)); 10807 10808 EXPECT_EQ("void a(){\n" 10809 "// line starts with '\t'\n" 10810 "};", 10811 format("void a(){\n" 10812 "\t\t// line starts with '\t'\n" 10813 "};", 10814 Tab)); 10815 } 10816 10817 TEST_F(FormatTest, CalculatesOriginalColumn) { 10818 EXPECT_EQ("\"qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n" 10819 "q\"; /* some\n" 10820 " comment */", 10821 format(" \"qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n" 10822 "q\"; /* some\n" 10823 " comment */", 10824 getLLVMStyle())); 10825 EXPECT_EQ("// qqqqqqqqqqqqqqqqqqqqqqqqqq\n" 10826 "/* some\n" 10827 " comment */", 10828 format("// qqqqqqqqqqqqqqqqqqqqqqqqqq\n" 10829 " /* some\n" 10830 " comment */", 10831 getLLVMStyle())); 10832 EXPECT_EQ("// qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n" 10833 "qqq\n" 10834 "/* some\n" 10835 " comment */", 10836 format("// qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n" 10837 "qqq\n" 10838 " /* some\n" 10839 " comment */", 10840 getLLVMStyle())); 10841 EXPECT_EQ("inttt qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\\\n" 10842 "wwww; /* some\n" 10843 " comment */", 10844 format(" inttt qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\\\n" 10845 "wwww; /* some\n" 10846 " comment */", 10847 getLLVMStyle())); 10848 } 10849 10850 TEST_F(FormatTest, ConfigurableSpaceBeforeParens) { 10851 FormatStyle NoSpace = getLLVMStyle(); 10852 NoSpace.SpaceBeforeParens = FormatStyle::SBPO_Never; 10853 10854 verifyFormat("while(true)\n" 10855 " continue;", 10856 NoSpace); 10857 verifyFormat("for(;;)\n" 10858 " continue;", 10859 NoSpace); 10860 verifyFormat("if(true)\n" 10861 " f();\n" 10862 "else if(true)\n" 10863 " f();", 10864 NoSpace); 10865 verifyFormat("do {\n" 10866 " do_something();\n" 10867 "} while(something());", 10868 NoSpace); 10869 verifyFormat("switch(x) {\n" 10870 "default:\n" 10871 " break;\n" 10872 "}", 10873 NoSpace); 10874 verifyFormat("auto i = std::make_unique<int>(5);", NoSpace); 10875 verifyFormat("size_t x = sizeof(x);", NoSpace); 10876 verifyFormat("auto f(int x) -> decltype(x);", NoSpace); 10877 verifyFormat("int f(T x) noexcept(x.create());", NoSpace); 10878 verifyFormat("alignas(128) char a[128];", NoSpace); 10879 verifyFormat("size_t x = alignof(MyType);", NoSpace); 10880 verifyFormat("static_assert(sizeof(char) == 1, \"Impossible!\");", NoSpace); 10881 verifyFormat("int f() throw(Deprecated);", NoSpace); 10882 verifyFormat("typedef void (*cb)(int);", NoSpace); 10883 verifyFormat("T A::operator()();", NoSpace); 10884 verifyFormat("X A::operator++(T);", NoSpace); 10885 verifyFormat("auto lambda = []() { return 0; };", NoSpace); 10886 10887 FormatStyle Space = getLLVMStyle(); 10888 Space.SpaceBeforeParens = FormatStyle::SBPO_Always; 10889 10890 verifyFormat("int f ();", Space); 10891 verifyFormat("void f (int a, T b) {\n" 10892 " while (true)\n" 10893 " continue;\n" 10894 "}", 10895 Space); 10896 verifyFormat("if (true)\n" 10897 " f ();\n" 10898 "else if (true)\n" 10899 " f ();", 10900 Space); 10901 verifyFormat("do {\n" 10902 " do_something ();\n" 10903 "} while (something ());", 10904 Space); 10905 verifyFormat("switch (x) {\n" 10906 "default:\n" 10907 " break;\n" 10908 "}", 10909 Space); 10910 verifyFormat("A::A () : a (1) {}", Space); 10911 verifyFormat("void f () __attribute__ ((asdf));", Space); 10912 verifyFormat("*(&a + 1);\n" 10913 "&((&a)[1]);\n" 10914 "a[(b + c) * d];\n" 10915 "(((a + 1) * 2) + 3) * 4;", 10916 Space); 10917 verifyFormat("#define A(x) x", Space); 10918 verifyFormat("#define A (x) x", Space); 10919 verifyFormat("#if defined(x)\n" 10920 "#endif", 10921 Space); 10922 verifyFormat("auto i = std::make_unique<int> (5);", Space); 10923 verifyFormat("size_t x = sizeof (x);", Space); 10924 verifyFormat("auto f (int x) -> decltype (x);", Space); 10925 verifyFormat("int f (T x) noexcept (x.create ());", Space); 10926 verifyFormat("alignas (128) char a[128];", Space); 10927 verifyFormat("size_t x = alignof (MyType);", Space); 10928 verifyFormat("static_assert (sizeof (char) == 1, \"Impossible!\");", Space); 10929 verifyFormat("int f () throw (Deprecated);", Space); 10930 verifyFormat("typedef void (*cb) (int);", Space); 10931 verifyFormat("T A::operator() ();", Space); 10932 verifyFormat("X A::operator++ (T);", Space); 10933 verifyFormat("auto lambda = [] () { return 0; };", Space); 10934 verifyFormat("int x = int (y);", Space); 10935 10936 FormatStyle SomeSpace = getLLVMStyle(); 10937 SomeSpace.SpaceBeforeParens = FormatStyle::SBPO_NonEmptyParentheses; 10938 10939 verifyFormat("[]() -> float {}", SomeSpace); 10940 verifyFormat("[] (auto foo) {}", SomeSpace); 10941 verifyFormat("[foo]() -> int {}", SomeSpace); 10942 verifyFormat("int f();", SomeSpace); 10943 verifyFormat("void f (int a, T b) {\n" 10944 " while (true)\n" 10945 " continue;\n" 10946 "}", 10947 SomeSpace); 10948 verifyFormat("if (true)\n" 10949 " f();\n" 10950 "else if (true)\n" 10951 " f();", 10952 SomeSpace); 10953 verifyFormat("do {\n" 10954 " do_something();\n" 10955 "} while (something());", 10956 SomeSpace); 10957 verifyFormat("switch (x) {\n" 10958 "default:\n" 10959 " break;\n" 10960 "}", 10961 SomeSpace); 10962 verifyFormat("A::A() : a (1) {}", SomeSpace); 10963 verifyFormat("void f() __attribute__ ((asdf));", SomeSpace); 10964 verifyFormat("*(&a + 1);\n" 10965 "&((&a)[1]);\n" 10966 "a[(b + c) * d];\n" 10967 "(((a + 1) * 2) + 3) * 4;", 10968 SomeSpace); 10969 verifyFormat("#define A(x) x", SomeSpace); 10970 verifyFormat("#define A (x) x", SomeSpace); 10971 verifyFormat("#if defined(x)\n" 10972 "#endif", 10973 SomeSpace); 10974 verifyFormat("auto i = std::make_unique<int> (5);", SomeSpace); 10975 verifyFormat("size_t x = sizeof (x);", SomeSpace); 10976 verifyFormat("auto f (int x) -> decltype (x);", SomeSpace); 10977 verifyFormat("int f (T x) noexcept (x.create());", SomeSpace); 10978 verifyFormat("alignas (128) char a[128];", SomeSpace); 10979 verifyFormat("size_t x = alignof (MyType);", SomeSpace); 10980 verifyFormat("static_assert (sizeof (char) == 1, \"Impossible!\");", 10981 SomeSpace); 10982 verifyFormat("int f() throw (Deprecated);", SomeSpace); 10983 verifyFormat("typedef void (*cb) (int);", SomeSpace); 10984 verifyFormat("T A::operator()();", SomeSpace); 10985 verifyFormat("X A::operator++ (T);", SomeSpace); 10986 verifyFormat("int x = int (y);", SomeSpace); 10987 verifyFormat("auto lambda = []() { return 0; };", SomeSpace); 10988 } 10989 10990 TEST_F(FormatTest, SpaceAfterLogicalNot) { 10991 FormatStyle Spaces = getLLVMStyle(); 10992 Spaces.SpaceAfterLogicalNot = true; 10993 10994 verifyFormat("bool x = ! y", Spaces); 10995 verifyFormat("if (! isFailure())", Spaces); 10996 verifyFormat("if (! (a && b))", Spaces); 10997 verifyFormat("\"Error!\"", Spaces); 10998 verifyFormat("! ! x", Spaces); 10999 } 11000 11001 TEST_F(FormatTest, ConfigurableSpacesInParentheses) { 11002 FormatStyle Spaces = getLLVMStyle(); 11003 11004 Spaces.SpacesInParentheses = true; 11005 verifyFormat("do_something( ::globalVar );", Spaces); 11006 verifyFormat("call( x, y, z );", Spaces); 11007 verifyFormat("call();", Spaces); 11008 verifyFormat("std::function<void( int, int )> callback;", Spaces); 11009 verifyFormat("void inFunction() { std::function<void( int, int )> fct; }", 11010 Spaces); 11011 verifyFormat("while ( (bool)1 )\n" 11012 " continue;", 11013 Spaces); 11014 verifyFormat("for ( ;; )\n" 11015 " continue;", 11016 Spaces); 11017 verifyFormat("if ( true )\n" 11018 " f();\n" 11019 "else if ( true )\n" 11020 " f();", 11021 Spaces); 11022 verifyFormat("do {\n" 11023 " do_something( (int)i );\n" 11024 "} while ( something() );", 11025 Spaces); 11026 verifyFormat("switch ( x ) {\n" 11027 "default:\n" 11028 " break;\n" 11029 "}", 11030 Spaces); 11031 11032 Spaces.SpacesInParentheses = false; 11033 Spaces.SpacesInCStyleCastParentheses = true; 11034 verifyFormat("Type *A = ( Type * )P;", Spaces); 11035 verifyFormat("Type *A = ( vector<Type *, int *> )P;", Spaces); 11036 verifyFormat("x = ( int32 )y;", Spaces); 11037 verifyFormat("int a = ( int )(2.0f);", Spaces); 11038 verifyFormat("#define AA(X) sizeof((( X * )NULL)->a)", Spaces); 11039 verifyFormat("my_int a = ( my_int )sizeof(int);", Spaces); 11040 verifyFormat("#define x (( int )-1)", Spaces); 11041 11042 // Run the first set of tests again with: 11043 Spaces.SpacesInParentheses = false; 11044 Spaces.SpaceInEmptyParentheses = true; 11045 Spaces.SpacesInCStyleCastParentheses = true; 11046 verifyFormat("call(x, y, z);", Spaces); 11047 verifyFormat("call( );", Spaces); 11048 verifyFormat("std::function<void(int, int)> callback;", Spaces); 11049 verifyFormat("while (( bool )1)\n" 11050 " continue;", 11051 Spaces); 11052 verifyFormat("for (;;)\n" 11053 " continue;", 11054 Spaces); 11055 verifyFormat("if (true)\n" 11056 " f( );\n" 11057 "else if (true)\n" 11058 " f( );", 11059 Spaces); 11060 verifyFormat("do {\n" 11061 " do_something(( int )i);\n" 11062 "} while (something( ));", 11063 Spaces); 11064 verifyFormat("switch (x) {\n" 11065 "default:\n" 11066 " break;\n" 11067 "}", 11068 Spaces); 11069 11070 // Run the first set of tests again with: 11071 Spaces.SpaceAfterCStyleCast = true; 11072 verifyFormat("call(x, y, z);", Spaces); 11073 verifyFormat("call( );", Spaces); 11074 verifyFormat("std::function<void(int, int)> callback;", Spaces); 11075 verifyFormat("while (( bool ) 1)\n" 11076 " continue;", 11077 Spaces); 11078 verifyFormat("for (;;)\n" 11079 " continue;", 11080 Spaces); 11081 verifyFormat("if (true)\n" 11082 " f( );\n" 11083 "else if (true)\n" 11084 " f( );", 11085 Spaces); 11086 verifyFormat("do {\n" 11087 " do_something(( int ) i);\n" 11088 "} while (something( ));", 11089 Spaces); 11090 verifyFormat("switch (x) {\n" 11091 "default:\n" 11092 " break;\n" 11093 "}", 11094 Spaces); 11095 11096 // Run subset of tests again with: 11097 Spaces.SpacesInCStyleCastParentheses = false; 11098 Spaces.SpaceAfterCStyleCast = true; 11099 verifyFormat("while ((bool) 1)\n" 11100 " continue;", 11101 Spaces); 11102 verifyFormat("do {\n" 11103 " do_something((int) i);\n" 11104 "} while (something( ));", 11105 Spaces); 11106 } 11107 11108 TEST_F(FormatTest, ConfigurableSpacesInSquareBrackets) { 11109 verifyFormat("int a[5];"); 11110 verifyFormat("a[3] += 42;"); 11111 11112 FormatStyle Spaces = getLLVMStyle(); 11113 Spaces.SpacesInSquareBrackets = true; 11114 // Not lambdas. 11115 verifyFormat("int a[ 5 ];", Spaces); 11116 verifyFormat("a[ 3 ] += 42;", Spaces); 11117 verifyFormat("constexpr char hello[]{\"hello\"};", Spaces); 11118 verifyFormat("double &operator[](int i) { return 0; }\n" 11119 "int i;", 11120 Spaces); 11121 verifyFormat("std::unique_ptr<int[]> foo() {}", Spaces); 11122 verifyFormat("int i = a[ a ][ a ]->f();", Spaces); 11123 verifyFormat("int i = (*b)[ a ]->f();", Spaces); 11124 // Lambdas. 11125 verifyFormat("int c = []() -> int { return 2; }();\n", Spaces); 11126 verifyFormat("return [ i, args... ] {};", Spaces); 11127 verifyFormat("int foo = [ &bar ]() {};", Spaces); 11128 verifyFormat("int foo = [ = ]() {};", Spaces); 11129 verifyFormat("int foo = [ & ]() {};", Spaces); 11130 verifyFormat("int foo = [ =, &bar ]() {};", Spaces); 11131 verifyFormat("int foo = [ &bar, = ]() {};", Spaces); 11132 } 11133 11134 TEST_F(FormatTest, ConfigurableSpaceBeforeBrackets) { 11135 FormatStyle NoSpaceStyle = getLLVMStyle(); 11136 verifyFormat("int a[5];", NoSpaceStyle); 11137 verifyFormat("a[3] += 42;", NoSpaceStyle); 11138 11139 verifyFormat("int a[1];", NoSpaceStyle); 11140 verifyFormat("int 1 [a];", NoSpaceStyle); 11141 verifyFormat("int a[1][2];", NoSpaceStyle); 11142 verifyFormat("a[7] = 5;", NoSpaceStyle); 11143 verifyFormat("int a = (f())[23];", NoSpaceStyle); 11144 verifyFormat("f([] {})", NoSpaceStyle); 11145 11146 FormatStyle Space = getLLVMStyle(); 11147 Space.SpaceBeforeSquareBrackets = true; 11148 verifyFormat("int c = []() -> int { return 2; }();\n", Space); 11149 verifyFormat("return [i, args...] {};", Space); 11150 11151 verifyFormat("int a [5];", Space); 11152 verifyFormat("a [3] += 42;", Space); 11153 verifyFormat("constexpr char hello []{\"hello\"};", Space); 11154 verifyFormat("double &operator[](int i) { return 0; }\n" 11155 "int i;", 11156 Space); 11157 verifyFormat("std::unique_ptr<int []> foo() {}", Space); 11158 verifyFormat("int i = a [a][a]->f();", Space); 11159 verifyFormat("int i = (*b) [a]->f();", Space); 11160 11161 verifyFormat("int a [1];", Space); 11162 verifyFormat("int 1 [a];", Space); 11163 verifyFormat("int a [1][2];", Space); 11164 verifyFormat("a [7] = 5;", Space); 11165 verifyFormat("int a = (f()) [23];", Space); 11166 verifyFormat("f([] {})", Space); 11167 } 11168 11169 TEST_F(FormatTest, ConfigurableSpaceBeforeAssignmentOperators) { 11170 verifyFormat("int a = 5;"); 11171 verifyFormat("a += 42;"); 11172 verifyFormat("a or_eq 8;"); 11173 11174 FormatStyle Spaces = getLLVMStyle(); 11175 Spaces.SpaceBeforeAssignmentOperators = false; 11176 verifyFormat("int a= 5;", Spaces); 11177 verifyFormat("a+= 42;", Spaces); 11178 verifyFormat("a or_eq 8;", Spaces); 11179 } 11180 11181 TEST_F(FormatTest, ConfigurableSpaceBeforeColon) { 11182 verifyFormat("class Foo : public Bar {};"); 11183 verifyFormat("Foo::Foo() : foo(1) {}"); 11184 verifyFormat("for (auto a : b) {\n}"); 11185 verifyFormat("int x = a ? b : c;"); 11186 verifyFormat("{\n" 11187 "label0:\n" 11188 " int x = 0;\n" 11189 "}"); 11190 verifyFormat("switch (x) {\n" 11191 "case 1:\n" 11192 "default:\n" 11193 "}"); 11194 11195 FormatStyle CtorInitializerStyle = getLLVMStyleWithColumns(30); 11196 CtorInitializerStyle.SpaceBeforeCtorInitializerColon = false; 11197 verifyFormat("class Foo : public Bar {};", CtorInitializerStyle); 11198 verifyFormat("Foo::Foo(): foo(1) {}", CtorInitializerStyle); 11199 verifyFormat("for (auto a : b) {\n}", CtorInitializerStyle); 11200 verifyFormat("int x = a ? b : c;", CtorInitializerStyle); 11201 verifyFormat("{\n" 11202 "label1:\n" 11203 " int x = 0;\n" 11204 "}", 11205 CtorInitializerStyle); 11206 verifyFormat("switch (x) {\n" 11207 "case 1:\n" 11208 "default:\n" 11209 "}", 11210 CtorInitializerStyle); 11211 CtorInitializerStyle.BreakConstructorInitializers = 11212 FormatStyle::BCIS_AfterColon; 11213 verifyFormat("Fooooooooooo::Fooooooooooo():\n" 11214 " aaaaaaaaaaaaaaaa(1),\n" 11215 " bbbbbbbbbbbbbbbb(2) {}", 11216 CtorInitializerStyle); 11217 CtorInitializerStyle.BreakConstructorInitializers = 11218 FormatStyle::BCIS_BeforeComma; 11219 verifyFormat("Fooooooooooo::Fooooooooooo()\n" 11220 " : aaaaaaaaaaaaaaaa(1)\n" 11221 " , bbbbbbbbbbbbbbbb(2) {}", 11222 CtorInitializerStyle); 11223 CtorInitializerStyle.BreakConstructorInitializers = 11224 FormatStyle::BCIS_BeforeColon; 11225 verifyFormat("Fooooooooooo::Fooooooooooo()\n" 11226 " : aaaaaaaaaaaaaaaa(1),\n" 11227 " bbbbbbbbbbbbbbbb(2) {}", 11228 CtorInitializerStyle); 11229 CtorInitializerStyle.ConstructorInitializerIndentWidth = 0; 11230 verifyFormat("Fooooooooooo::Fooooooooooo()\n" 11231 ": aaaaaaaaaaaaaaaa(1),\n" 11232 " bbbbbbbbbbbbbbbb(2) {}", 11233 CtorInitializerStyle); 11234 11235 FormatStyle InheritanceStyle = getLLVMStyleWithColumns(30); 11236 InheritanceStyle.SpaceBeforeInheritanceColon = false; 11237 verifyFormat("class Foo: public Bar {};", InheritanceStyle); 11238 verifyFormat("Foo::Foo() : foo(1) {}", InheritanceStyle); 11239 verifyFormat("for (auto a : b) {\n}", InheritanceStyle); 11240 verifyFormat("int x = a ? b : c;", InheritanceStyle); 11241 verifyFormat("{\n" 11242 "label2:\n" 11243 " int x = 0;\n" 11244 "}", 11245 InheritanceStyle); 11246 verifyFormat("switch (x) {\n" 11247 "case 1:\n" 11248 "default:\n" 11249 "}", 11250 InheritanceStyle); 11251 InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_AfterColon; 11252 verifyFormat("class Foooooooooooooooooooooo:\n" 11253 " public aaaaaaaaaaaaaaaaaa,\n" 11254 " public bbbbbbbbbbbbbbbbbb {\n" 11255 "}", 11256 InheritanceStyle); 11257 InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_BeforeComma; 11258 verifyFormat("class Foooooooooooooooooooooo\n" 11259 " : public aaaaaaaaaaaaaaaaaa\n" 11260 " , public bbbbbbbbbbbbbbbbbb {\n" 11261 "}", 11262 InheritanceStyle); 11263 InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_BeforeColon; 11264 verifyFormat("class Foooooooooooooooooooooo\n" 11265 " : public aaaaaaaaaaaaaaaaaa,\n" 11266 " public bbbbbbbbbbbbbbbbbb {\n" 11267 "}", 11268 InheritanceStyle); 11269 InheritanceStyle.ConstructorInitializerIndentWidth = 0; 11270 verifyFormat("class Foooooooooooooooooooooo\n" 11271 ": public aaaaaaaaaaaaaaaaaa,\n" 11272 " public bbbbbbbbbbbbbbbbbb {}", 11273 InheritanceStyle); 11274 11275 FormatStyle ForLoopStyle = getLLVMStyle(); 11276 ForLoopStyle.SpaceBeforeRangeBasedForLoopColon = false; 11277 verifyFormat("class Foo : public Bar {};", ForLoopStyle); 11278 verifyFormat("Foo::Foo() : foo(1) {}", ForLoopStyle); 11279 verifyFormat("for (auto a: b) {\n}", ForLoopStyle); 11280 verifyFormat("int x = a ? b : c;", ForLoopStyle); 11281 verifyFormat("{\n" 11282 "label2:\n" 11283 " int x = 0;\n" 11284 "}", 11285 ForLoopStyle); 11286 verifyFormat("switch (x) {\n" 11287 "case 1:\n" 11288 "default:\n" 11289 "}", 11290 ForLoopStyle); 11291 11292 FormatStyle NoSpaceStyle = getLLVMStyle(); 11293 NoSpaceStyle.SpaceBeforeCtorInitializerColon = false; 11294 NoSpaceStyle.SpaceBeforeInheritanceColon = false; 11295 NoSpaceStyle.SpaceBeforeRangeBasedForLoopColon = false; 11296 verifyFormat("class Foo: public Bar {};", NoSpaceStyle); 11297 verifyFormat("Foo::Foo(): foo(1) {}", NoSpaceStyle); 11298 verifyFormat("for (auto a: b) {\n}", NoSpaceStyle); 11299 verifyFormat("int x = a ? b : c;", NoSpaceStyle); 11300 verifyFormat("{\n" 11301 "label3:\n" 11302 " int x = 0;\n" 11303 "}", 11304 NoSpaceStyle); 11305 verifyFormat("switch (x) {\n" 11306 "case 1:\n" 11307 "default:\n" 11308 "}", 11309 NoSpaceStyle); 11310 } 11311 11312 TEST_F(FormatTest, AlignConsecutiveMacros) { 11313 FormatStyle Style = getLLVMStyle(); 11314 Style.AlignConsecutiveAssignments = true; 11315 Style.AlignConsecutiveDeclarations = true; 11316 Style.AlignConsecutiveMacros = false; 11317 11318 verifyFormat("#define a 3\n" 11319 "#define bbbb 4\n" 11320 "#define ccc (5)", 11321 Style); 11322 11323 verifyFormat("#define f(x) (x * x)\n" 11324 "#define fff(x, y, z) (x * y + z)\n" 11325 "#define ffff(x, y) (x - y)", 11326 Style); 11327 11328 verifyFormat("#define foo(x, y) (x + y)\n" 11329 "#define bar (5, 6)(2 + 2)", 11330 Style); 11331 11332 verifyFormat("#define a 3\n" 11333 "#define bbbb 4\n" 11334 "#define ccc (5)\n" 11335 "#define f(x) (x * x)\n" 11336 "#define fff(x, y, z) (x * y + z)\n" 11337 "#define ffff(x, y) (x - y)", 11338 Style); 11339 11340 Style.AlignConsecutiveMacros = true; 11341 verifyFormat("#define a 3\n" 11342 "#define bbbb 4\n" 11343 "#define ccc (5)", 11344 Style); 11345 11346 verifyFormat("#define f(x) (x * x)\n" 11347 "#define fff(x, y, z) (x * y + z)\n" 11348 "#define ffff(x, y) (x - y)", 11349 Style); 11350 11351 verifyFormat("#define foo(x, y) (x + y)\n" 11352 "#define bar (5, 6)(2 + 2)", 11353 Style); 11354 11355 verifyFormat("#define a 3\n" 11356 "#define bbbb 4\n" 11357 "#define ccc (5)\n" 11358 "#define f(x) (x * x)\n" 11359 "#define fff(x, y, z) (x * y + z)\n" 11360 "#define ffff(x, y) (x - y)", 11361 Style); 11362 11363 verifyFormat("#define a 5\n" 11364 "#define foo(x, y) (x + y)\n" 11365 "#define CCC (6)\n" 11366 "auto lambda = []() {\n" 11367 " auto ii = 0;\n" 11368 " float j = 0;\n" 11369 " return 0;\n" 11370 "};\n" 11371 "int i = 0;\n" 11372 "float i2 = 0;\n" 11373 "auto v = type{\n" 11374 " i = 1, //\n" 11375 " (i = 2), //\n" 11376 " i = 3 //\n" 11377 "};", 11378 Style); 11379 11380 Style.AlignConsecutiveMacros = false; 11381 Style.ColumnLimit = 20; 11382 11383 verifyFormat("#define a \\\n" 11384 " \"aabbbbbbbbbbbb\"\n" 11385 "#define D \\\n" 11386 " \"aabbbbbbbbbbbb\" \\\n" 11387 " \"ccddeeeeeeeee\"\n" 11388 "#define B \\\n" 11389 " \"QQQQQQQQQQQQQ\" \\\n" 11390 " \"FFFFFFFFFFFFF\" \\\n" 11391 " \"LLLLLLLL\"\n", 11392 Style); 11393 11394 Style.AlignConsecutiveMacros = true; 11395 verifyFormat("#define a \\\n" 11396 " \"aabbbbbbbbbbbb\"\n" 11397 "#define D \\\n" 11398 " \"aabbbbbbbbbbbb\" \\\n" 11399 " \"ccddeeeeeeeee\"\n" 11400 "#define B \\\n" 11401 " \"QQQQQQQQQQQQQ\" \\\n" 11402 " \"FFFFFFFFFFFFF\" \\\n" 11403 " \"LLLLLLLL\"\n", 11404 Style); 11405 } 11406 11407 TEST_F(FormatTest, AlignConsecutiveAssignments) { 11408 FormatStyle Alignment = getLLVMStyle(); 11409 Alignment.AlignConsecutiveMacros = true; 11410 Alignment.AlignConsecutiveAssignments = false; 11411 verifyFormat("int a = 5;\n" 11412 "int oneTwoThree = 123;", 11413 Alignment); 11414 verifyFormat("int a = 5;\n" 11415 "int oneTwoThree = 123;", 11416 Alignment); 11417 11418 Alignment.AlignConsecutiveAssignments = true; 11419 verifyFormat("int a = 5;\n" 11420 "int oneTwoThree = 123;", 11421 Alignment); 11422 verifyFormat("int a = method();\n" 11423 "int oneTwoThree = 133;", 11424 Alignment); 11425 verifyFormat("a &= 5;\n" 11426 "bcd *= 5;\n" 11427 "ghtyf += 5;\n" 11428 "dvfvdb -= 5;\n" 11429 "a /= 5;\n" 11430 "vdsvsv %= 5;\n" 11431 "sfdbddfbdfbb ^= 5;\n" 11432 "dvsdsv |= 5;\n" 11433 "int dsvvdvsdvvv = 123;", 11434 Alignment); 11435 verifyFormat("int i = 1, j = 10;\n" 11436 "something = 2000;", 11437 Alignment); 11438 verifyFormat("something = 2000;\n" 11439 "int i = 1, j = 10;\n", 11440 Alignment); 11441 verifyFormat("something = 2000;\n" 11442 "another = 911;\n" 11443 "int i = 1, j = 10;\n" 11444 "oneMore = 1;\n" 11445 "i = 2;", 11446 Alignment); 11447 verifyFormat("int a = 5;\n" 11448 "int one = 1;\n" 11449 "method();\n" 11450 "int oneTwoThree = 123;\n" 11451 "int oneTwo = 12;", 11452 Alignment); 11453 verifyFormat("int oneTwoThree = 123;\n" 11454 "int oneTwo = 12;\n" 11455 "method();\n", 11456 Alignment); 11457 verifyFormat("int oneTwoThree = 123; // comment\n" 11458 "int oneTwo = 12; // comment", 11459 Alignment); 11460 EXPECT_EQ("int a = 5;\n" 11461 "\n" 11462 "int oneTwoThree = 123;", 11463 format("int a = 5;\n" 11464 "\n" 11465 "int oneTwoThree= 123;", 11466 Alignment)); 11467 EXPECT_EQ("int a = 5;\n" 11468 "int one = 1;\n" 11469 "\n" 11470 "int oneTwoThree = 123;", 11471 format("int a = 5;\n" 11472 "int one = 1;\n" 11473 "\n" 11474 "int oneTwoThree = 123;", 11475 Alignment)); 11476 EXPECT_EQ("int a = 5;\n" 11477 "int one = 1;\n" 11478 "\n" 11479 "int oneTwoThree = 123;\n" 11480 "int oneTwo = 12;", 11481 format("int a = 5;\n" 11482 "int one = 1;\n" 11483 "\n" 11484 "int oneTwoThree = 123;\n" 11485 "int oneTwo = 12;", 11486 Alignment)); 11487 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign; 11488 verifyFormat("#define A \\\n" 11489 " int aaaa = 12; \\\n" 11490 " int b = 23; \\\n" 11491 " int ccc = 234; \\\n" 11492 " int dddddddddd = 2345;", 11493 Alignment); 11494 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Left; 11495 verifyFormat("#define A \\\n" 11496 " int aaaa = 12; \\\n" 11497 " int b = 23; \\\n" 11498 " int ccc = 234; \\\n" 11499 " int dddddddddd = 2345;", 11500 Alignment); 11501 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Right; 11502 verifyFormat("#define A " 11503 " \\\n" 11504 " int aaaa = 12; " 11505 " \\\n" 11506 " int b = 23; " 11507 " \\\n" 11508 " int ccc = 234; " 11509 " \\\n" 11510 " int dddddddddd = 2345;", 11511 Alignment); 11512 verifyFormat("void SomeFunction(int parameter = 1, int i = 2, int j = 3, int " 11513 "k = 4, int l = 5,\n" 11514 " int m = 6) {\n" 11515 " int j = 10;\n" 11516 " otherThing = 1;\n" 11517 "}", 11518 Alignment); 11519 verifyFormat("void SomeFunction(int parameter = 0) {\n" 11520 " int i = 1;\n" 11521 " int j = 2;\n" 11522 " int big = 10000;\n" 11523 "}", 11524 Alignment); 11525 verifyFormat("class C {\n" 11526 "public:\n" 11527 " int i = 1;\n" 11528 " virtual void f() = 0;\n" 11529 "};", 11530 Alignment); 11531 verifyFormat("int i = 1;\n" 11532 "if (SomeType t = getSomething()) {\n" 11533 "}\n" 11534 "int j = 2;\n" 11535 "int big = 10000;", 11536 Alignment); 11537 verifyFormat("int j = 7;\n" 11538 "for (int k = 0; k < N; ++k) {\n" 11539 "}\n" 11540 "int j = 2;\n" 11541 "int big = 10000;\n" 11542 "}", 11543 Alignment); 11544 Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 11545 verifyFormat("int i = 1;\n" 11546 "LooooooooooongType loooooooooooooooooooooongVariable\n" 11547 " = someLooooooooooooooooongFunction();\n" 11548 "int j = 2;", 11549 Alignment); 11550 Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_None; 11551 verifyFormat("int i = 1;\n" 11552 "LooooooooooongType loooooooooooooooooooooongVariable =\n" 11553 " someLooooooooooooooooongFunction();\n" 11554 "int j = 2;", 11555 Alignment); 11556 11557 verifyFormat("auto lambda = []() {\n" 11558 " auto i = 0;\n" 11559 " return 0;\n" 11560 "};\n" 11561 "int i = 0;\n" 11562 "auto v = type{\n" 11563 " i = 1, //\n" 11564 " (i = 2), //\n" 11565 " i = 3 //\n" 11566 "};", 11567 Alignment); 11568 11569 verifyFormat( 11570 "int i = 1;\n" 11571 "SomeType a = SomeFunction(looooooooooooooooooooooongParameterA,\n" 11572 " loooooooooooooooooooooongParameterB);\n" 11573 "int j = 2;", 11574 Alignment); 11575 11576 verifyFormat("template <typename T, typename T_0 = very_long_type_name_0,\n" 11577 " typename B = very_long_type_name_1,\n" 11578 " typename T_2 = very_long_type_name_2>\n" 11579 "auto foo() {}\n", 11580 Alignment); 11581 verifyFormat("int a, b = 1;\n" 11582 "int c = 2;\n" 11583 "int dd = 3;\n", 11584 Alignment); 11585 verifyFormat("int aa = ((1 > 2) ? 3 : 4);\n" 11586 "float b[1][] = {{3.f}};\n", 11587 Alignment); 11588 verifyFormat("for (int i = 0; i < 1; i++)\n" 11589 " int x = 1;\n", 11590 Alignment); 11591 verifyFormat("for (i = 0; i < 1; i++)\n" 11592 " x = 1;\n" 11593 "y = 1;\n", 11594 Alignment); 11595 } 11596 11597 TEST_F(FormatTest, AlignConsecutiveDeclarations) { 11598 FormatStyle Alignment = getLLVMStyle(); 11599 Alignment.AlignConsecutiveMacros = true; 11600 Alignment.AlignConsecutiveDeclarations = false; 11601 verifyFormat("float const a = 5;\n" 11602 "int oneTwoThree = 123;", 11603 Alignment); 11604 verifyFormat("int a = 5;\n" 11605 "float const oneTwoThree = 123;", 11606 Alignment); 11607 11608 Alignment.AlignConsecutiveDeclarations = true; 11609 verifyFormat("float const a = 5;\n" 11610 "int oneTwoThree = 123;", 11611 Alignment); 11612 verifyFormat("int a = method();\n" 11613 "float const oneTwoThree = 133;", 11614 Alignment); 11615 verifyFormat("int i = 1, j = 10;\n" 11616 "something = 2000;", 11617 Alignment); 11618 verifyFormat("something = 2000;\n" 11619 "int i = 1, j = 10;\n", 11620 Alignment); 11621 verifyFormat("float something = 2000;\n" 11622 "double another = 911;\n" 11623 "int i = 1, j = 10;\n" 11624 "const int *oneMore = 1;\n" 11625 "unsigned i = 2;", 11626 Alignment); 11627 verifyFormat("float a = 5;\n" 11628 "int one = 1;\n" 11629 "method();\n" 11630 "const double oneTwoThree = 123;\n" 11631 "const unsigned int oneTwo = 12;", 11632 Alignment); 11633 verifyFormat("int oneTwoThree{0}; // comment\n" 11634 "unsigned oneTwo; // comment", 11635 Alignment); 11636 EXPECT_EQ("float const a = 5;\n" 11637 "\n" 11638 "int oneTwoThree = 123;", 11639 format("float const a = 5;\n" 11640 "\n" 11641 "int oneTwoThree= 123;", 11642 Alignment)); 11643 EXPECT_EQ("float a = 5;\n" 11644 "int one = 1;\n" 11645 "\n" 11646 "unsigned oneTwoThree = 123;", 11647 format("float a = 5;\n" 11648 "int one = 1;\n" 11649 "\n" 11650 "unsigned oneTwoThree = 123;", 11651 Alignment)); 11652 EXPECT_EQ("float a = 5;\n" 11653 "int one = 1;\n" 11654 "\n" 11655 "unsigned oneTwoThree = 123;\n" 11656 "int oneTwo = 12;", 11657 format("float a = 5;\n" 11658 "int one = 1;\n" 11659 "\n" 11660 "unsigned oneTwoThree = 123;\n" 11661 "int oneTwo = 12;", 11662 Alignment)); 11663 // Function prototype alignment 11664 verifyFormat("int a();\n" 11665 "double b();", 11666 Alignment); 11667 verifyFormat("int a(int x);\n" 11668 "double b();", 11669 Alignment); 11670 unsigned OldColumnLimit = Alignment.ColumnLimit; 11671 // We need to set ColumnLimit to zero, in order to stress nested alignments, 11672 // otherwise the function parameters will be re-flowed onto a single line. 11673 Alignment.ColumnLimit = 0; 11674 EXPECT_EQ("int a(int x,\n" 11675 " float y);\n" 11676 "double b(int x,\n" 11677 " double y);", 11678 format("int a(int x,\n" 11679 " float y);\n" 11680 "double b(int x,\n" 11681 " double y);", 11682 Alignment)); 11683 // This ensures that function parameters of function declarations are 11684 // correctly indented when their owning functions are indented. 11685 // The failure case here is for 'double y' to not be indented enough. 11686 EXPECT_EQ("double a(int x);\n" 11687 "int b(int y,\n" 11688 " double z);", 11689 format("double a(int x);\n" 11690 "int b(int y,\n" 11691 " double z);", 11692 Alignment)); 11693 // Set ColumnLimit low so that we induce wrapping immediately after 11694 // the function name and opening paren. 11695 Alignment.ColumnLimit = 13; 11696 verifyFormat("int function(\n" 11697 " int x,\n" 11698 " bool y);", 11699 Alignment); 11700 Alignment.ColumnLimit = OldColumnLimit; 11701 // Ensure function pointers don't screw up recursive alignment 11702 verifyFormat("int a(int x, void (*fp)(int y));\n" 11703 "double b();", 11704 Alignment); 11705 Alignment.AlignConsecutiveAssignments = true; 11706 // Ensure recursive alignment is broken by function braces, so that the 11707 // "a = 1" does not align with subsequent assignments inside the function 11708 // body. 11709 verifyFormat("int func(int a = 1) {\n" 11710 " int b = 2;\n" 11711 " int cc = 3;\n" 11712 "}", 11713 Alignment); 11714 verifyFormat("float something = 2000;\n" 11715 "double another = 911;\n" 11716 "int i = 1, j = 10;\n" 11717 "const int *oneMore = 1;\n" 11718 "unsigned i = 2;", 11719 Alignment); 11720 verifyFormat("int oneTwoThree = {0}; // comment\n" 11721 "unsigned oneTwo = 0; // comment", 11722 Alignment); 11723 // Make sure that scope is correctly tracked, in the absence of braces 11724 verifyFormat("for (int i = 0; i < n; i++)\n" 11725 " j = i;\n" 11726 "double x = 1;\n", 11727 Alignment); 11728 verifyFormat("if (int i = 0)\n" 11729 " j = i;\n" 11730 "double x = 1;\n", 11731 Alignment); 11732 // Ensure operator[] and operator() are comprehended 11733 verifyFormat("struct test {\n" 11734 " long long int foo();\n" 11735 " int operator[](int a);\n" 11736 " double bar();\n" 11737 "};\n", 11738 Alignment); 11739 verifyFormat("struct test {\n" 11740 " long long int foo();\n" 11741 " int operator()(int a);\n" 11742 " double bar();\n" 11743 "};\n", 11744 Alignment); 11745 EXPECT_EQ("void SomeFunction(int parameter = 0) {\n" 11746 " int const i = 1;\n" 11747 " int * j = 2;\n" 11748 " int big = 10000;\n" 11749 "\n" 11750 " unsigned oneTwoThree = 123;\n" 11751 " int oneTwo = 12;\n" 11752 " method();\n" 11753 " float k = 2;\n" 11754 " int ll = 10000;\n" 11755 "}", 11756 format("void SomeFunction(int parameter= 0) {\n" 11757 " int const i= 1;\n" 11758 " int *j=2;\n" 11759 " int big = 10000;\n" 11760 "\n" 11761 "unsigned oneTwoThree =123;\n" 11762 "int oneTwo = 12;\n" 11763 " method();\n" 11764 "float k= 2;\n" 11765 "int ll=10000;\n" 11766 "}", 11767 Alignment)); 11768 Alignment.AlignConsecutiveAssignments = false; 11769 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign; 11770 verifyFormat("#define A \\\n" 11771 " int aaaa = 12; \\\n" 11772 " float b = 23; \\\n" 11773 " const int ccc = 234; \\\n" 11774 " unsigned dddddddddd = 2345;", 11775 Alignment); 11776 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Left; 11777 verifyFormat("#define A \\\n" 11778 " int aaaa = 12; \\\n" 11779 " float b = 23; \\\n" 11780 " const int ccc = 234; \\\n" 11781 " unsigned dddddddddd = 2345;", 11782 Alignment); 11783 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Right; 11784 Alignment.ColumnLimit = 30; 11785 verifyFormat("#define A \\\n" 11786 " int aaaa = 12; \\\n" 11787 " float b = 23; \\\n" 11788 " const int ccc = 234; \\\n" 11789 " int dddddddddd = 2345;", 11790 Alignment); 11791 Alignment.ColumnLimit = 80; 11792 verifyFormat("void SomeFunction(int parameter = 1, int i = 2, int j = 3, int " 11793 "k = 4, int l = 5,\n" 11794 " int m = 6) {\n" 11795 " const int j = 10;\n" 11796 " otherThing = 1;\n" 11797 "}", 11798 Alignment); 11799 verifyFormat("void SomeFunction(int parameter = 0) {\n" 11800 " int const i = 1;\n" 11801 " int * j = 2;\n" 11802 " int big = 10000;\n" 11803 "}", 11804 Alignment); 11805 verifyFormat("class C {\n" 11806 "public:\n" 11807 " int i = 1;\n" 11808 " virtual void f() = 0;\n" 11809 "};", 11810 Alignment); 11811 verifyFormat("float i = 1;\n" 11812 "if (SomeType t = getSomething()) {\n" 11813 "}\n" 11814 "const unsigned j = 2;\n" 11815 "int big = 10000;", 11816 Alignment); 11817 verifyFormat("float j = 7;\n" 11818 "for (int k = 0; k < N; ++k) {\n" 11819 "}\n" 11820 "unsigned j = 2;\n" 11821 "int big = 10000;\n" 11822 "}", 11823 Alignment); 11824 Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 11825 verifyFormat("float i = 1;\n" 11826 "LooooooooooongType loooooooooooooooooooooongVariable\n" 11827 " = someLooooooooooooooooongFunction();\n" 11828 "int j = 2;", 11829 Alignment); 11830 Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_None; 11831 verifyFormat("int i = 1;\n" 11832 "LooooooooooongType loooooooooooooooooooooongVariable =\n" 11833 " someLooooooooooooooooongFunction();\n" 11834 "int j = 2;", 11835 Alignment); 11836 11837 Alignment.AlignConsecutiveAssignments = true; 11838 verifyFormat("auto lambda = []() {\n" 11839 " auto ii = 0;\n" 11840 " float j = 0;\n" 11841 " return 0;\n" 11842 "};\n" 11843 "int i = 0;\n" 11844 "float i2 = 0;\n" 11845 "auto v = type{\n" 11846 " i = 1, //\n" 11847 " (i = 2), //\n" 11848 " i = 3 //\n" 11849 "};", 11850 Alignment); 11851 Alignment.AlignConsecutiveAssignments = false; 11852 11853 verifyFormat( 11854 "int i = 1;\n" 11855 "SomeType a = SomeFunction(looooooooooooooooooooooongParameterA,\n" 11856 " loooooooooooooooooooooongParameterB);\n" 11857 "int j = 2;", 11858 Alignment); 11859 11860 // Test interactions with ColumnLimit and AlignConsecutiveAssignments: 11861 // We expect declarations and assignments to align, as long as it doesn't 11862 // exceed the column limit, starting a new alignment sequence whenever it 11863 // happens. 11864 Alignment.AlignConsecutiveAssignments = true; 11865 Alignment.ColumnLimit = 30; 11866 verifyFormat("float ii = 1;\n" 11867 "unsigned j = 2;\n" 11868 "int someVerylongVariable = 1;\n" 11869 "AnotherLongType ll = 123456;\n" 11870 "VeryVeryLongType k = 2;\n" 11871 "int myvar = 1;", 11872 Alignment); 11873 Alignment.ColumnLimit = 80; 11874 Alignment.AlignConsecutiveAssignments = false; 11875 11876 verifyFormat( 11877 "template <typename LongTemplate, typename VeryLongTemplateTypeName,\n" 11878 " typename LongType, typename B>\n" 11879 "auto foo() {}\n", 11880 Alignment); 11881 verifyFormat("float a, b = 1;\n" 11882 "int c = 2;\n" 11883 "int dd = 3;\n", 11884 Alignment); 11885 verifyFormat("int aa = ((1 > 2) ? 3 : 4);\n" 11886 "float b[1][] = {{3.f}};\n", 11887 Alignment); 11888 Alignment.AlignConsecutiveAssignments = true; 11889 verifyFormat("float a, b = 1;\n" 11890 "int c = 2;\n" 11891 "int dd = 3;\n", 11892 Alignment); 11893 verifyFormat("int aa = ((1 > 2) ? 3 : 4);\n" 11894 "float b[1][] = {{3.f}};\n", 11895 Alignment); 11896 Alignment.AlignConsecutiveAssignments = false; 11897 11898 Alignment.ColumnLimit = 30; 11899 Alignment.BinPackParameters = false; 11900 verifyFormat("void foo(float a,\n" 11901 " float b,\n" 11902 " int c,\n" 11903 " uint32_t *d) {\n" 11904 " int * e = 0;\n" 11905 " float f = 0;\n" 11906 " double g = 0;\n" 11907 "}\n" 11908 "void bar(ino_t a,\n" 11909 " int b,\n" 11910 " uint32_t *c,\n" 11911 " bool d) {}\n", 11912 Alignment); 11913 Alignment.BinPackParameters = true; 11914 Alignment.ColumnLimit = 80; 11915 11916 // Bug 33507 11917 Alignment.PointerAlignment = FormatStyle::PAS_Middle; 11918 verifyFormat( 11919 "auto found = range::find_if(vsProducts, [&](auto * aProduct) {\n" 11920 " static const Version verVs2017;\n" 11921 " return true;\n" 11922 "});\n", 11923 Alignment); 11924 Alignment.PointerAlignment = FormatStyle::PAS_Right; 11925 11926 // See llvm.org/PR35641 11927 Alignment.AlignConsecutiveDeclarations = true; 11928 verifyFormat("int func() { //\n" 11929 " int b;\n" 11930 " unsigned c;\n" 11931 "}", 11932 Alignment); 11933 11934 // See PR37175 11935 FormatStyle Style = getMozillaStyle(); 11936 Style.AlignConsecutiveDeclarations = true; 11937 EXPECT_EQ("DECOR1 /**/ int8_t /**/ DECOR2 /**/\n" 11938 "foo(int a);", 11939 format("DECOR1 /**/ int8_t /**/ DECOR2 /**/ foo (int a);", Style)); 11940 } 11941 11942 TEST_F(FormatTest, LinuxBraceBreaking) { 11943 FormatStyle LinuxBraceStyle = getLLVMStyle(); 11944 LinuxBraceStyle.BreakBeforeBraces = FormatStyle::BS_Linux; 11945 verifyFormat("namespace a\n" 11946 "{\n" 11947 "class A\n" 11948 "{\n" 11949 " void f()\n" 11950 " {\n" 11951 " if (true) {\n" 11952 " a();\n" 11953 " b();\n" 11954 " } else {\n" 11955 " a();\n" 11956 " }\n" 11957 " }\n" 11958 " void g() { return; }\n" 11959 "};\n" 11960 "struct B {\n" 11961 " int x;\n" 11962 "};\n" 11963 "} // namespace a\n", 11964 LinuxBraceStyle); 11965 verifyFormat("enum X {\n" 11966 " Y = 0,\n" 11967 "}\n", 11968 LinuxBraceStyle); 11969 verifyFormat("struct S {\n" 11970 " int Type;\n" 11971 " union {\n" 11972 " int x;\n" 11973 " double y;\n" 11974 " } Value;\n" 11975 " class C\n" 11976 " {\n" 11977 " MyFavoriteType Value;\n" 11978 " } Class;\n" 11979 "}\n", 11980 LinuxBraceStyle); 11981 } 11982 11983 TEST_F(FormatTest, MozillaBraceBreaking) { 11984 FormatStyle MozillaBraceStyle = getLLVMStyle(); 11985 MozillaBraceStyle.BreakBeforeBraces = FormatStyle::BS_Mozilla; 11986 MozillaBraceStyle.FixNamespaceComments = false; 11987 verifyFormat("namespace a {\n" 11988 "class A\n" 11989 "{\n" 11990 " void f()\n" 11991 " {\n" 11992 " if (true) {\n" 11993 " a();\n" 11994 " b();\n" 11995 " }\n" 11996 " }\n" 11997 " void g() { return; }\n" 11998 "};\n" 11999 "enum E\n" 12000 "{\n" 12001 " A,\n" 12002 " // foo\n" 12003 " B,\n" 12004 " C\n" 12005 "};\n" 12006 "struct B\n" 12007 "{\n" 12008 " int x;\n" 12009 "};\n" 12010 "}\n", 12011 MozillaBraceStyle); 12012 verifyFormat("struct S\n" 12013 "{\n" 12014 " int Type;\n" 12015 " union\n" 12016 " {\n" 12017 " int x;\n" 12018 " double y;\n" 12019 " } Value;\n" 12020 " class C\n" 12021 " {\n" 12022 " MyFavoriteType Value;\n" 12023 " } Class;\n" 12024 "}\n", 12025 MozillaBraceStyle); 12026 } 12027 12028 TEST_F(FormatTest, StroustrupBraceBreaking) { 12029 FormatStyle StroustrupBraceStyle = getLLVMStyle(); 12030 StroustrupBraceStyle.BreakBeforeBraces = FormatStyle::BS_Stroustrup; 12031 verifyFormat("namespace a {\n" 12032 "class A {\n" 12033 " void f()\n" 12034 " {\n" 12035 " if (true) {\n" 12036 " a();\n" 12037 " b();\n" 12038 " }\n" 12039 " }\n" 12040 " void g() { return; }\n" 12041 "};\n" 12042 "struct B {\n" 12043 " int x;\n" 12044 "};\n" 12045 "} // namespace a\n", 12046 StroustrupBraceStyle); 12047 12048 verifyFormat("void foo()\n" 12049 "{\n" 12050 " if (a) {\n" 12051 " a();\n" 12052 " }\n" 12053 " else {\n" 12054 " b();\n" 12055 " }\n" 12056 "}\n", 12057 StroustrupBraceStyle); 12058 12059 verifyFormat("#ifdef _DEBUG\n" 12060 "int foo(int i = 0)\n" 12061 "#else\n" 12062 "int foo(int i = 5)\n" 12063 "#endif\n" 12064 "{\n" 12065 " return i;\n" 12066 "}", 12067 StroustrupBraceStyle); 12068 12069 verifyFormat("void foo() {}\n" 12070 "void bar()\n" 12071 "#ifdef _DEBUG\n" 12072 "{\n" 12073 " foo();\n" 12074 "}\n" 12075 "#else\n" 12076 "{\n" 12077 "}\n" 12078 "#endif", 12079 StroustrupBraceStyle); 12080 12081 verifyFormat("void foobar() { int i = 5; }\n" 12082 "#ifdef _DEBUG\n" 12083 "void bar() {}\n" 12084 "#else\n" 12085 "void bar() { foobar(); }\n" 12086 "#endif", 12087 StroustrupBraceStyle); 12088 } 12089 12090 TEST_F(FormatTest, AllmanBraceBreaking) { 12091 FormatStyle AllmanBraceStyle = getLLVMStyle(); 12092 AllmanBraceStyle.BreakBeforeBraces = FormatStyle::BS_Allman; 12093 12094 EXPECT_EQ("namespace a\n" 12095 "{\n" 12096 "void f();\n" 12097 "void g();\n" 12098 "} // namespace a\n", 12099 format("namespace a\n" 12100 "{\n" 12101 "void f();\n" 12102 "void g();\n" 12103 "}\n", 12104 AllmanBraceStyle)); 12105 12106 verifyFormat("namespace a\n" 12107 "{\n" 12108 "class A\n" 12109 "{\n" 12110 " void f()\n" 12111 " {\n" 12112 " if (true)\n" 12113 " {\n" 12114 " a();\n" 12115 " b();\n" 12116 " }\n" 12117 " }\n" 12118 " void g() { return; }\n" 12119 "};\n" 12120 "struct B\n" 12121 "{\n" 12122 " int x;\n" 12123 "};\n" 12124 "union C\n" 12125 "{\n" 12126 "};\n" 12127 "} // namespace a", 12128 AllmanBraceStyle); 12129 12130 verifyFormat("void f()\n" 12131 "{\n" 12132 " if (true)\n" 12133 " {\n" 12134 " a();\n" 12135 " }\n" 12136 " else if (false)\n" 12137 " {\n" 12138 " b();\n" 12139 " }\n" 12140 " else\n" 12141 " {\n" 12142 " c();\n" 12143 " }\n" 12144 "}\n", 12145 AllmanBraceStyle); 12146 12147 verifyFormat("void f()\n" 12148 "{\n" 12149 " for (int i = 0; i < 10; ++i)\n" 12150 " {\n" 12151 " a();\n" 12152 " }\n" 12153 " while (false)\n" 12154 " {\n" 12155 " b();\n" 12156 " }\n" 12157 " do\n" 12158 " {\n" 12159 " c();\n" 12160 " } while (false)\n" 12161 "}\n", 12162 AllmanBraceStyle); 12163 12164 verifyFormat("void f(int a)\n" 12165 "{\n" 12166 " switch (a)\n" 12167 " {\n" 12168 " case 0:\n" 12169 " break;\n" 12170 " case 1:\n" 12171 " {\n" 12172 " break;\n" 12173 " }\n" 12174 " case 2:\n" 12175 " {\n" 12176 " }\n" 12177 " break;\n" 12178 " default:\n" 12179 " break;\n" 12180 " }\n" 12181 "}\n", 12182 AllmanBraceStyle); 12183 12184 verifyFormat("enum X\n" 12185 "{\n" 12186 " Y = 0,\n" 12187 "}\n", 12188 AllmanBraceStyle); 12189 verifyFormat("enum X\n" 12190 "{\n" 12191 " Y = 0\n" 12192 "}\n", 12193 AllmanBraceStyle); 12194 12195 verifyFormat("@interface BSApplicationController ()\n" 12196 "{\n" 12197 "@private\n" 12198 " id _extraIvar;\n" 12199 "}\n" 12200 "@end\n", 12201 AllmanBraceStyle); 12202 12203 verifyFormat("#ifdef _DEBUG\n" 12204 "int foo(int i = 0)\n" 12205 "#else\n" 12206 "int foo(int i = 5)\n" 12207 "#endif\n" 12208 "{\n" 12209 " return i;\n" 12210 "}", 12211 AllmanBraceStyle); 12212 12213 verifyFormat("void foo() {}\n" 12214 "void bar()\n" 12215 "#ifdef _DEBUG\n" 12216 "{\n" 12217 " foo();\n" 12218 "}\n" 12219 "#else\n" 12220 "{\n" 12221 "}\n" 12222 "#endif", 12223 AllmanBraceStyle); 12224 12225 verifyFormat("void foobar() { int i = 5; }\n" 12226 "#ifdef _DEBUG\n" 12227 "void bar() {}\n" 12228 "#else\n" 12229 "void bar() { foobar(); }\n" 12230 "#endif", 12231 AllmanBraceStyle); 12232 12233 // This shouldn't affect ObjC blocks.. 12234 verifyFormat("[self doSomeThingWithACompletionHandler:^{\n" 12235 " // ...\n" 12236 " int i;\n" 12237 "}];", 12238 AllmanBraceStyle); 12239 verifyFormat("void (^block)(void) = ^{\n" 12240 " // ...\n" 12241 " int i;\n" 12242 "};", 12243 AllmanBraceStyle); 12244 // .. or dict literals. 12245 verifyFormat("void f()\n" 12246 "{\n" 12247 " // ...\n" 12248 " [object someMethod:@{@\"a\" : @\"b\"}];\n" 12249 "}", 12250 AllmanBraceStyle); 12251 verifyFormat("void f()\n" 12252 "{\n" 12253 " // ...\n" 12254 " [object someMethod:@{a : @\"b\"}];\n" 12255 "}", 12256 AllmanBraceStyle); 12257 verifyFormat("int f()\n" 12258 "{ // comment\n" 12259 " return 42;\n" 12260 "}", 12261 AllmanBraceStyle); 12262 12263 AllmanBraceStyle.ColumnLimit = 19; 12264 verifyFormat("void f() { int i; }", AllmanBraceStyle); 12265 AllmanBraceStyle.ColumnLimit = 18; 12266 verifyFormat("void f()\n" 12267 "{\n" 12268 " int i;\n" 12269 "}", 12270 AllmanBraceStyle); 12271 AllmanBraceStyle.ColumnLimit = 80; 12272 12273 FormatStyle BreakBeforeBraceShortIfs = AllmanBraceStyle; 12274 BreakBeforeBraceShortIfs.AllowShortIfStatementsOnASingleLine = 12275 FormatStyle::SIS_WithoutElse; 12276 BreakBeforeBraceShortIfs.AllowShortLoopsOnASingleLine = true; 12277 verifyFormat("void f(bool b)\n" 12278 "{\n" 12279 " if (b)\n" 12280 " {\n" 12281 " return;\n" 12282 " }\n" 12283 "}\n", 12284 BreakBeforeBraceShortIfs); 12285 verifyFormat("void f(bool b)\n" 12286 "{\n" 12287 " if constexpr (b)\n" 12288 " {\n" 12289 " return;\n" 12290 " }\n" 12291 "}\n", 12292 BreakBeforeBraceShortIfs); 12293 verifyFormat("void f(bool b)\n" 12294 "{\n" 12295 " if CONSTEXPR (b)\n" 12296 " {\n" 12297 " return;\n" 12298 " }\n" 12299 "}\n", 12300 BreakBeforeBraceShortIfs); 12301 verifyFormat("void f(bool b)\n" 12302 "{\n" 12303 " if (b) return;\n" 12304 "}\n", 12305 BreakBeforeBraceShortIfs); 12306 verifyFormat("void f(bool b)\n" 12307 "{\n" 12308 " if constexpr (b) return;\n" 12309 "}\n", 12310 BreakBeforeBraceShortIfs); 12311 verifyFormat("void f(bool b)\n" 12312 "{\n" 12313 " if CONSTEXPR (b) return;\n" 12314 "}\n", 12315 BreakBeforeBraceShortIfs); 12316 verifyFormat("void f(bool b)\n" 12317 "{\n" 12318 " while (b)\n" 12319 " {\n" 12320 " return;\n" 12321 " }\n" 12322 "}\n", 12323 BreakBeforeBraceShortIfs); 12324 } 12325 12326 TEST_F(FormatTest, WhitesmithsBraceBreaking) { 12327 FormatStyle WhitesmithsBraceStyle = getLLVMStyle(); 12328 WhitesmithsBraceStyle.BreakBeforeBraces = FormatStyle::BS_Whitesmiths; 12329 12330 // Make a few changes to the style for testing purposes 12331 WhitesmithsBraceStyle.AllowShortFunctionsOnASingleLine = 12332 FormatStyle::SFS_Empty; 12333 WhitesmithsBraceStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None; 12334 WhitesmithsBraceStyle.ColumnLimit = 0; 12335 12336 // FIXME: this test case can't decide whether there should be a blank line 12337 // after the ~D() line or not. It adds one if one doesn't exist in the test 12338 // and it removes the line if one exists. 12339 /* 12340 verifyFormat("class A;\n" 12341 "namespace B\n" 12342 " {\n" 12343 "class C;\n" 12344 "// Comment\n" 12345 "class D\n" 12346 " {\n" 12347 "public:\n" 12348 " D();\n" 12349 " ~D() {}\n" 12350 "private:\n" 12351 " enum E\n" 12352 " {\n" 12353 " F\n" 12354 " }\n" 12355 " };\n" 12356 " } // namespace B\n", 12357 WhitesmithsBraceStyle); 12358 */ 12359 12360 verifyFormat("namespace a\n" 12361 " {\n" 12362 "class A\n" 12363 " {\n" 12364 " void f()\n" 12365 " {\n" 12366 " if (true)\n" 12367 " {\n" 12368 " a();\n" 12369 " b();\n" 12370 " }\n" 12371 " }\n" 12372 " void g()\n" 12373 " {\n" 12374 " return;\n" 12375 " }\n" 12376 " };\n" 12377 "struct B\n" 12378 " {\n" 12379 " int x;\n" 12380 " };\n" 12381 " } // namespace a", 12382 WhitesmithsBraceStyle); 12383 12384 verifyFormat("void f()\n" 12385 " {\n" 12386 " if (true)\n" 12387 " {\n" 12388 " a();\n" 12389 " }\n" 12390 " else if (false)\n" 12391 " {\n" 12392 " b();\n" 12393 " }\n" 12394 " else\n" 12395 " {\n" 12396 " c();\n" 12397 " }\n" 12398 " }\n", 12399 WhitesmithsBraceStyle); 12400 12401 verifyFormat("void f()\n" 12402 " {\n" 12403 " for (int i = 0; i < 10; ++i)\n" 12404 " {\n" 12405 " a();\n" 12406 " }\n" 12407 " while (false)\n" 12408 " {\n" 12409 " b();\n" 12410 " }\n" 12411 " do\n" 12412 " {\n" 12413 " c();\n" 12414 " } while (false)\n" 12415 " }\n", 12416 WhitesmithsBraceStyle); 12417 12418 // FIXME: the block and the break under case 2 in this test don't get indented 12419 // correctly 12420 /* 12421 verifyFormat("void switchTest1(int a)\n" 12422 " {\n" 12423 " switch (a)\n" 12424 " {\n" 12425 " case 2:\n" 12426 " {\n" 12427 " }\n" 12428 " break;\n" 12429 " }\n" 12430 " }\n", 12431 WhitesmithsBraceStyle); 12432 */ 12433 12434 // FIXME: the block and the break under case 2 in this test don't get indented 12435 // correctly 12436 /* 12437 verifyFormat("void switchTest2(int a)\n" 12438 " {\n" 12439 " switch (a)\n" 12440 " {\n" 12441 " case 0:\n" 12442 " break;\n" 12443 " case 1:\n" 12444 " {\n" 12445 " break;\n" 12446 " }\n" 12447 " case 2:\n" 12448 " {\n" 12449 " }\n" 12450 " break;\n" 12451 " default:\n" 12452 " break;\n" 12453 " }\n" 12454 " }\n", 12455 WhitesmithsBraceStyle); 12456 */ 12457 12458 verifyFormat("enum X\n" 12459 " {\n" 12460 " Y = 0, // testing\n" 12461 " }\n", 12462 WhitesmithsBraceStyle); 12463 12464 verifyFormat("enum X\n" 12465 " {\n" 12466 " Y = 0\n" 12467 " }\n", 12468 WhitesmithsBraceStyle); 12469 verifyFormat("enum X\n" 12470 " {\n" 12471 " Y = 0,\n" 12472 " Z = 1\n" 12473 " };\n", 12474 WhitesmithsBraceStyle); 12475 12476 verifyFormat("@interface BSApplicationController ()\n" 12477 " {\n" 12478 "@private\n" 12479 " id _extraIvar;\n" 12480 " }\n" 12481 "@end\n", 12482 WhitesmithsBraceStyle); 12483 12484 verifyFormat("#ifdef _DEBUG\n" 12485 "int foo(int i = 0)\n" 12486 "#else\n" 12487 "int foo(int i = 5)\n" 12488 "#endif\n" 12489 " {\n" 12490 " return i;\n" 12491 " }", 12492 WhitesmithsBraceStyle); 12493 12494 verifyFormat("void foo() {}\n" 12495 "void bar()\n" 12496 "#ifdef _DEBUG\n" 12497 " {\n" 12498 " foo();\n" 12499 " }\n" 12500 "#else\n" 12501 " {\n" 12502 " }\n" 12503 "#endif", 12504 WhitesmithsBraceStyle); 12505 12506 verifyFormat("void foobar()\n" 12507 " {\n" 12508 " int i = 5;\n" 12509 " }\n" 12510 "#ifdef _DEBUG\n" 12511 "void bar()\n" 12512 " {\n" 12513 " }\n" 12514 "#else\n" 12515 "void bar()\n" 12516 " {\n" 12517 " foobar();\n" 12518 " }\n" 12519 "#endif", 12520 WhitesmithsBraceStyle); 12521 12522 // This shouldn't affect ObjC blocks.. 12523 verifyFormat("[self doSomeThingWithACompletionHandler:^{\n" 12524 " // ...\n" 12525 " int i;\n" 12526 "}];", 12527 WhitesmithsBraceStyle); 12528 verifyFormat("void (^block)(void) = ^{\n" 12529 " // ...\n" 12530 " int i;\n" 12531 "};", 12532 WhitesmithsBraceStyle); 12533 // .. or dict literals. 12534 verifyFormat("void f()\n" 12535 " {\n" 12536 " [object someMethod:@{@\"a\" : @\"b\"}];\n" 12537 " }", 12538 WhitesmithsBraceStyle); 12539 12540 verifyFormat("int f()\n" 12541 " { // comment\n" 12542 " return 42;\n" 12543 " }", 12544 WhitesmithsBraceStyle); 12545 12546 FormatStyle BreakBeforeBraceShortIfs = WhitesmithsBraceStyle; 12547 BreakBeforeBraceShortIfs.AllowShortIfStatementsOnASingleLine = 12548 FormatStyle::SIS_Always; 12549 BreakBeforeBraceShortIfs.AllowShortLoopsOnASingleLine = true; 12550 verifyFormat("void f(bool b)\n" 12551 " {\n" 12552 " if (b)\n" 12553 " {\n" 12554 " return;\n" 12555 " }\n" 12556 " }\n", 12557 BreakBeforeBraceShortIfs); 12558 verifyFormat("void f(bool b)\n" 12559 " {\n" 12560 " if (b) return;\n" 12561 " }\n", 12562 BreakBeforeBraceShortIfs); 12563 verifyFormat("void f(bool b)\n" 12564 " {\n" 12565 " while (b)\n" 12566 " {\n" 12567 " return;\n" 12568 " }\n" 12569 " }\n", 12570 BreakBeforeBraceShortIfs); 12571 } 12572 12573 TEST_F(FormatTest, GNUBraceBreaking) { 12574 FormatStyle GNUBraceStyle = getLLVMStyle(); 12575 GNUBraceStyle.BreakBeforeBraces = FormatStyle::BS_GNU; 12576 verifyFormat("namespace a\n" 12577 "{\n" 12578 "class A\n" 12579 "{\n" 12580 " void f()\n" 12581 " {\n" 12582 " int a;\n" 12583 " {\n" 12584 " int b;\n" 12585 " }\n" 12586 " if (true)\n" 12587 " {\n" 12588 " a();\n" 12589 " b();\n" 12590 " }\n" 12591 " }\n" 12592 " void g() { return; }\n" 12593 "}\n" 12594 "} // namespace a", 12595 GNUBraceStyle); 12596 12597 verifyFormat("void f()\n" 12598 "{\n" 12599 " if (true)\n" 12600 " {\n" 12601 " a();\n" 12602 " }\n" 12603 " else if (false)\n" 12604 " {\n" 12605 " b();\n" 12606 " }\n" 12607 " else\n" 12608 " {\n" 12609 " c();\n" 12610 " }\n" 12611 "}\n", 12612 GNUBraceStyle); 12613 12614 verifyFormat("void f()\n" 12615 "{\n" 12616 " for (int i = 0; i < 10; ++i)\n" 12617 " {\n" 12618 " a();\n" 12619 " }\n" 12620 " while (false)\n" 12621 " {\n" 12622 " b();\n" 12623 " }\n" 12624 " do\n" 12625 " {\n" 12626 " c();\n" 12627 " }\n" 12628 " while (false);\n" 12629 "}\n", 12630 GNUBraceStyle); 12631 12632 verifyFormat("void f(int a)\n" 12633 "{\n" 12634 " switch (a)\n" 12635 " {\n" 12636 " case 0:\n" 12637 " break;\n" 12638 " case 1:\n" 12639 " {\n" 12640 " break;\n" 12641 " }\n" 12642 " case 2:\n" 12643 " {\n" 12644 " }\n" 12645 " break;\n" 12646 " default:\n" 12647 " break;\n" 12648 " }\n" 12649 "}\n", 12650 GNUBraceStyle); 12651 12652 verifyFormat("enum X\n" 12653 "{\n" 12654 " Y = 0,\n" 12655 "}\n", 12656 GNUBraceStyle); 12657 12658 verifyFormat("@interface BSApplicationController ()\n" 12659 "{\n" 12660 "@private\n" 12661 " id _extraIvar;\n" 12662 "}\n" 12663 "@end\n", 12664 GNUBraceStyle); 12665 12666 verifyFormat("#ifdef _DEBUG\n" 12667 "int foo(int i = 0)\n" 12668 "#else\n" 12669 "int foo(int i = 5)\n" 12670 "#endif\n" 12671 "{\n" 12672 " return i;\n" 12673 "}", 12674 GNUBraceStyle); 12675 12676 verifyFormat("void foo() {}\n" 12677 "void bar()\n" 12678 "#ifdef _DEBUG\n" 12679 "{\n" 12680 " foo();\n" 12681 "}\n" 12682 "#else\n" 12683 "{\n" 12684 "}\n" 12685 "#endif", 12686 GNUBraceStyle); 12687 12688 verifyFormat("void foobar() { int i = 5; }\n" 12689 "#ifdef _DEBUG\n" 12690 "void bar() {}\n" 12691 "#else\n" 12692 "void bar() { foobar(); }\n" 12693 "#endif", 12694 GNUBraceStyle); 12695 } 12696 12697 TEST_F(FormatTest, WebKitBraceBreaking) { 12698 FormatStyle WebKitBraceStyle = getLLVMStyle(); 12699 WebKitBraceStyle.BreakBeforeBraces = FormatStyle::BS_WebKit; 12700 WebKitBraceStyle.FixNamespaceComments = false; 12701 verifyFormat("namespace a {\n" 12702 "class A {\n" 12703 " void f()\n" 12704 " {\n" 12705 " if (true) {\n" 12706 " a();\n" 12707 " b();\n" 12708 " }\n" 12709 " }\n" 12710 " void g() { return; }\n" 12711 "};\n" 12712 "enum E {\n" 12713 " A,\n" 12714 " // foo\n" 12715 " B,\n" 12716 " C\n" 12717 "};\n" 12718 "struct B {\n" 12719 " int x;\n" 12720 "};\n" 12721 "}\n", 12722 WebKitBraceStyle); 12723 verifyFormat("struct S {\n" 12724 " int Type;\n" 12725 " union {\n" 12726 " int x;\n" 12727 " double y;\n" 12728 " } Value;\n" 12729 " class C {\n" 12730 " MyFavoriteType Value;\n" 12731 " } Class;\n" 12732 "};\n", 12733 WebKitBraceStyle); 12734 } 12735 12736 TEST_F(FormatTest, CatchExceptionReferenceBinding) { 12737 verifyFormat("void f() {\n" 12738 " try {\n" 12739 " } catch (const Exception &e) {\n" 12740 " }\n" 12741 "}\n", 12742 getLLVMStyle()); 12743 } 12744 12745 TEST_F(FormatTest, UnderstandsPragmas) { 12746 verifyFormat("#pragma omp reduction(| : var)"); 12747 verifyFormat("#pragma omp reduction(+ : var)"); 12748 12749 EXPECT_EQ("#pragma mark Any non-hyphenated or hyphenated string " 12750 "(including parentheses).", 12751 format("#pragma mark Any non-hyphenated or hyphenated string " 12752 "(including parentheses).")); 12753 } 12754 12755 TEST_F(FormatTest, UnderstandPragmaOption) { 12756 verifyFormat("#pragma option -C -A"); 12757 12758 EXPECT_EQ("#pragma option -C -A", format("#pragma option -C -A")); 12759 } 12760 12761 TEST_F(FormatTest, OptimizeBreakPenaltyVsExcess) { 12762 FormatStyle Style = getLLVMStyle(); 12763 Style.ColumnLimit = 20; 12764 12765 // See PR41213 12766 EXPECT_EQ("/*\n" 12767 " *\t9012345\n" 12768 " * /8901\n" 12769 " */", 12770 format("/*\n" 12771 " *\t9012345 /8901\n" 12772 " */", 12773 Style)); 12774 EXPECT_EQ("/*\n" 12775 " *345678\n" 12776 " *\t/8901\n" 12777 " */", 12778 format("/*\n" 12779 " *345678\t/8901\n" 12780 " */", 12781 Style)); 12782 12783 verifyFormat("int a; // the\n" 12784 " // comment", 12785 Style); 12786 EXPECT_EQ("int a; /* first line\n" 12787 " * second\n" 12788 " * line third\n" 12789 " * line\n" 12790 " */", 12791 format("int a; /* first line\n" 12792 " * second\n" 12793 " * line third\n" 12794 " * line\n" 12795 " */", 12796 Style)); 12797 EXPECT_EQ("int a; // first line\n" 12798 " // second\n" 12799 " // line third\n" 12800 " // line", 12801 format("int a; // first line\n" 12802 " // second line\n" 12803 " // third line", 12804 Style)); 12805 12806 Style.PenaltyExcessCharacter = 90; 12807 verifyFormat("int a; // the comment", Style); 12808 EXPECT_EQ("int a; // the comment\n" 12809 " // aaa", 12810 format("int a; // the comment aaa", Style)); 12811 EXPECT_EQ("int a; /* first line\n" 12812 " * second line\n" 12813 " * third line\n" 12814 " */", 12815 format("int a; /* first line\n" 12816 " * second line\n" 12817 " * third line\n" 12818 " */", 12819 Style)); 12820 EXPECT_EQ("int a; // first line\n" 12821 " // second line\n" 12822 " // third line", 12823 format("int a; // first line\n" 12824 " // second line\n" 12825 " // third line", 12826 Style)); 12827 // FIXME: Investigate why this is not getting the same layout as the test 12828 // above. 12829 EXPECT_EQ("int a; /* first line\n" 12830 " * second line\n" 12831 " * third line\n" 12832 " */", 12833 format("int a; /* first line second line third line" 12834 "\n*/", 12835 Style)); 12836 12837 EXPECT_EQ("// foo bar baz bazfoo\n" 12838 "// foo bar foo bar\n", 12839 format("// foo bar baz bazfoo\n" 12840 "// foo bar foo bar\n", 12841 Style)); 12842 EXPECT_EQ("// foo bar baz bazfoo\n" 12843 "// foo bar foo bar\n", 12844 format("// foo bar baz bazfoo\n" 12845 "// foo bar foo bar\n", 12846 Style)); 12847 12848 // FIXME: Optimally, we'd keep bazfoo on the first line and reflow bar to the 12849 // next one. 12850 EXPECT_EQ("// foo bar baz bazfoo\n" 12851 "// bar foo bar\n", 12852 format("// foo bar baz bazfoo bar\n" 12853 "// foo bar\n", 12854 Style)); 12855 12856 EXPECT_EQ("// foo bar baz bazfoo\n" 12857 "// foo bar baz bazfoo\n" 12858 "// bar foo bar\n", 12859 format("// foo bar baz bazfoo\n" 12860 "// foo bar baz bazfoo bar\n" 12861 "// foo bar\n", 12862 Style)); 12863 12864 EXPECT_EQ("// foo bar baz bazfoo\n" 12865 "// foo bar baz bazfoo\n" 12866 "// bar foo bar\n", 12867 format("// foo bar baz bazfoo\n" 12868 "// foo bar baz bazfoo bar\n" 12869 "// foo bar\n", 12870 Style)); 12871 12872 // Make sure we do not keep protruding characters if strict mode reflow is 12873 // cheaper than keeping protruding characters. 12874 Style.ColumnLimit = 21; 12875 EXPECT_EQ( 12876 "// foo foo foo foo\n" 12877 "// foo foo foo foo\n" 12878 "// foo foo foo foo\n", 12879 format("// foo foo foo foo foo foo foo foo foo foo foo foo\n", Style)); 12880 12881 EXPECT_EQ("int a = /* long block\n" 12882 " comment */\n" 12883 " 42;", 12884 format("int a = /* long block comment */ 42;", Style)); 12885 } 12886 12887 #define EXPECT_ALL_STYLES_EQUAL(Styles) \ 12888 for (size_t i = 1; i < Styles.size(); ++i) \ 12889 EXPECT_EQ(Styles[0], Styles[i]) \ 12890 << "Style #" << i << " of " << Styles.size() << " differs from Style #0" 12891 12892 TEST_F(FormatTest, GetsPredefinedStyleByName) { 12893 SmallVector<FormatStyle, 3> Styles; 12894 Styles.resize(3); 12895 12896 Styles[0] = getLLVMStyle(); 12897 EXPECT_TRUE(getPredefinedStyle("LLVM", FormatStyle::LK_Cpp, &Styles[1])); 12898 EXPECT_TRUE(getPredefinedStyle("lLvM", FormatStyle::LK_Cpp, &Styles[2])); 12899 EXPECT_ALL_STYLES_EQUAL(Styles); 12900 12901 Styles[0] = getGoogleStyle(); 12902 EXPECT_TRUE(getPredefinedStyle("Google", FormatStyle::LK_Cpp, &Styles[1])); 12903 EXPECT_TRUE(getPredefinedStyle("gOOgle", FormatStyle::LK_Cpp, &Styles[2])); 12904 EXPECT_ALL_STYLES_EQUAL(Styles); 12905 12906 Styles[0] = getGoogleStyle(FormatStyle::LK_JavaScript); 12907 EXPECT_TRUE( 12908 getPredefinedStyle("Google", FormatStyle::LK_JavaScript, &Styles[1])); 12909 EXPECT_TRUE( 12910 getPredefinedStyle("gOOgle", FormatStyle::LK_JavaScript, &Styles[2])); 12911 EXPECT_ALL_STYLES_EQUAL(Styles); 12912 12913 Styles[0] = getChromiumStyle(FormatStyle::LK_Cpp); 12914 EXPECT_TRUE(getPredefinedStyle("Chromium", FormatStyle::LK_Cpp, &Styles[1])); 12915 EXPECT_TRUE(getPredefinedStyle("cHRoMiUM", FormatStyle::LK_Cpp, &Styles[2])); 12916 EXPECT_ALL_STYLES_EQUAL(Styles); 12917 12918 Styles[0] = getMozillaStyle(); 12919 EXPECT_TRUE(getPredefinedStyle("Mozilla", FormatStyle::LK_Cpp, &Styles[1])); 12920 EXPECT_TRUE(getPredefinedStyle("moZILla", FormatStyle::LK_Cpp, &Styles[2])); 12921 EXPECT_ALL_STYLES_EQUAL(Styles); 12922 12923 Styles[0] = getWebKitStyle(); 12924 EXPECT_TRUE(getPredefinedStyle("WebKit", FormatStyle::LK_Cpp, &Styles[1])); 12925 EXPECT_TRUE(getPredefinedStyle("wEbKit", FormatStyle::LK_Cpp, &Styles[2])); 12926 EXPECT_ALL_STYLES_EQUAL(Styles); 12927 12928 Styles[0] = getGNUStyle(); 12929 EXPECT_TRUE(getPredefinedStyle("GNU", FormatStyle::LK_Cpp, &Styles[1])); 12930 EXPECT_TRUE(getPredefinedStyle("gnU", FormatStyle::LK_Cpp, &Styles[2])); 12931 EXPECT_ALL_STYLES_EQUAL(Styles); 12932 12933 EXPECT_FALSE(getPredefinedStyle("qwerty", FormatStyle::LK_Cpp, &Styles[0])); 12934 } 12935 12936 TEST_F(FormatTest, GetsCorrectBasedOnStyle) { 12937 SmallVector<FormatStyle, 8> Styles; 12938 Styles.resize(2); 12939 12940 Styles[0] = getGoogleStyle(); 12941 Styles[1] = getLLVMStyle(); 12942 EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Styles[1]).value()); 12943 EXPECT_ALL_STYLES_EQUAL(Styles); 12944 12945 Styles.resize(5); 12946 Styles[0] = getGoogleStyle(FormatStyle::LK_JavaScript); 12947 Styles[1] = getLLVMStyle(); 12948 Styles[1].Language = FormatStyle::LK_JavaScript; 12949 EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Styles[1]).value()); 12950 12951 Styles[2] = getLLVMStyle(); 12952 Styles[2].Language = FormatStyle::LK_JavaScript; 12953 EXPECT_EQ(0, parseConfiguration("Language: JavaScript\n" 12954 "BasedOnStyle: Google", 12955 &Styles[2]) 12956 .value()); 12957 12958 Styles[3] = getLLVMStyle(); 12959 Styles[3].Language = FormatStyle::LK_JavaScript; 12960 EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google\n" 12961 "Language: JavaScript", 12962 &Styles[3]) 12963 .value()); 12964 12965 Styles[4] = getLLVMStyle(); 12966 Styles[4].Language = FormatStyle::LK_JavaScript; 12967 EXPECT_EQ(0, parseConfiguration("---\n" 12968 "BasedOnStyle: LLVM\n" 12969 "IndentWidth: 123\n" 12970 "---\n" 12971 "BasedOnStyle: Google\n" 12972 "Language: JavaScript", 12973 &Styles[4]) 12974 .value()); 12975 EXPECT_ALL_STYLES_EQUAL(Styles); 12976 } 12977 12978 #define CHECK_PARSE_BOOL_FIELD(FIELD, CONFIG_NAME) \ 12979 Style.FIELD = false; \ 12980 EXPECT_EQ(0, parseConfiguration(CONFIG_NAME ": true", &Style).value()); \ 12981 EXPECT_TRUE(Style.FIELD); \ 12982 EXPECT_EQ(0, parseConfiguration(CONFIG_NAME ": false", &Style).value()); \ 12983 EXPECT_FALSE(Style.FIELD); 12984 12985 #define CHECK_PARSE_BOOL(FIELD) CHECK_PARSE_BOOL_FIELD(FIELD, #FIELD) 12986 12987 #define CHECK_PARSE_NESTED_BOOL_FIELD(STRUCT, FIELD, CONFIG_NAME) \ 12988 Style.STRUCT.FIELD = false; \ 12989 EXPECT_EQ(0, \ 12990 parseConfiguration(#STRUCT ":\n " CONFIG_NAME ": true", &Style) \ 12991 .value()); \ 12992 EXPECT_TRUE(Style.STRUCT.FIELD); \ 12993 EXPECT_EQ(0, \ 12994 parseConfiguration(#STRUCT ":\n " CONFIG_NAME ": false", &Style) \ 12995 .value()); \ 12996 EXPECT_FALSE(Style.STRUCT.FIELD); 12997 12998 #define CHECK_PARSE_NESTED_BOOL(STRUCT, FIELD) \ 12999 CHECK_PARSE_NESTED_BOOL_FIELD(STRUCT, FIELD, #FIELD) 13000 13001 #define CHECK_PARSE(TEXT, FIELD, VALUE) \ 13002 EXPECT_NE(VALUE, Style.FIELD); \ 13003 EXPECT_EQ(0, parseConfiguration(TEXT, &Style).value()); \ 13004 EXPECT_EQ(VALUE, Style.FIELD) 13005 13006 TEST_F(FormatTest, ParsesConfigurationBools) { 13007 FormatStyle Style = {}; 13008 Style.Language = FormatStyle::LK_Cpp; 13009 CHECK_PARSE_BOOL(AlignOperands); 13010 CHECK_PARSE_BOOL(AlignTrailingComments); 13011 CHECK_PARSE_BOOL(AlignConsecutiveAssignments); 13012 CHECK_PARSE_BOOL(AlignConsecutiveDeclarations); 13013 CHECK_PARSE_BOOL(AlignConsecutiveMacros); 13014 CHECK_PARSE_BOOL(AllowAllArgumentsOnNextLine); 13015 CHECK_PARSE_BOOL(AllowAllConstructorInitializersOnNextLine); 13016 CHECK_PARSE_BOOL(AllowAllParametersOfDeclarationOnNextLine); 13017 CHECK_PARSE_BOOL(AllowShortCaseLabelsOnASingleLine); 13018 CHECK_PARSE_BOOL(AllowShortEnumsOnASingleLine); 13019 CHECK_PARSE_BOOL(AllowShortLoopsOnASingleLine); 13020 CHECK_PARSE_BOOL(BinPackArguments); 13021 CHECK_PARSE_BOOL(BinPackParameters); 13022 CHECK_PARSE_BOOL(BreakAfterJavaFieldAnnotations); 13023 CHECK_PARSE_BOOL(BreakBeforeTernaryOperators); 13024 CHECK_PARSE_BOOL(BreakStringLiterals); 13025 CHECK_PARSE_BOOL(CompactNamespaces); 13026 CHECK_PARSE_BOOL(ConstructorInitializerAllOnOneLineOrOnePerLine); 13027 CHECK_PARSE_BOOL(DeriveLineEnding); 13028 CHECK_PARSE_BOOL(DerivePointerAlignment); 13029 CHECK_PARSE_BOOL_FIELD(DerivePointerAlignment, "DerivePointerBinding"); 13030 CHECK_PARSE_BOOL(DisableFormat); 13031 CHECK_PARSE_BOOL(IndentCaseLabels); 13032 CHECK_PARSE_BOOL(IndentCaseBlocks); 13033 CHECK_PARSE_BOOL(IndentGotoLabels); 13034 CHECK_PARSE_BOOL(IndentWrappedFunctionNames); 13035 CHECK_PARSE_BOOL(KeepEmptyLinesAtTheStartOfBlocks); 13036 CHECK_PARSE_BOOL(ObjCSpaceAfterProperty); 13037 CHECK_PARSE_BOOL(ObjCSpaceBeforeProtocolList); 13038 CHECK_PARSE_BOOL(Cpp11BracedListStyle); 13039 CHECK_PARSE_BOOL(ReflowComments); 13040 CHECK_PARSE_BOOL(SortIncludes); 13041 CHECK_PARSE_BOOL(SortUsingDeclarations); 13042 CHECK_PARSE_BOOL(SpacesInParentheses); 13043 CHECK_PARSE_BOOL(SpacesInSquareBrackets); 13044 CHECK_PARSE_BOOL(SpacesInAngles); 13045 CHECK_PARSE_BOOL(SpacesInConditionalStatement); 13046 CHECK_PARSE_BOOL(SpaceInEmptyBlock); 13047 CHECK_PARSE_BOOL(SpaceInEmptyParentheses); 13048 CHECK_PARSE_BOOL(SpacesInContainerLiterals); 13049 CHECK_PARSE_BOOL(SpacesInCStyleCastParentheses); 13050 CHECK_PARSE_BOOL(SpaceAfterCStyleCast); 13051 CHECK_PARSE_BOOL(SpaceAfterTemplateKeyword); 13052 CHECK_PARSE_BOOL(SpaceAfterLogicalNot); 13053 CHECK_PARSE_BOOL(SpaceBeforeAssignmentOperators); 13054 CHECK_PARSE_BOOL(SpaceBeforeCpp11BracedList); 13055 CHECK_PARSE_BOOL(SpaceBeforeCtorInitializerColon); 13056 CHECK_PARSE_BOOL(SpaceBeforeInheritanceColon); 13057 CHECK_PARSE_BOOL(SpaceBeforeRangeBasedForLoopColon); 13058 CHECK_PARSE_BOOL(SpaceBeforeSquareBrackets); 13059 CHECK_PARSE_BOOL(UseCRLF); 13060 13061 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterCaseLabel); 13062 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterClass); 13063 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterEnum); 13064 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterFunction); 13065 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterNamespace); 13066 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterObjCDeclaration); 13067 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterStruct); 13068 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterUnion); 13069 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterExternBlock); 13070 CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeCatch); 13071 CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeElse); 13072 CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeLambdaBody); 13073 CHECK_PARSE_NESTED_BOOL(BraceWrapping, IndentBraces); 13074 CHECK_PARSE_NESTED_BOOL(BraceWrapping, SplitEmptyFunction); 13075 CHECK_PARSE_NESTED_BOOL(BraceWrapping, SplitEmptyRecord); 13076 CHECK_PARSE_NESTED_BOOL(BraceWrapping, SplitEmptyNamespace); 13077 } 13078 13079 #undef CHECK_PARSE_BOOL 13080 13081 TEST_F(FormatTest, ParsesConfiguration) { 13082 FormatStyle Style = {}; 13083 Style.Language = FormatStyle::LK_Cpp; 13084 CHECK_PARSE("AccessModifierOffset: -1234", AccessModifierOffset, -1234); 13085 CHECK_PARSE("ConstructorInitializerIndentWidth: 1234", 13086 ConstructorInitializerIndentWidth, 1234u); 13087 CHECK_PARSE("ObjCBlockIndentWidth: 1234", ObjCBlockIndentWidth, 1234u); 13088 CHECK_PARSE("ColumnLimit: 1234", ColumnLimit, 1234u); 13089 CHECK_PARSE("MaxEmptyLinesToKeep: 1234", MaxEmptyLinesToKeep, 1234u); 13090 CHECK_PARSE("PenaltyBreakAssignment: 1234", PenaltyBreakAssignment, 1234u); 13091 CHECK_PARSE("PenaltyBreakBeforeFirstCallParameter: 1234", 13092 PenaltyBreakBeforeFirstCallParameter, 1234u); 13093 CHECK_PARSE("PenaltyBreakTemplateDeclaration: 1234", 13094 PenaltyBreakTemplateDeclaration, 1234u); 13095 CHECK_PARSE("PenaltyExcessCharacter: 1234", PenaltyExcessCharacter, 1234u); 13096 CHECK_PARSE("PenaltyReturnTypeOnItsOwnLine: 1234", 13097 PenaltyReturnTypeOnItsOwnLine, 1234u); 13098 CHECK_PARSE("SpacesBeforeTrailingComments: 1234", 13099 SpacesBeforeTrailingComments, 1234u); 13100 CHECK_PARSE("IndentWidth: 32", IndentWidth, 32u); 13101 CHECK_PARSE("ContinuationIndentWidth: 11", ContinuationIndentWidth, 11u); 13102 CHECK_PARSE("CommentPragmas: '// abc$'", CommentPragmas, "// abc$"); 13103 13104 Style.PointerAlignment = FormatStyle::PAS_Middle; 13105 CHECK_PARSE("PointerAlignment: Left", PointerAlignment, 13106 FormatStyle::PAS_Left); 13107 CHECK_PARSE("PointerAlignment: Right", PointerAlignment, 13108 FormatStyle::PAS_Right); 13109 CHECK_PARSE("PointerAlignment: Middle", PointerAlignment, 13110 FormatStyle::PAS_Middle); 13111 // For backward compatibility: 13112 CHECK_PARSE("PointerBindsToType: Left", PointerAlignment, 13113 FormatStyle::PAS_Left); 13114 CHECK_PARSE("PointerBindsToType: Right", PointerAlignment, 13115 FormatStyle::PAS_Right); 13116 CHECK_PARSE("PointerBindsToType: Middle", PointerAlignment, 13117 FormatStyle::PAS_Middle); 13118 13119 Style.Standard = FormatStyle::LS_Auto; 13120 CHECK_PARSE("Standard: c++03", Standard, FormatStyle::LS_Cpp03); 13121 CHECK_PARSE("Standard: c++11", Standard, FormatStyle::LS_Cpp11); 13122 CHECK_PARSE("Standard: c++14", Standard, FormatStyle::LS_Cpp14); 13123 CHECK_PARSE("Standard: c++17", Standard, FormatStyle::LS_Cpp17); 13124 CHECK_PARSE("Standard: c++20", Standard, FormatStyle::LS_Cpp20); 13125 CHECK_PARSE("Standard: Auto", Standard, FormatStyle::LS_Auto); 13126 CHECK_PARSE("Standard: Latest", Standard, FormatStyle::LS_Latest); 13127 // Legacy aliases: 13128 CHECK_PARSE("Standard: Cpp03", Standard, FormatStyle::LS_Cpp03); 13129 CHECK_PARSE("Standard: Cpp11", Standard, FormatStyle::LS_Latest); 13130 CHECK_PARSE("Standard: C++03", Standard, FormatStyle::LS_Cpp03); 13131 CHECK_PARSE("Standard: C++11", Standard, FormatStyle::LS_Cpp11); 13132 13133 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 13134 CHECK_PARSE("BreakBeforeBinaryOperators: NonAssignment", 13135 BreakBeforeBinaryOperators, FormatStyle::BOS_NonAssignment); 13136 CHECK_PARSE("BreakBeforeBinaryOperators: None", BreakBeforeBinaryOperators, 13137 FormatStyle::BOS_None); 13138 CHECK_PARSE("BreakBeforeBinaryOperators: All", BreakBeforeBinaryOperators, 13139 FormatStyle::BOS_All); 13140 // For backward compatibility: 13141 CHECK_PARSE("BreakBeforeBinaryOperators: false", BreakBeforeBinaryOperators, 13142 FormatStyle::BOS_None); 13143 CHECK_PARSE("BreakBeforeBinaryOperators: true", BreakBeforeBinaryOperators, 13144 FormatStyle::BOS_All); 13145 13146 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon; 13147 CHECK_PARSE("BreakConstructorInitializers: BeforeComma", 13148 BreakConstructorInitializers, FormatStyle::BCIS_BeforeComma); 13149 CHECK_PARSE("BreakConstructorInitializers: AfterColon", 13150 BreakConstructorInitializers, FormatStyle::BCIS_AfterColon); 13151 CHECK_PARSE("BreakConstructorInitializers: BeforeColon", 13152 BreakConstructorInitializers, FormatStyle::BCIS_BeforeColon); 13153 // For backward compatibility: 13154 CHECK_PARSE("BreakConstructorInitializersBeforeComma: true", 13155 BreakConstructorInitializers, FormatStyle::BCIS_BeforeComma); 13156 13157 Style.BreakInheritanceList = FormatStyle::BILS_BeforeColon; 13158 CHECK_PARSE("BreakInheritanceList: BeforeComma", BreakInheritanceList, 13159 FormatStyle::BILS_BeforeComma); 13160 CHECK_PARSE("BreakInheritanceList: AfterColon", BreakInheritanceList, 13161 FormatStyle::BILS_AfterColon); 13162 CHECK_PARSE("BreakInheritanceList: BeforeColon", BreakInheritanceList, 13163 FormatStyle::BILS_BeforeColon); 13164 // For backward compatibility: 13165 CHECK_PARSE("BreakBeforeInheritanceComma: true", BreakInheritanceList, 13166 FormatStyle::BILS_BeforeComma); 13167 13168 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 13169 CHECK_PARSE("AlignAfterOpenBracket: Align", AlignAfterOpenBracket, 13170 FormatStyle::BAS_Align); 13171 CHECK_PARSE("AlignAfterOpenBracket: DontAlign", AlignAfterOpenBracket, 13172 FormatStyle::BAS_DontAlign); 13173 CHECK_PARSE("AlignAfterOpenBracket: AlwaysBreak", AlignAfterOpenBracket, 13174 FormatStyle::BAS_AlwaysBreak); 13175 // For backward compatibility: 13176 CHECK_PARSE("AlignAfterOpenBracket: false", AlignAfterOpenBracket, 13177 FormatStyle::BAS_DontAlign); 13178 CHECK_PARSE("AlignAfterOpenBracket: true", AlignAfterOpenBracket, 13179 FormatStyle::BAS_Align); 13180 13181 Style.AlignEscapedNewlines = FormatStyle::ENAS_Left; 13182 CHECK_PARSE("AlignEscapedNewlines: DontAlign", AlignEscapedNewlines, 13183 FormatStyle::ENAS_DontAlign); 13184 CHECK_PARSE("AlignEscapedNewlines: Left", AlignEscapedNewlines, 13185 FormatStyle::ENAS_Left); 13186 CHECK_PARSE("AlignEscapedNewlines: Right", AlignEscapedNewlines, 13187 FormatStyle::ENAS_Right); 13188 // For backward compatibility: 13189 CHECK_PARSE("AlignEscapedNewlinesLeft: true", AlignEscapedNewlines, 13190 FormatStyle::ENAS_Left); 13191 CHECK_PARSE("AlignEscapedNewlinesLeft: false", AlignEscapedNewlines, 13192 FormatStyle::ENAS_Right); 13193 13194 Style.UseTab = FormatStyle::UT_ForIndentation; 13195 CHECK_PARSE("UseTab: Never", UseTab, FormatStyle::UT_Never); 13196 CHECK_PARSE("UseTab: ForIndentation", UseTab, FormatStyle::UT_ForIndentation); 13197 CHECK_PARSE("UseTab: Always", UseTab, FormatStyle::UT_Always); 13198 CHECK_PARSE("UseTab: ForContinuationAndIndentation", UseTab, 13199 FormatStyle::UT_ForContinuationAndIndentation); 13200 CHECK_PARSE("UseTab: AlignWithSpaces", UseTab, 13201 FormatStyle::UT_AlignWithSpaces); 13202 // For backward compatibility: 13203 CHECK_PARSE("UseTab: false", UseTab, FormatStyle::UT_Never); 13204 CHECK_PARSE("UseTab: true", UseTab, FormatStyle::UT_Always); 13205 13206 Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Empty; 13207 CHECK_PARSE("AllowShortBlocksOnASingleLine: Never", 13208 AllowShortBlocksOnASingleLine, FormatStyle::SBS_Never); 13209 CHECK_PARSE("AllowShortBlocksOnASingleLine: Empty", 13210 AllowShortBlocksOnASingleLine, FormatStyle::SBS_Empty); 13211 CHECK_PARSE("AllowShortBlocksOnASingleLine: Always", 13212 AllowShortBlocksOnASingleLine, FormatStyle::SBS_Always); 13213 // For backward compatibility: 13214 CHECK_PARSE("AllowShortBlocksOnASingleLine: false", 13215 AllowShortBlocksOnASingleLine, FormatStyle::SBS_Never); 13216 CHECK_PARSE("AllowShortBlocksOnASingleLine: true", 13217 AllowShortBlocksOnASingleLine, FormatStyle::SBS_Always); 13218 13219 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline; 13220 CHECK_PARSE("AllowShortFunctionsOnASingleLine: None", 13221 AllowShortFunctionsOnASingleLine, FormatStyle::SFS_None); 13222 CHECK_PARSE("AllowShortFunctionsOnASingleLine: Inline", 13223 AllowShortFunctionsOnASingleLine, FormatStyle::SFS_Inline); 13224 CHECK_PARSE("AllowShortFunctionsOnASingleLine: Empty", 13225 AllowShortFunctionsOnASingleLine, FormatStyle::SFS_Empty); 13226 CHECK_PARSE("AllowShortFunctionsOnASingleLine: All", 13227 AllowShortFunctionsOnASingleLine, FormatStyle::SFS_All); 13228 // For backward compatibility: 13229 CHECK_PARSE("AllowShortFunctionsOnASingleLine: false", 13230 AllowShortFunctionsOnASingleLine, FormatStyle::SFS_None); 13231 CHECK_PARSE("AllowShortFunctionsOnASingleLine: true", 13232 AllowShortFunctionsOnASingleLine, FormatStyle::SFS_All); 13233 13234 Style.SpaceBeforeParens = FormatStyle::SBPO_Always; 13235 CHECK_PARSE("SpaceBeforeParens: Never", SpaceBeforeParens, 13236 FormatStyle::SBPO_Never); 13237 CHECK_PARSE("SpaceBeforeParens: Always", SpaceBeforeParens, 13238 FormatStyle::SBPO_Always); 13239 CHECK_PARSE("SpaceBeforeParens: ControlStatements", SpaceBeforeParens, 13240 FormatStyle::SBPO_ControlStatements); 13241 CHECK_PARSE("SpaceBeforeParens: NonEmptyParentheses", SpaceBeforeParens, 13242 FormatStyle::SBPO_NonEmptyParentheses); 13243 // For backward compatibility: 13244 CHECK_PARSE("SpaceAfterControlStatementKeyword: false", SpaceBeforeParens, 13245 FormatStyle::SBPO_Never); 13246 CHECK_PARSE("SpaceAfterControlStatementKeyword: true", SpaceBeforeParens, 13247 FormatStyle::SBPO_ControlStatements); 13248 13249 Style.ColumnLimit = 123; 13250 FormatStyle BaseStyle = getLLVMStyle(); 13251 CHECK_PARSE("BasedOnStyle: LLVM", ColumnLimit, BaseStyle.ColumnLimit); 13252 CHECK_PARSE("BasedOnStyle: LLVM\nColumnLimit: 1234", ColumnLimit, 1234u); 13253 13254 Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup; 13255 CHECK_PARSE("BreakBeforeBraces: Attach", BreakBeforeBraces, 13256 FormatStyle::BS_Attach); 13257 CHECK_PARSE("BreakBeforeBraces: Linux", BreakBeforeBraces, 13258 FormatStyle::BS_Linux); 13259 CHECK_PARSE("BreakBeforeBraces: Mozilla", BreakBeforeBraces, 13260 FormatStyle::BS_Mozilla); 13261 CHECK_PARSE("BreakBeforeBraces: Stroustrup", BreakBeforeBraces, 13262 FormatStyle::BS_Stroustrup); 13263 CHECK_PARSE("BreakBeforeBraces: Allman", BreakBeforeBraces, 13264 FormatStyle::BS_Allman); 13265 CHECK_PARSE("BreakBeforeBraces: Whitesmiths", BreakBeforeBraces, 13266 FormatStyle::BS_Whitesmiths); 13267 CHECK_PARSE("BreakBeforeBraces: GNU", BreakBeforeBraces, FormatStyle::BS_GNU); 13268 CHECK_PARSE("BreakBeforeBraces: WebKit", BreakBeforeBraces, 13269 FormatStyle::BS_WebKit); 13270 CHECK_PARSE("BreakBeforeBraces: Custom", BreakBeforeBraces, 13271 FormatStyle::BS_Custom); 13272 13273 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Never; 13274 CHECK_PARSE("BraceWrapping:\n" 13275 " AfterControlStatement: MultiLine", 13276 BraceWrapping.AfterControlStatement, 13277 FormatStyle::BWACS_MultiLine); 13278 CHECK_PARSE("BraceWrapping:\n" 13279 " AfterControlStatement: Always", 13280 BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Always); 13281 CHECK_PARSE("BraceWrapping:\n" 13282 " AfterControlStatement: Never", 13283 BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Never); 13284 // For backward compatibility: 13285 CHECK_PARSE("BraceWrapping:\n" 13286 " AfterControlStatement: true", 13287 BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Always); 13288 CHECK_PARSE("BraceWrapping:\n" 13289 " AfterControlStatement: false", 13290 BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Never); 13291 13292 Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_All; 13293 CHECK_PARSE("AlwaysBreakAfterReturnType: None", AlwaysBreakAfterReturnType, 13294 FormatStyle::RTBS_None); 13295 CHECK_PARSE("AlwaysBreakAfterReturnType: All", AlwaysBreakAfterReturnType, 13296 FormatStyle::RTBS_All); 13297 CHECK_PARSE("AlwaysBreakAfterReturnType: TopLevel", 13298 AlwaysBreakAfterReturnType, FormatStyle::RTBS_TopLevel); 13299 CHECK_PARSE("AlwaysBreakAfterReturnType: AllDefinitions", 13300 AlwaysBreakAfterReturnType, FormatStyle::RTBS_AllDefinitions); 13301 CHECK_PARSE("AlwaysBreakAfterReturnType: TopLevelDefinitions", 13302 AlwaysBreakAfterReturnType, 13303 FormatStyle::RTBS_TopLevelDefinitions); 13304 13305 Style.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes; 13306 CHECK_PARSE("AlwaysBreakTemplateDeclarations: No", 13307 AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_No); 13308 CHECK_PARSE("AlwaysBreakTemplateDeclarations: MultiLine", 13309 AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_MultiLine); 13310 CHECK_PARSE("AlwaysBreakTemplateDeclarations: Yes", 13311 AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_Yes); 13312 CHECK_PARSE("AlwaysBreakTemplateDeclarations: false", 13313 AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_MultiLine); 13314 CHECK_PARSE("AlwaysBreakTemplateDeclarations: true", 13315 AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_Yes); 13316 13317 Style.AlwaysBreakAfterDefinitionReturnType = FormatStyle::DRTBS_All; 13318 CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: None", 13319 AlwaysBreakAfterDefinitionReturnType, FormatStyle::DRTBS_None); 13320 CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: All", 13321 AlwaysBreakAfterDefinitionReturnType, FormatStyle::DRTBS_All); 13322 CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: TopLevel", 13323 AlwaysBreakAfterDefinitionReturnType, 13324 FormatStyle::DRTBS_TopLevel); 13325 13326 Style.NamespaceIndentation = FormatStyle::NI_All; 13327 CHECK_PARSE("NamespaceIndentation: None", NamespaceIndentation, 13328 FormatStyle::NI_None); 13329 CHECK_PARSE("NamespaceIndentation: Inner", NamespaceIndentation, 13330 FormatStyle::NI_Inner); 13331 CHECK_PARSE("NamespaceIndentation: All", NamespaceIndentation, 13332 FormatStyle::NI_All); 13333 13334 Style.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_Always; 13335 CHECK_PARSE("AllowShortIfStatementsOnASingleLine: Never", 13336 AllowShortIfStatementsOnASingleLine, FormatStyle::SIS_Never); 13337 CHECK_PARSE("AllowShortIfStatementsOnASingleLine: WithoutElse", 13338 AllowShortIfStatementsOnASingleLine, 13339 FormatStyle::SIS_WithoutElse); 13340 CHECK_PARSE("AllowShortIfStatementsOnASingleLine: Always", 13341 AllowShortIfStatementsOnASingleLine, FormatStyle::SIS_Always); 13342 CHECK_PARSE("AllowShortIfStatementsOnASingleLine: false", 13343 AllowShortIfStatementsOnASingleLine, FormatStyle::SIS_Never); 13344 CHECK_PARSE("AllowShortIfStatementsOnASingleLine: true", 13345 AllowShortIfStatementsOnASingleLine, 13346 FormatStyle::SIS_WithoutElse); 13347 13348 // FIXME: This is required because parsing a configuration simply overwrites 13349 // the first N elements of the list instead of resetting it. 13350 Style.ForEachMacros.clear(); 13351 std::vector<std::string> BoostForeach; 13352 BoostForeach.push_back("BOOST_FOREACH"); 13353 CHECK_PARSE("ForEachMacros: [BOOST_FOREACH]", ForEachMacros, BoostForeach); 13354 std::vector<std::string> BoostAndQForeach; 13355 BoostAndQForeach.push_back("BOOST_FOREACH"); 13356 BoostAndQForeach.push_back("Q_FOREACH"); 13357 CHECK_PARSE("ForEachMacros: [BOOST_FOREACH, Q_FOREACH]", ForEachMacros, 13358 BoostAndQForeach); 13359 13360 Style.StatementMacros.clear(); 13361 CHECK_PARSE("StatementMacros: [QUNUSED]", StatementMacros, 13362 std::vector<std::string>{"QUNUSED"}); 13363 CHECK_PARSE("StatementMacros: [QUNUSED, QT_REQUIRE_VERSION]", StatementMacros, 13364 std::vector<std::string>({"QUNUSED", "QT_REQUIRE_VERSION"})); 13365 13366 Style.NamespaceMacros.clear(); 13367 CHECK_PARSE("NamespaceMacros: [TESTSUITE]", NamespaceMacros, 13368 std::vector<std::string>{"TESTSUITE"}); 13369 CHECK_PARSE("NamespaceMacros: [TESTSUITE, SUITE]", NamespaceMacros, 13370 std::vector<std::string>({"TESTSUITE", "SUITE"})); 13371 13372 Style.IncludeStyle.IncludeCategories.clear(); 13373 std::vector<tooling::IncludeStyle::IncludeCategory> ExpectedCategories = { 13374 {"abc/.*", 2, 0}, {".*", 1, 0}}; 13375 CHECK_PARSE("IncludeCategories:\n" 13376 " - Regex: abc/.*\n" 13377 " Priority: 2\n" 13378 " - Regex: .*\n" 13379 " Priority: 1", 13380 IncludeStyle.IncludeCategories, ExpectedCategories); 13381 CHECK_PARSE("IncludeIsMainRegex: 'abc$'", IncludeStyle.IncludeIsMainRegex, 13382 "abc$"); 13383 CHECK_PARSE("IncludeIsMainSourceRegex: 'abc$'", 13384 IncludeStyle.IncludeIsMainSourceRegex, "abc$"); 13385 13386 Style.RawStringFormats.clear(); 13387 std::vector<FormatStyle::RawStringFormat> ExpectedRawStringFormats = { 13388 { 13389 FormatStyle::LK_TextProto, 13390 {"pb", "proto"}, 13391 {"PARSE_TEXT_PROTO"}, 13392 /*CanonicalDelimiter=*/"", 13393 "llvm", 13394 }, 13395 { 13396 FormatStyle::LK_Cpp, 13397 {"cc", "cpp"}, 13398 {"C_CODEBLOCK", "CPPEVAL"}, 13399 /*CanonicalDelimiter=*/"cc", 13400 /*BasedOnStyle=*/"", 13401 }, 13402 }; 13403 13404 CHECK_PARSE("RawStringFormats:\n" 13405 " - Language: TextProto\n" 13406 " Delimiters:\n" 13407 " - 'pb'\n" 13408 " - 'proto'\n" 13409 " EnclosingFunctions:\n" 13410 " - 'PARSE_TEXT_PROTO'\n" 13411 " BasedOnStyle: llvm\n" 13412 " - Language: Cpp\n" 13413 " Delimiters:\n" 13414 " - 'cc'\n" 13415 " - 'cpp'\n" 13416 " EnclosingFunctions:\n" 13417 " - 'C_CODEBLOCK'\n" 13418 " - 'CPPEVAL'\n" 13419 " CanonicalDelimiter: 'cc'", 13420 RawStringFormats, ExpectedRawStringFormats); 13421 } 13422 13423 TEST_F(FormatTest, ParsesConfigurationWithLanguages) { 13424 FormatStyle Style = {}; 13425 Style.Language = FormatStyle::LK_Cpp; 13426 CHECK_PARSE("Language: Cpp\n" 13427 "IndentWidth: 12", 13428 IndentWidth, 12u); 13429 EXPECT_EQ(parseConfiguration("Language: JavaScript\n" 13430 "IndentWidth: 34", 13431 &Style), 13432 ParseError::Unsuitable); 13433 FormatStyle BinPackedTCS = {}; 13434 BinPackedTCS.Language = FormatStyle::LK_JavaScript; 13435 EXPECT_EQ(parseConfiguration("BinPackArguments: true\n" 13436 "InsertTrailingCommas: Wrapped", 13437 &BinPackedTCS), 13438 ParseError::BinPackTrailingCommaConflict); 13439 EXPECT_EQ(12u, Style.IndentWidth); 13440 CHECK_PARSE("IndentWidth: 56", IndentWidth, 56u); 13441 EXPECT_EQ(FormatStyle::LK_Cpp, Style.Language); 13442 13443 Style.Language = FormatStyle::LK_JavaScript; 13444 CHECK_PARSE("Language: JavaScript\n" 13445 "IndentWidth: 12", 13446 IndentWidth, 12u); 13447 CHECK_PARSE("IndentWidth: 23", IndentWidth, 23u); 13448 EXPECT_EQ(parseConfiguration("Language: Cpp\n" 13449 "IndentWidth: 34", 13450 &Style), 13451 ParseError::Unsuitable); 13452 EXPECT_EQ(23u, Style.IndentWidth); 13453 CHECK_PARSE("IndentWidth: 56", IndentWidth, 56u); 13454 EXPECT_EQ(FormatStyle::LK_JavaScript, Style.Language); 13455 13456 CHECK_PARSE("BasedOnStyle: LLVM\n" 13457 "IndentWidth: 67", 13458 IndentWidth, 67u); 13459 13460 CHECK_PARSE("---\n" 13461 "Language: JavaScript\n" 13462 "IndentWidth: 12\n" 13463 "---\n" 13464 "Language: Cpp\n" 13465 "IndentWidth: 34\n" 13466 "...\n", 13467 IndentWidth, 12u); 13468 13469 Style.Language = FormatStyle::LK_Cpp; 13470 CHECK_PARSE("---\n" 13471 "Language: JavaScript\n" 13472 "IndentWidth: 12\n" 13473 "---\n" 13474 "Language: Cpp\n" 13475 "IndentWidth: 34\n" 13476 "...\n", 13477 IndentWidth, 34u); 13478 CHECK_PARSE("---\n" 13479 "IndentWidth: 78\n" 13480 "---\n" 13481 "Language: JavaScript\n" 13482 "IndentWidth: 56\n" 13483 "...\n", 13484 IndentWidth, 78u); 13485 13486 Style.ColumnLimit = 123; 13487 Style.IndentWidth = 234; 13488 Style.BreakBeforeBraces = FormatStyle::BS_Linux; 13489 Style.TabWidth = 345; 13490 EXPECT_FALSE(parseConfiguration("---\n" 13491 "IndentWidth: 456\n" 13492 "BreakBeforeBraces: Allman\n" 13493 "---\n" 13494 "Language: JavaScript\n" 13495 "IndentWidth: 111\n" 13496 "TabWidth: 111\n" 13497 "---\n" 13498 "Language: Cpp\n" 13499 "BreakBeforeBraces: Stroustrup\n" 13500 "TabWidth: 789\n" 13501 "...\n", 13502 &Style)); 13503 EXPECT_EQ(123u, Style.ColumnLimit); 13504 EXPECT_EQ(456u, Style.IndentWidth); 13505 EXPECT_EQ(FormatStyle::BS_Stroustrup, Style.BreakBeforeBraces); 13506 EXPECT_EQ(789u, Style.TabWidth); 13507 13508 EXPECT_EQ(parseConfiguration("---\n" 13509 "Language: JavaScript\n" 13510 "IndentWidth: 56\n" 13511 "---\n" 13512 "IndentWidth: 78\n" 13513 "...\n", 13514 &Style), 13515 ParseError::Error); 13516 EXPECT_EQ(parseConfiguration("---\n" 13517 "Language: JavaScript\n" 13518 "IndentWidth: 56\n" 13519 "---\n" 13520 "Language: JavaScript\n" 13521 "IndentWidth: 78\n" 13522 "...\n", 13523 &Style), 13524 ParseError::Error); 13525 13526 EXPECT_EQ(FormatStyle::LK_Cpp, Style.Language); 13527 } 13528 13529 #undef CHECK_PARSE 13530 13531 TEST_F(FormatTest, UsesLanguageForBasedOnStyle) { 13532 FormatStyle Style = {}; 13533 Style.Language = FormatStyle::LK_JavaScript; 13534 Style.BreakBeforeTernaryOperators = true; 13535 EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Style).value()); 13536 EXPECT_FALSE(Style.BreakBeforeTernaryOperators); 13537 13538 Style.BreakBeforeTernaryOperators = true; 13539 EXPECT_EQ(0, parseConfiguration("---\n" 13540 "BasedOnStyle: Google\n" 13541 "---\n" 13542 "Language: JavaScript\n" 13543 "IndentWidth: 76\n" 13544 "...\n", 13545 &Style) 13546 .value()); 13547 EXPECT_FALSE(Style.BreakBeforeTernaryOperators); 13548 EXPECT_EQ(76u, Style.IndentWidth); 13549 EXPECT_EQ(FormatStyle::LK_JavaScript, Style.Language); 13550 } 13551 13552 TEST_F(FormatTest, ConfigurationRoundTripTest) { 13553 FormatStyle Style = getLLVMStyle(); 13554 std::string YAML = configurationAsText(Style); 13555 FormatStyle ParsedStyle = {}; 13556 ParsedStyle.Language = FormatStyle::LK_Cpp; 13557 EXPECT_EQ(0, parseConfiguration(YAML, &ParsedStyle).value()); 13558 EXPECT_EQ(Style, ParsedStyle); 13559 } 13560 13561 TEST_F(FormatTest, WorksFor8bitEncodings) { 13562 EXPECT_EQ("\"\xce\xe4\xed\xe0\xe6\xe4\xfb \xe2 \"\n" 13563 "\"\xf1\xf2\xf3\xe4\xb8\xed\xf3\xfe \"\n" 13564 "\"\xe7\xe8\xec\xed\xfe\xfe \"\n" 13565 "\"\xef\xee\xf0\xf3...\"", 13566 format("\"\xce\xe4\xed\xe0\xe6\xe4\xfb \xe2 " 13567 "\xf1\xf2\xf3\xe4\xb8\xed\xf3\xfe \xe7\xe8\xec\xed\xfe\xfe " 13568 "\xef\xee\xf0\xf3...\"", 13569 getLLVMStyleWithColumns(12))); 13570 } 13571 13572 TEST_F(FormatTest, HandlesUTF8BOM) { 13573 EXPECT_EQ("\xef\xbb\xbf", format("\xef\xbb\xbf")); 13574 EXPECT_EQ("\xef\xbb\xbf#include <iostream>", 13575 format("\xef\xbb\xbf#include <iostream>")); 13576 EXPECT_EQ("\xef\xbb\xbf\n#include <iostream>", 13577 format("\xef\xbb\xbf\n#include <iostream>")); 13578 } 13579 13580 // FIXME: Encode Cyrillic and CJK characters below to appease MS compilers. 13581 #if !defined(_MSC_VER) 13582 13583 TEST_F(FormatTest, CountsUTF8CharactersProperly) { 13584 verifyFormat("\"Однажды в студёную зимнюю пору...\"", 13585 getLLVMStyleWithColumns(35)); 13586 verifyFormat("\"一 二 三 四 五 六 七 八 九 十\"", 13587 getLLVMStyleWithColumns(31)); 13588 verifyFormat("// Однажды в студёную зимнюю пору...", 13589 getLLVMStyleWithColumns(36)); 13590 verifyFormat("// 一 二 三 四 五 六 七 八 九 十", getLLVMStyleWithColumns(32)); 13591 verifyFormat("/* Однажды в студёную зимнюю пору... */", 13592 getLLVMStyleWithColumns(39)); 13593 verifyFormat("/* 一 二 三 四 五 六 七 八 九 十 */", 13594 getLLVMStyleWithColumns(35)); 13595 } 13596 13597 TEST_F(FormatTest, SplitsUTF8Strings) { 13598 // Non-printable characters' width is currently considered to be the length in 13599 // bytes in UTF8. The characters can be displayed in very different manner 13600 // (zero-width, single width with a substitution glyph, expanded to their code 13601 // (e.g. "<8d>"), so there's no single correct way to handle them. 13602 EXPECT_EQ("\"aaaaÄ\"\n" 13603 "\"\xc2\x8d\";", 13604 format("\"aaaaÄ\xc2\x8d\";", getLLVMStyleWithColumns(10))); 13605 EXPECT_EQ("\"aaaaaaaÄ\"\n" 13606 "\"\xc2\x8d\";", 13607 format("\"aaaaaaaÄ\xc2\x8d\";", getLLVMStyleWithColumns(10))); 13608 EXPECT_EQ("\"Однажды, в \"\n" 13609 "\"студёную \"\n" 13610 "\"зимнюю \"\n" 13611 "\"пору,\"", 13612 format("\"Однажды, в студёную зимнюю пору,\"", 13613 getLLVMStyleWithColumns(13))); 13614 EXPECT_EQ( 13615 "\"一 二 三 \"\n" 13616 "\"四 五六 \"\n" 13617 "\"七 八 九 \"\n" 13618 "\"十\"", 13619 format("\"一 二 三 四 五六 七 八 九 十\"", getLLVMStyleWithColumns(11))); 13620 EXPECT_EQ("\"一\t\"\n" 13621 "\"二 \t\"\n" 13622 "\"三 四 \"\n" 13623 "\"五\t\"\n" 13624 "\"六 \t\"\n" 13625 "\"七 \"\n" 13626 "\"八九十\tqq\"", 13627 format("\"一\t二 \t三 四 五\t六 \t七 八九十\tqq\"", 13628 getLLVMStyleWithColumns(11))); 13629 13630 // UTF8 character in an escape sequence. 13631 EXPECT_EQ("\"aaaaaa\"\n" 13632 "\"\\\xC2\x8D\"", 13633 format("\"aaaaaa\\\xC2\x8D\"", getLLVMStyleWithColumns(10))); 13634 } 13635 13636 TEST_F(FormatTest, HandlesDoubleWidthCharsInMultiLineStrings) { 13637 EXPECT_EQ("const char *sssss =\n" 13638 " \"一二三四五六七八\\\n" 13639 " 九 十\";", 13640 format("const char *sssss = \"一二三四五六七八\\\n" 13641 " 九 十\";", 13642 getLLVMStyleWithColumns(30))); 13643 } 13644 13645 TEST_F(FormatTest, SplitsUTF8LineComments) { 13646 EXPECT_EQ("// aaaaÄ\xc2\x8d", 13647 format("// aaaaÄ\xc2\x8d", getLLVMStyleWithColumns(10))); 13648 EXPECT_EQ("// Я из лесу\n" 13649 "// вышел; был\n" 13650 "// сильный\n" 13651 "// мороз.", 13652 format("// Я из лесу вышел; был сильный мороз.", 13653 getLLVMStyleWithColumns(13))); 13654 EXPECT_EQ("// 一二三\n" 13655 "// 四五六七\n" 13656 "// 八 九\n" 13657 "// 十", 13658 format("// 一二三 四五六七 八 九 十", getLLVMStyleWithColumns(9))); 13659 } 13660 13661 TEST_F(FormatTest, SplitsUTF8BlockComments) { 13662 EXPECT_EQ("/* Гляжу,\n" 13663 " * поднимается\n" 13664 " * медленно в\n" 13665 " * гору\n" 13666 " * Лошадка,\n" 13667 " * везущая\n" 13668 " * хворосту\n" 13669 " * воз. */", 13670 format("/* Гляжу, поднимается медленно в гору\n" 13671 " * Лошадка, везущая хворосту воз. */", 13672 getLLVMStyleWithColumns(13))); 13673 EXPECT_EQ( 13674 "/* 一二三\n" 13675 " * 四五六七\n" 13676 " * 八 九\n" 13677 " * 十 */", 13678 format("/* 一二三 四五六七 八 九 十 */", getLLVMStyleWithColumns(9))); 13679 EXPECT_EQ("/* \n" 13680 " * \n" 13681 " * - */", 13682 format("/* - */", getLLVMStyleWithColumns(12))); 13683 } 13684 13685 #endif // _MSC_VER 13686 13687 TEST_F(FormatTest, ConstructorInitializerIndentWidth) { 13688 FormatStyle Style = getLLVMStyle(); 13689 13690 Style.ConstructorInitializerIndentWidth = 4; 13691 verifyFormat( 13692 "SomeClass::Constructor()\n" 13693 " : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 13694 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", 13695 Style); 13696 13697 Style.ConstructorInitializerIndentWidth = 2; 13698 verifyFormat( 13699 "SomeClass::Constructor()\n" 13700 " : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 13701 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", 13702 Style); 13703 13704 Style.ConstructorInitializerIndentWidth = 0; 13705 verifyFormat( 13706 "SomeClass::Constructor()\n" 13707 ": aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 13708 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", 13709 Style); 13710 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 13711 verifyFormat( 13712 "SomeLongTemplateVariableName<\n" 13713 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>", 13714 Style); 13715 verifyFormat("bool smaller = 1 < " 13716 "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n" 13717 " " 13718 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 13719 Style); 13720 13721 Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon; 13722 verifyFormat("SomeClass::Constructor() :\n" 13723 "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa),\n" 13724 "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa) {}", 13725 Style); 13726 } 13727 13728 TEST_F(FormatTest, BreakConstructorInitializersBeforeComma) { 13729 FormatStyle Style = getLLVMStyle(); 13730 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma; 13731 Style.ConstructorInitializerIndentWidth = 4; 13732 verifyFormat("SomeClass::Constructor()\n" 13733 " : a(a)\n" 13734 " , b(b)\n" 13735 " , c(c) {}", 13736 Style); 13737 verifyFormat("SomeClass::Constructor()\n" 13738 " : a(a) {}", 13739 Style); 13740 13741 Style.ColumnLimit = 0; 13742 verifyFormat("SomeClass::Constructor()\n" 13743 " : a(a) {}", 13744 Style); 13745 verifyFormat("SomeClass::Constructor() noexcept\n" 13746 " : a(a) {}", 13747 Style); 13748 verifyFormat("SomeClass::Constructor()\n" 13749 " : a(a)\n" 13750 " , b(b)\n" 13751 " , c(c) {}", 13752 Style); 13753 verifyFormat("SomeClass::Constructor()\n" 13754 " : a(a) {\n" 13755 " foo();\n" 13756 " bar();\n" 13757 "}", 13758 Style); 13759 13760 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 13761 verifyFormat("SomeClass::Constructor()\n" 13762 " : a(a)\n" 13763 " , b(b)\n" 13764 " , c(c) {\n}", 13765 Style); 13766 verifyFormat("SomeClass::Constructor()\n" 13767 " : a(a) {\n}", 13768 Style); 13769 13770 Style.ColumnLimit = 80; 13771 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All; 13772 Style.ConstructorInitializerIndentWidth = 2; 13773 verifyFormat("SomeClass::Constructor()\n" 13774 " : a(a)\n" 13775 " , b(b)\n" 13776 " , c(c) {}", 13777 Style); 13778 13779 Style.ConstructorInitializerIndentWidth = 0; 13780 verifyFormat("SomeClass::Constructor()\n" 13781 ": a(a)\n" 13782 ", b(b)\n" 13783 ", c(c) {}", 13784 Style); 13785 13786 Style.ConstructorInitializerAllOnOneLineOrOnePerLine = true; 13787 Style.ConstructorInitializerIndentWidth = 4; 13788 verifyFormat("SomeClass::Constructor() : aaaaaaaa(aaaaaaaa) {}", Style); 13789 verifyFormat( 13790 "SomeClass::Constructor() : aaaaa(aaaaa), aaaaa(aaaaa), aaaaa(aaaaa)\n", 13791 Style); 13792 verifyFormat( 13793 "SomeClass::Constructor()\n" 13794 " : aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaa) {}", 13795 Style); 13796 Style.ConstructorInitializerIndentWidth = 4; 13797 Style.ColumnLimit = 60; 13798 verifyFormat("SomeClass::Constructor()\n" 13799 " : aaaaaaaa(aaaaaaaa)\n" 13800 " , aaaaaaaa(aaaaaaaa)\n" 13801 " , aaaaaaaa(aaaaaaaa) {}", 13802 Style); 13803 } 13804 13805 TEST_F(FormatTest, Destructors) { 13806 verifyFormat("void F(int &i) { i.~int(); }"); 13807 verifyFormat("void F(int &i) { i->~int(); }"); 13808 } 13809 13810 TEST_F(FormatTest, FormatsWithWebKitStyle) { 13811 FormatStyle Style = getWebKitStyle(); 13812 13813 // Don't indent in outer namespaces. 13814 verifyFormat("namespace outer {\n" 13815 "int i;\n" 13816 "namespace inner {\n" 13817 " int i;\n" 13818 "} // namespace inner\n" 13819 "} // namespace outer\n" 13820 "namespace other_outer {\n" 13821 "int i;\n" 13822 "}", 13823 Style); 13824 13825 // Don't indent case labels. 13826 verifyFormat("switch (variable) {\n" 13827 "case 1:\n" 13828 "case 2:\n" 13829 " doSomething();\n" 13830 " break;\n" 13831 "default:\n" 13832 " ++variable;\n" 13833 "}", 13834 Style); 13835 13836 // Wrap before binary operators. 13837 EXPECT_EQ("void f()\n" 13838 "{\n" 13839 " if (aaaaaaaaaaaaaaaa\n" 13840 " && bbbbbbbbbbbbbbbbbbbbbbbb\n" 13841 " && (cccccccccccccccccccccccccc || dddddddddddddddddddd))\n" 13842 " return;\n" 13843 "}", 13844 format("void f() {\n" 13845 "if (aaaaaaaaaaaaaaaa\n" 13846 "&& bbbbbbbbbbbbbbbbbbbbbbbb\n" 13847 "&& (cccccccccccccccccccccccccc || dddddddddddddddddddd))\n" 13848 "return;\n" 13849 "}", 13850 Style)); 13851 13852 // Allow functions on a single line. 13853 verifyFormat("void f() { return; }", Style); 13854 13855 // Allow empty blocks on a single line and insert a space in empty blocks. 13856 EXPECT_EQ("void f() { }", format("void f() {}", Style)); 13857 EXPECT_EQ("while (true) { }", format("while (true) {}", Style)); 13858 // However, don't merge non-empty short loops. 13859 EXPECT_EQ("while (true) {\n" 13860 " continue;\n" 13861 "}", 13862 format("while (true) { continue; }", Style)); 13863 13864 // Constructor initializers are formatted one per line with the "," on the 13865 // new line. 13866 verifyFormat("Constructor()\n" 13867 " : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 13868 " , aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaa, // break\n" 13869 " aaaaaaaaaaaaaa)\n" 13870 " , aaaaaaaaaaaaaaaaaaaaaaa()\n" 13871 "{\n" 13872 "}", 13873 Style); 13874 verifyFormat("SomeClass::Constructor()\n" 13875 " : a(a)\n" 13876 "{\n" 13877 "}", 13878 Style); 13879 EXPECT_EQ("SomeClass::Constructor()\n" 13880 " : a(a)\n" 13881 "{\n" 13882 "}", 13883 format("SomeClass::Constructor():a(a){}", Style)); 13884 verifyFormat("SomeClass::Constructor()\n" 13885 " : a(a)\n" 13886 " , b(b)\n" 13887 " , c(c)\n" 13888 "{\n" 13889 "}", 13890 Style); 13891 verifyFormat("SomeClass::Constructor()\n" 13892 " : a(a)\n" 13893 "{\n" 13894 " foo();\n" 13895 " bar();\n" 13896 "}", 13897 Style); 13898 13899 // Access specifiers should be aligned left. 13900 verifyFormat("class C {\n" 13901 "public:\n" 13902 " int i;\n" 13903 "};", 13904 Style); 13905 13906 // Do not align comments. 13907 verifyFormat("int a; // Do not\n" 13908 "double b; // align comments.", 13909 Style); 13910 13911 // Do not align operands. 13912 EXPECT_EQ("ASSERT(aaaa\n" 13913 " || bbbb);", 13914 format("ASSERT ( aaaa\n||bbbb);", Style)); 13915 13916 // Accept input's line breaks. 13917 EXPECT_EQ("if (aaaaaaaaaaaaaaa\n" 13918 " || bbbbbbbbbbbbbbb) {\n" 13919 " i++;\n" 13920 "}", 13921 format("if (aaaaaaaaaaaaaaa\n" 13922 "|| bbbbbbbbbbbbbbb) { i++; }", 13923 Style)); 13924 EXPECT_EQ("if (aaaaaaaaaaaaaaa || bbbbbbbbbbbbbbb) {\n" 13925 " i++;\n" 13926 "}", 13927 format("if (aaaaaaaaaaaaaaa || bbbbbbbbbbbbbbb) { i++; }", Style)); 13928 13929 // Don't automatically break all macro definitions (llvm.org/PR17842). 13930 verifyFormat("#define aNumber 10", Style); 13931 // However, generally keep the line breaks that the user authored. 13932 EXPECT_EQ("#define aNumber \\\n" 13933 " 10", 13934 format("#define aNumber \\\n" 13935 " 10", 13936 Style)); 13937 13938 // Keep empty and one-element array literals on a single line. 13939 EXPECT_EQ("NSArray* a = [[NSArray alloc] initWithArray:@[]\n" 13940 " copyItems:YES];", 13941 format("NSArray*a=[[NSArray alloc] initWithArray:@[]\n" 13942 "copyItems:YES];", 13943 Style)); 13944 EXPECT_EQ("NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\" ]\n" 13945 " copyItems:YES];", 13946 format("NSArray*a=[[NSArray alloc]initWithArray:@[ @\"a\" ]\n" 13947 " copyItems:YES];", 13948 Style)); 13949 // FIXME: This does not seem right, there should be more indentation before 13950 // the array literal's entries. Nested blocks have the same problem. 13951 EXPECT_EQ("NSArray* a = [[NSArray alloc] initWithArray:@[\n" 13952 " @\"a\",\n" 13953 " @\"a\"\n" 13954 "]\n" 13955 " copyItems:YES];", 13956 format("NSArray* a = [[NSArray alloc] initWithArray:@[\n" 13957 " @\"a\",\n" 13958 " @\"a\"\n" 13959 " ]\n" 13960 " copyItems:YES];", 13961 Style)); 13962 EXPECT_EQ( 13963 "NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\", @\"a\" ]\n" 13964 " copyItems:YES];", 13965 format("NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\", @\"a\" ]\n" 13966 " copyItems:YES];", 13967 Style)); 13968 13969 verifyFormat("[self.a b:c c:d];", Style); 13970 EXPECT_EQ("[self.a b:c\n" 13971 " c:d];", 13972 format("[self.a b:c\n" 13973 "c:d];", 13974 Style)); 13975 } 13976 13977 TEST_F(FormatTest, FormatsLambdas) { 13978 verifyFormat("int c = [b]() mutable { return [&b] { return b++; }(); }();\n"); 13979 verifyFormat( 13980 "int c = [b]() mutable noexcept { return [&b] { return b++; }(); }();\n"); 13981 verifyFormat("int c = [&] { [=] { return b++; }(); }();\n"); 13982 verifyFormat("int c = [&, &a, a] { [=, c, &d] { return b++; }(); }();\n"); 13983 verifyFormat("int c = [&a, &a, a] { [=, a, b, &c] { return b++; }(); }();\n"); 13984 verifyFormat("auto c = {[&a, &a, a] { [=, a, b, &c] { return b++; }(); }}\n"); 13985 verifyFormat("auto c = {[&a, &a, a] { [=, a, b, &c] {}(); }}\n"); 13986 verifyFormat("auto c = [a = [b = 42] {}] {};\n"); 13987 verifyFormat("auto c = [a = &i + 10, b = [] {}] {};\n"); 13988 verifyFormat("int x = f(*+[] {});"); 13989 verifyFormat("void f() {\n" 13990 " other(x.begin(), x.end(), [&](int, int) { return 1; });\n" 13991 "}\n"); 13992 verifyFormat("void f() {\n" 13993 " other(x.begin(), //\n" 13994 " x.end(), //\n" 13995 " [&](int, int) { return 1; });\n" 13996 "}\n"); 13997 verifyFormat("void f() {\n" 13998 " other.other.other.other.other(\n" 13999 " x.begin(), x.end(),\n" 14000 " [something, rather](int, int, int, int, int, int, int) { " 14001 "return 1; });\n" 14002 "}\n"); 14003 verifyFormat( 14004 "void f() {\n" 14005 " other.other.other.other.other(\n" 14006 " x.begin(), x.end(),\n" 14007 " [something, rather](int, int, int, int, int, int, int) {\n" 14008 " //\n" 14009 " });\n" 14010 "}\n"); 14011 verifyFormat("SomeFunction([]() { // A cool function...\n" 14012 " return 43;\n" 14013 "});"); 14014 EXPECT_EQ("SomeFunction([]() {\n" 14015 "#define A a\n" 14016 " return 43;\n" 14017 "});", 14018 format("SomeFunction([](){\n" 14019 "#define A a\n" 14020 "return 43;\n" 14021 "});")); 14022 verifyFormat("void f() {\n" 14023 " SomeFunction([](decltype(x), A *a) {});\n" 14024 "}"); 14025 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 14026 " [](const aaaaaaaaaa &a) { return a; });"); 14027 verifyFormat("string abc = SomeFunction(aaaaaaaaaaaaa, aaaaa, []() {\n" 14028 " SomeOtherFunctioooooooooooooooooooooooooon();\n" 14029 "});"); 14030 verifyFormat("Constructor()\n" 14031 " : Field([] { // comment\n" 14032 " int i;\n" 14033 " }) {}"); 14034 verifyFormat("auto my_lambda = [](const string &some_parameter) {\n" 14035 " return some_parameter.size();\n" 14036 "};"); 14037 verifyFormat("std::function<std::string(const std::string &)> my_lambda =\n" 14038 " [](const string &s) { return s; };"); 14039 verifyFormat("int i = aaaaaa ? 1 //\n" 14040 " : [] {\n" 14041 " return 2; //\n" 14042 " }();"); 14043 verifyFormat("llvm::errs() << \"number of twos is \"\n" 14044 " << std::count_if(v.begin(), v.end(), [](int x) {\n" 14045 " return x == 2; // force break\n" 14046 " });"); 14047 verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 14048 " [=](int iiiiiiiiiiii) {\n" 14049 " return aaaaaaaaaaaaaaaaaaaaaaa !=\n" 14050 " aaaaaaaaaaaaaaaaaaaaaaa;\n" 14051 " });", 14052 getLLVMStyleWithColumns(60)); 14053 verifyFormat("SomeFunction({[&] {\n" 14054 " // comment\n" 14055 " },\n" 14056 " [&] {\n" 14057 " // comment\n" 14058 " }});"); 14059 verifyFormat("SomeFunction({[&] {\n" 14060 " // comment\n" 14061 "}});"); 14062 verifyFormat( 14063 "virtual aaaaaaaaaaaaaaaa(\n" 14064 " std::function<bool()> bbbbbbbbbbbb = [&]() { return true; },\n" 14065 " aaaaa aaaaaaaaa);"); 14066 14067 // Lambdas with return types. 14068 verifyFormat("int c = []() -> int { return 2; }();\n"); 14069 verifyFormat("int c = []() -> int * { return 2; }();\n"); 14070 verifyFormat("int c = []() -> vector<int> { return {2}; }();\n"); 14071 verifyFormat("Foo([]() -> std::vector<int> { return {2}; }());"); 14072 verifyGoogleFormat("auto a = [&b, c](D* d) -> D* {};"); 14073 verifyGoogleFormat("auto a = [&b, c](D* d) -> pair<D*, D*> {};"); 14074 verifyGoogleFormat("auto a = [&b, c](D* d) -> D& {};"); 14075 verifyGoogleFormat("auto a = [&b, c](D* d) -> const D* {};"); 14076 verifyFormat("[a, a]() -> a<1> {};"); 14077 verifyFormat("[]() -> foo<5 + 2> { return {}; };"); 14078 verifyFormat("[]() -> foo<5 - 2> { return {}; };"); 14079 verifyFormat("[]() -> foo<5 / 2> { return {}; };"); 14080 verifyFormat("[]() -> foo<5 * 2> { return {}; };"); 14081 verifyFormat("[]() -> foo<5 % 2> { return {}; };"); 14082 verifyFormat("[]() -> foo<5 << 2> { return {}; };"); 14083 verifyFormat("[]() -> foo<!5> { return {}; };"); 14084 verifyFormat("[]() -> foo<~5> { return {}; };"); 14085 verifyFormat("[]() -> foo<5 | 2> { return {}; };"); 14086 verifyFormat("[]() -> foo<5 || 2> { return {}; };"); 14087 verifyFormat("[]() -> foo<5 & 2> { return {}; };"); 14088 verifyFormat("[]() -> foo<5 && 2> { return {}; };"); 14089 verifyFormat("[]() -> foo<5 == 2> { return {}; };"); 14090 verifyFormat("[]() -> foo<5 != 2> { return {}; };"); 14091 verifyFormat("[]() -> foo<5 >= 2> { return {}; };"); 14092 verifyFormat("[]() -> foo<5 <= 2> { return {}; };"); 14093 verifyFormat("[]() -> foo<5 < 2> { return {}; };"); 14094 verifyFormat("[]() -> foo<2 ? 1 : 0> { return {}; };"); 14095 verifyFormat("namespace bar {\n" 14096 "// broken:\n" 14097 "auto foo{[]() -> foo<5 + 2> { return {}; }};\n" 14098 "} // namespace bar"); 14099 verifyFormat("namespace bar {\n" 14100 "// broken:\n" 14101 "auto foo{[]() -> foo<5 - 2> { return {}; }};\n" 14102 "} // namespace bar"); 14103 verifyFormat("namespace bar {\n" 14104 "// broken:\n" 14105 "auto foo{[]() -> foo<5 / 2> { return {}; }};\n" 14106 "} // namespace bar"); 14107 verifyFormat("namespace bar {\n" 14108 "// broken:\n" 14109 "auto foo{[]() -> foo<5 * 2> { return {}; }};\n" 14110 "} // namespace bar"); 14111 verifyFormat("namespace bar {\n" 14112 "// broken:\n" 14113 "auto foo{[]() -> foo<5 % 2> { return {}; }};\n" 14114 "} // namespace bar"); 14115 verifyFormat("namespace bar {\n" 14116 "// broken:\n" 14117 "auto foo{[]() -> foo<5 << 2> { return {}; }};\n" 14118 "} // namespace bar"); 14119 verifyFormat("namespace bar {\n" 14120 "// broken:\n" 14121 "auto foo{[]() -> foo<!5> { return {}; }};\n" 14122 "} // namespace bar"); 14123 verifyFormat("namespace bar {\n" 14124 "// broken:\n" 14125 "auto foo{[]() -> foo<~5> { return {}; }};\n" 14126 "} // namespace bar"); 14127 verifyFormat("namespace bar {\n" 14128 "// broken:\n" 14129 "auto foo{[]() -> foo<5 | 2> { return {}; }};\n" 14130 "} // namespace bar"); 14131 verifyFormat("namespace bar {\n" 14132 "// broken:\n" 14133 "auto foo{[]() -> foo<5 || 2> { return {}; }};\n" 14134 "} // namespace bar"); 14135 verifyFormat("namespace bar {\n" 14136 "// broken:\n" 14137 "auto foo{[]() -> foo<5 & 2> { return {}; }};\n" 14138 "} // namespace bar"); 14139 verifyFormat("namespace bar {\n" 14140 "// broken:\n" 14141 "auto foo{[]() -> foo<5 && 2> { return {}; }};\n" 14142 "} // namespace bar"); 14143 verifyFormat("namespace bar {\n" 14144 "// broken:\n" 14145 "auto foo{[]() -> foo<5 == 2> { return {}; }};\n" 14146 "} // namespace bar"); 14147 verifyFormat("namespace bar {\n" 14148 "// broken:\n" 14149 "auto foo{[]() -> foo<5 != 2> { return {}; }};\n" 14150 "} // namespace bar"); 14151 verifyFormat("namespace bar {\n" 14152 "// broken:\n" 14153 "auto foo{[]() -> foo<5 >= 2> { return {}; }};\n" 14154 "} // namespace bar"); 14155 verifyFormat("namespace bar {\n" 14156 "// broken:\n" 14157 "auto foo{[]() -> foo<5 <= 2> { return {}; }};\n" 14158 "} // namespace bar"); 14159 verifyFormat("namespace bar {\n" 14160 "// broken:\n" 14161 "auto foo{[]() -> foo<5 < 2> { return {}; }};\n" 14162 "} // namespace bar"); 14163 verifyFormat("namespace bar {\n" 14164 "// broken:\n" 14165 "auto foo{[]() -> foo<2 ? 1 : 0> { return {}; }};\n" 14166 "} // namespace bar"); 14167 verifyFormat("[]() -> a<1> {};"); 14168 verifyFormat("[]() -> a<1> { ; };"); 14169 verifyFormat("[]() -> a<1> { ; }();"); 14170 verifyFormat("[a, a]() -> a<true> {};"); 14171 verifyFormat("[]() -> a<true> {};"); 14172 verifyFormat("[]() -> a<true> { ; };"); 14173 verifyFormat("[]() -> a<true> { ; }();"); 14174 verifyFormat("[a, a]() -> a<false> {};"); 14175 verifyFormat("[]() -> a<false> {};"); 14176 verifyFormat("[]() -> a<false> { ; };"); 14177 verifyFormat("[]() -> a<false> { ; }();"); 14178 verifyFormat("auto foo{[]() -> foo<false> { ; }};"); 14179 verifyFormat("namespace bar {\n" 14180 "auto foo{[]() -> foo<false> { ; }};\n" 14181 "} // namespace bar"); 14182 verifyFormat("auto aaaaaaaa = [](int i, // break for some reason\n" 14183 " int j) -> int {\n" 14184 " return ffffffffffffffffffffffffffffffffffffffffffff(i * j);\n" 14185 "};"); 14186 verifyFormat( 14187 "aaaaaaaaaaaaaaaaaaaaaa(\n" 14188 " [](aaaaaaaaaaaaaaaaaaaaaaaaaaa &aaa) -> aaaaaaaaaaaaaaaa {\n" 14189 " return aaaaaaaaaaaaaaaaa;\n" 14190 " });", 14191 getLLVMStyleWithColumns(70)); 14192 verifyFormat("[]() //\n" 14193 " -> int {\n" 14194 " return 1; //\n" 14195 "};"); 14196 verifyFormat("[]() -> Void<T...> {};"); 14197 verifyFormat("[a, b]() -> Tuple<T...> { return {}; };"); 14198 14199 // Lambdas with explicit template argument lists. 14200 verifyFormat( 14201 "auto L = []<template <typename> class T, class U>(T<U> &&a) {};\n"); 14202 14203 // Multiple lambdas in the same parentheses change indentation rules. These 14204 // lambdas are forced to start on new lines. 14205 verifyFormat("SomeFunction(\n" 14206 " []() {\n" 14207 " //\n" 14208 " },\n" 14209 " []() {\n" 14210 " //\n" 14211 " });"); 14212 14213 // A lambda passed as arg0 is always pushed to the next line. 14214 verifyFormat("SomeFunction(\n" 14215 " [this] {\n" 14216 " //\n" 14217 " },\n" 14218 " 1);\n"); 14219 14220 // A multi-line lambda passed as arg1 forces arg0 to be pushed out, just like 14221 // the arg0 case above. 14222 auto Style = getGoogleStyle(); 14223 Style.BinPackArguments = false; 14224 verifyFormat("SomeFunction(\n" 14225 " a,\n" 14226 " [this] {\n" 14227 " //\n" 14228 " },\n" 14229 " b);\n", 14230 Style); 14231 verifyFormat("SomeFunction(\n" 14232 " a,\n" 14233 " [this] {\n" 14234 " //\n" 14235 " },\n" 14236 " b);\n"); 14237 14238 // A lambda with a very long line forces arg0 to be pushed out irrespective of 14239 // the BinPackArguments value (as long as the code is wide enough). 14240 verifyFormat( 14241 "something->SomeFunction(\n" 14242 " a,\n" 14243 " [this] {\n" 14244 " " 14245 "D0000000000000000000000000000000000000000000000000000000000001();\n" 14246 " },\n" 14247 " b);\n"); 14248 14249 // A multi-line lambda is pulled up as long as the introducer fits on the 14250 // previous line and there are no further args. 14251 verifyFormat("function(1, [this, that] {\n" 14252 " //\n" 14253 "});\n"); 14254 verifyFormat("function([this, that] {\n" 14255 " //\n" 14256 "});\n"); 14257 // FIXME: this format is not ideal and we should consider forcing the first 14258 // arg onto its own line. 14259 verifyFormat("function(a, b, c, //\n" 14260 " d, [this, that] {\n" 14261 " //\n" 14262 " });\n"); 14263 14264 // Multiple lambdas are treated correctly even when there is a short arg0. 14265 verifyFormat("SomeFunction(\n" 14266 " 1,\n" 14267 " [this] {\n" 14268 " //\n" 14269 " },\n" 14270 " [this] {\n" 14271 " //\n" 14272 " },\n" 14273 " 1);\n"); 14274 14275 // More complex introducers. 14276 verifyFormat("return [i, args...] {};"); 14277 14278 // Not lambdas. 14279 verifyFormat("constexpr char hello[]{\"hello\"};"); 14280 verifyFormat("double &operator[](int i) { return 0; }\n" 14281 "int i;"); 14282 verifyFormat("std::unique_ptr<int[]> foo() {}"); 14283 verifyFormat("int i = a[a][a]->f();"); 14284 verifyFormat("int i = (*b)[a]->f();"); 14285 14286 // Other corner cases. 14287 verifyFormat("void f() {\n" 14288 " bar([]() {} // Did not respect SpacesBeforeTrailingComments\n" 14289 " );\n" 14290 "}"); 14291 14292 // Lambdas created through weird macros. 14293 verifyFormat("void f() {\n" 14294 " MACRO((const AA &a) { return 1; });\n" 14295 " MACRO((AA &a) { return 1; });\n" 14296 "}"); 14297 14298 verifyFormat("if (blah_blah(whatever, whatever, [] {\n" 14299 " doo_dah();\n" 14300 " doo_dah();\n" 14301 " })) {\n" 14302 "}"); 14303 verifyFormat("if constexpr (blah_blah(whatever, whatever, [] {\n" 14304 " doo_dah();\n" 14305 " doo_dah();\n" 14306 " })) {\n" 14307 "}"); 14308 verifyFormat("if CONSTEXPR (blah_blah(whatever, whatever, [] {\n" 14309 " doo_dah();\n" 14310 " doo_dah();\n" 14311 " })) {\n" 14312 "}"); 14313 verifyFormat("auto lambda = []() {\n" 14314 " int a = 2\n" 14315 "#if A\n" 14316 " + 2\n" 14317 "#endif\n" 14318 " ;\n" 14319 "};"); 14320 14321 // Lambdas with complex multiline introducers. 14322 verifyFormat( 14323 "aaaaaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 14324 " [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]()\n" 14325 " -> ::std::unordered_set<\n" 14326 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa> {\n" 14327 " //\n" 14328 " });"); 14329 14330 FormatStyle DoNotMerge = getLLVMStyle(); 14331 DoNotMerge.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None; 14332 verifyFormat("auto c = []() {\n" 14333 " return b;\n" 14334 "};", 14335 "auto c = []() { return b; };", DoNotMerge); 14336 verifyFormat("auto c = []() {\n" 14337 "};", 14338 " auto c = []() {};", DoNotMerge); 14339 14340 FormatStyle MergeEmptyOnly = getLLVMStyle(); 14341 MergeEmptyOnly.AllowShortLambdasOnASingleLine = FormatStyle::SLS_Empty; 14342 verifyFormat("auto c = []() {\n" 14343 " return b;\n" 14344 "};", 14345 "auto c = []() {\n" 14346 " return b;\n" 14347 " };", 14348 MergeEmptyOnly); 14349 verifyFormat("auto c = []() {};", 14350 "auto c = []() {\n" 14351 "};", 14352 MergeEmptyOnly); 14353 14354 FormatStyle MergeInline = getLLVMStyle(); 14355 MergeInline.AllowShortLambdasOnASingleLine = FormatStyle::SLS_Inline; 14356 verifyFormat("auto c = []() {\n" 14357 " return b;\n" 14358 "};", 14359 "auto c = []() { return b; };", MergeInline); 14360 verifyFormat("function([]() { return b; })", "function([]() { return b; })", 14361 MergeInline); 14362 verifyFormat("function([]() { return b; }, a)", 14363 "function([]() { return b; }, a)", MergeInline); 14364 verifyFormat("function(a, []() { return b; })", 14365 "function(a, []() { return b; })", MergeInline); 14366 14367 // Check option "BraceWrapping.BeforeLambdaBody" and different state of 14368 // AllowShortLambdasOnASingleLine 14369 FormatStyle LLVMWithBeforeLambdaBody = getLLVMStyle(); 14370 LLVMWithBeforeLambdaBody.BreakBeforeBraces = FormatStyle::BS_Custom; 14371 LLVMWithBeforeLambdaBody.BraceWrapping.BeforeLambdaBody = true; 14372 LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine = 14373 FormatStyle::ShortLambdaStyle::SLS_None; 14374 verifyFormat("FctWithOneNestedLambdaInline_SLS_None(\n" 14375 " []()\n" 14376 " {\n" 14377 " return 17;\n" 14378 " });", 14379 LLVMWithBeforeLambdaBody); 14380 verifyFormat("FctWithOneNestedLambdaEmpty_SLS_None(\n" 14381 " []()\n" 14382 " {\n" 14383 " });", 14384 LLVMWithBeforeLambdaBody); 14385 verifyFormat("auto fct_SLS_None = []()\n" 14386 "{\n" 14387 " return 17;\n" 14388 "};", 14389 LLVMWithBeforeLambdaBody); 14390 verifyFormat("TwoNestedLambdas_SLS_None(\n" 14391 " []()\n" 14392 " {\n" 14393 " return Call(\n" 14394 " []()\n" 14395 " {\n" 14396 " return 17;\n" 14397 " });\n" 14398 " });", 14399 LLVMWithBeforeLambdaBody); 14400 verifyFormat("void Fct()\n" 14401 "{\n" 14402 " return {[]()\n" 14403 " {\n" 14404 " return 17;\n" 14405 " }};\n" 14406 "}", 14407 LLVMWithBeforeLambdaBody); 14408 14409 LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine = 14410 FormatStyle::ShortLambdaStyle::SLS_Empty; 14411 verifyFormat("FctWithOneNestedLambdaInline_SLS_Empty(\n" 14412 " []()\n" 14413 " {\n" 14414 " return 17;\n" 14415 " });", 14416 LLVMWithBeforeLambdaBody); 14417 verifyFormat("FctWithOneNestedLambdaEmpty_SLS_Empty([]() {});", 14418 LLVMWithBeforeLambdaBody); 14419 verifyFormat("FctWithOneNestedLambdaEmptyInsideAVeryVeryVeryVeryVeryVeryVeryL" 14420 "ongFunctionName_SLS_Empty(\n" 14421 " []() {});", 14422 LLVMWithBeforeLambdaBody); 14423 verifyFormat("FctWithMultipleParams_SLS_Empty(A, B,\n" 14424 " []()\n" 14425 " {\n" 14426 " return 17;\n" 14427 " });", 14428 LLVMWithBeforeLambdaBody); 14429 verifyFormat("auto fct_SLS_Empty = []()\n" 14430 "{\n" 14431 " return 17;\n" 14432 "};", 14433 LLVMWithBeforeLambdaBody); 14434 verifyFormat("TwoNestedLambdas_SLS_Empty(\n" 14435 " []()\n" 14436 " {\n" 14437 " return Call([]() {});\n" 14438 " });", 14439 LLVMWithBeforeLambdaBody); 14440 verifyFormat("TwoNestedLambdas_SLS_Empty(A,\n" 14441 " []()\n" 14442 " {\n" 14443 " return Call([]() {});\n" 14444 " });", 14445 LLVMWithBeforeLambdaBody); 14446 verifyFormat( 14447 "FctWithLongLineInLambda_SLS_Empty(\n" 14448 " []()\n" 14449 " {\n" 14450 " return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n" 14451 " AndShouldNotBeConsiderAsInline,\n" 14452 " LambdaBodyMustBeBreak);\n" 14453 " });", 14454 LLVMWithBeforeLambdaBody); 14455 14456 LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine = 14457 FormatStyle::ShortLambdaStyle::SLS_Inline; 14458 verifyFormat("FctWithOneNestedLambdaInline_SLS_Inline([]() { return 17; });", 14459 LLVMWithBeforeLambdaBody); 14460 verifyFormat("FctWithOneNestedLambdaEmpty_SLS_Inline([]() {});", 14461 LLVMWithBeforeLambdaBody); 14462 verifyFormat("auto fct_SLS_Inline = []()\n" 14463 "{\n" 14464 " return 17;\n" 14465 "};", 14466 LLVMWithBeforeLambdaBody); 14467 verifyFormat("TwoNestedLambdas_SLS_Inline([]() { return Call([]() { return " 14468 "17; }); });", 14469 LLVMWithBeforeLambdaBody); 14470 verifyFormat( 14471 "FctWithLongLineInLambda_SLS_Inline(\n" 14472 " []()\n" 14473 " {\n" 14474 " return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n" 14475 " AndShouldNotBeConsiderAsInline,\n" 14476 " LambdaBodyMustBeBreak);\n" 14477 " });", 14478 LLVMWithBeforeLambdaBody); 14479 verifyFormat("FctWithMultipleParams_SLS_Inline(" 14480 "VeryLongParameterThatShouldAskToBeOnMultiLine,\n" 14481 " []() { return 17; });", 14482 LLVMWithBeforeLambdaBody); 14483 verifyFormat( 14484 "FctWithMultipleParams_SLS_Inline(FirstParam, []() { return 17; });", 14485 LLVMWithBeforeLambdaBody); 14486 14487 LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine = 14488 FormatStyle::ShortLambdaStyle::SLS_All; 14489 verifyFormat("FctWithOneNestedLambdaInline_SLS_All([]() { return 17; });", 14490 LLVMWithBeforeLambdaBody); 14491 verifyFormat("FctWithOneNestedLambdaEmpty_SLS_All([]() {});", 14492 LLVMWithBeforeLambdaBody); 14493 verifyFormat("auto fct_SLS_All = []() { return 17; };", 14494 LLVMWithBeforeLambdaBody); 14495 verifyFormat("FctWithOneParam_SLS_All(\n" 14496 " []()\n" 14497 " {\n" 14498 " // A cool function...\n" 14499 " return 43;\n" 14500 " });", 14501 LLVMWithBeforeLambdaBody); 14502 verifyFormat("FctWithMultipleParams_SLS_All(" 14503 "VeryLongParameterThatShouldAskToBeOnMultiLine,\n" 14504 " []() { return 17; });", 14505 LLVMWithBeforeLambdaBody); 14506 verifyFormat("FctWithMultipleParams_SLS_All(A, []() { return 17; });", 14507 LLVMWithBeforeLambdaBody); 14508 verifyFormat("FctWithMultipleParams_SLS_All(A, B, []() { return 17; });", 14509 LLVMWithBeforeLambdaBody); 14510 verifyFormat( 14511 "FctWithLongLineInLambda_SLS_All(\n" 14512 " []()\n" 14513 " {\n" 14514 " return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n" 14515 " AndShouldNotBeConsiderAsInline,\n" 14516 " LambdaBodyMustBeBreak);\n" 14517 " });", 14518 LLVMWithBeforeLambdaBody); 14519 verifyFormat( 14520 "auto fct_SLS_All = []()\n" 14521 "{\n" 14522 " return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n" 14523 " AndShouldNotBeConsiderAsInline,\n" 14524 " LambdaBodyMustBeBreak);\n" 14525 "};", 14526 LLVMWithBeforeLambdaBody); 14527 LLVMWithBeforeLambdaBody.BinPackParameters = false; 14528 verifyFormat("FctAllOnSameLine_SLS_All([]() { return S; }, Fst, Second);", 14529 LLVMWithBeforeLambdaBody); 14530 verifyFormat( 14531 "FctWithLongLineInLambda_SLS_All([]() { return SomeValueNotSoLong; },\n" 14532 " FirstParam,\n" 14533 " SecondParam,\n" 14534 " ThirdParam,\n" 14535 " FourthParam);", 14536 LLVMWithBeforeLambdaBody); 14537 verifyFormat("FctWithLongLineInLambda_SLS_All(\n" 14538 " []() { return " 14539 "SomeValueVeryVeryVeryVeryVeryVeryVeryVeryVeryLong; },\n" 14540 " FirstParam,\n" 14541 " SecondParam,\n" 14542 " ThirdParam,\n" 14543 " FourthParam);", 14544 LLVMWithBeforeLambdaBody); 14545 verifyFormat( 14546 "FctWithLongLineInLambda_SLS_All(FirstParam,\n" 14547 " SecondParam,\n" 14548 " ThirdParam,\n" 14549 " FourthParam,\n" 14550 " []() { return SomeValueNotSoLong; });", 14551 LLVMWithBeforeLambdaBody); 14552 verifyFormat("FctWithLongLineInLambda_SLS_All(\n" 14553 " []()\n" 14554 " {\n" 14555 " return " 14556 "HereAVeryLongLineThatWillBeFormattedOnMultipleLineAndShouldNotB" 14557 "eConsiderAsInline;\n" 14558 " });", 14559 LLVMWithBeforeLambdaBody); 14560 verifyFormat( 14561 "FctWithLongLineInLambda_SLS_All(\n" 14562 " []()\n" 14563 " {\n" 14564 " return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n" 14565 " AndShouldNotBeConsiderAsInline,\n" 14566 " LambdaBodyMustBeBreak);\n" 14567 " });", 14568 LLVMWithBeforeLambdaBody); 14569 verifyFormat("FctWithTwoParams_SLS_All(\n" 14570 " []()\n" 14571 " {\n" 14572 " // A cool function...\n" 14573 " return 43;\n" 14574 " },\n" 14575 " 87);", 14576 LLVMWithBeforeLambdaBody); 14577 verifyFormat("FctWithTwoParams_SLS_All([]() { return 43; }, 87);", 14578 LLVMWithBeforeLambdaBody); 14579 verifyFormat("FctWithOneNestedLambdas_SLS_All([]() { return 17; });", 14580 LLVMWithBeforeLambdaBody); 14581 verifyFormat( 14582 "TwoNestedLambdas_SLS_All([]() { return Call([]() { return 17; }); });", 14583 LLVMWithBeforeLambdaBody); 14584 verifyFormat("TwoNestedLambdas_SLS_All([]() { return Call([]() { return 17; " 14585 "}); }, x);", 14586 LLVMWithBeforeLambdaBody); 14587 verifyFormat("TwoNestedLambdas_SLS_All(\n" 14588 " []()\n" 14589 " {\n" 14590 " // A cool function...\n" 14591 " return Call([]() { return 17; });\n" 14592 " });", 14593 LLVMWithBeforeLambdaBody); 14594 verifyFormat("TwoNestedLambdas_SLS_All(\n" 14595 " []()\n" 14596 " {\n" 14597 " return Call(\n" 14598 " []()\n" 14599 " {\n" 14600 " // A cool function...\n" 14601 " return 17;\n" 14602 " });\n" 14603 " });", 14604 LLVMWithBeforeLambdaBody); 14605 } 14606 14607 TEST_F(FormatTest, LambdaWithLineComments) { 14608 FormatStyle LLVMWithBeforeLambdaBody = getLLVMStyle(); 14609 LLVMWithBeforeLambdaBody.BreakBeforeBraces = FormatStyle::BS_Custom; 14610 LLVMWithBeforeLambdaBody.BraceWrapping.BeforeLambdaBody = true; 14611 LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine = 14612 FormatStyle::ShortLambdaStyle::SLS_All; 14613 14614 verifyFormat("auto k = []() { return; }", LLVMWithBeforeLambdaBody); 14615 verifyFormat("auto k = []() // comment\n" 14616 "{ return; }", 14617 LLVMWithBeforeLambdaBody); 14618 verifyFormat("auto k = []() /* comment */ { return; }", 14619 LLVMWithBeforeLambdaBody); 14620 verifyFormat("auto k = []() /* comment */ /* comment */ { return; }", 14621 LLVMWithBeforeLambdaBody); 14622 verifyFormat("auto k = []() // X\n" 14623 "{ return; }", 14624 LLVMWithBeforeLambdaBody); 14625 verifyFormat( 14626 "auto k = []() // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n" 14627 "{ return; }", 14628 LLVMWithBeforeLambdaBody); 14629 } 14630 14631 TEST_F(FormatTest, EmptyLinesInLambdas) { 14632 verifyFormat("auto lambda = []() {\n" 14633 " x(); //\n" 14634 "};", 14635 "auto lambda = []() {\n" 14636 "\n" 14637 " x(); //\n" 14638 "\n" 14639 "};"); 14640 } 14641 14642 TEST_F(FormatTest, FormatsBlocks) { 14643 FormatStyle ShortBlocks = getLLVMStyle(); 14644 ShortBlocks.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always; 14645 verifyFormat("int (^Block)(int, int);", ShortBlocks); 14646 verifyFormat("int (^Block1)(int, int) = ^(int i, int j)", ShortBlocks); 14647 verifyFormat("void (^block)(int) = ^(id test) { int i; };", ShortBlocks); 14648 verifyFormat("void (^block)(int) = ^(int test) { int i; };", ShortBlocks); 14649 verifyFormat("void (^block)(int) = ^id(int test) { int i; };", ShortBlocks); 14650 verifyFormat("void (^block)(int) = ^int(int test) { int i; };", ShortBlocks); 14651 14652 verifyFormat("foo(^{ bar(); });", ShortBlocks); 14653 verifyFormat("foo(a, ^{ bar(); });", ShortBlocks); 14654 verifyFormat("{ void (^block)(Object *x); }", ShortBlocks); 14655 14656 verifyFormat("[operation setCompletionBlock:^{\n" 14657 " [self onOperationDone];\n" 14658 "}];"); 14659 verifyFormat("int i = {[operation setCompletionBlock:^{\n" 14660 " [self onOperationDone];\n" 14661 "}]};"); 14662 verifyFormat("[operation setCompletionBlock:^(int *i) {\n" 14663 " f();\n" 14664 "}];"); 14665 verifyFormat("int a = [operation block:^int(int *i) {\n" 14666 " return 1;\n" 14667 "}];"); 14668 verifyFormat("[myObject doSomethingWith:arg1\n" 14669 " aaa:^int(int *a) {\n" 14670 " return 1;\n" 14671 " }\n" 14672 " bbb:f(a * bbbbbbbb)];"); 14673 14674 verifyFormat("[operation setCompletionBlock:^{\n" 14675 " [self.delegate newDataAvailable];\n" 14676 "}];", 14677 getLLVMStyleWithColumns(60)); 14678 verifyFormat("dispatch_async(_fileIOQueue, ^{\n" 14679 " NSString *path = [self sessionFilePath];\n" 14680 " if (path) {\n" 14681 " // ...\n" 14682 " }\n" 14683 "});"); 14684 verifyFormat("[[SessionService sharedService]\n" 14685 " loadWindowWithCompletionBlock:^(SessionWindow *window) {\n" 14686 " if (window) {\n" 14687 " [self windowDidLoad:window];\n" 14688 " } else {\n" 14689 " [self errorLoadingWindow];\n" 14690 " }\n" 14691 " }];"); 14692 verifyFormat("void (^largeBlock)(void) = ^{\n" 14693 " // ...\n" 14694 "};\n", 14695 getLLVMStyleWithColumns(40)); 14696 verifyFormat("[[SessionService sharedService]\n" 14697 " loadWindowWithCompletionBlock: //\n" 14698 " ^(SessionWindow *window) {\n" 14699 " if (window) {\n" 14700 " [self windowDidLoad:window];\n" 14701 " } else {\n" 14702 " [self errorLoadingWindow];\n" 14703 " }\n" 14704 " }];", 14705 getLLVMStyleWithColumns(60)); 14706 verifyFormat("[myObject doSomethingWith:arg1\n" 14707 " firstBlock:^(Foo *a) {\n" 14708 " // ...\n" 14709 " int i;\n" 14710 " }\n" 14711 " secondBlock:^(Bar *b) {\n" 14712 " // ...\n" 14713 " int i;\n" 14714 " }\n" 14715 " thirdBlock:^Foo(Bar *b) {\n" 14716 " // ...\n" 14717 " int i;\n" 14718 " }];"); 14719 verifyFormat("[myObject doSomethingWith:arg1\n" 14720 " firstBlock:-1\n" 14721 " secondBlock:^(Bar *b) {\n" 14722 " // ...\n" 14723 " int i;\n" 14724 " }];"); 14725 14726 verifyFormat("f(^{\n" 14727 " @autoreleasepool {\n" 14728 " if (a) {\n" 14729 " g();\n" 14730 " }\n" 14731 " }\n" 14732 "});"); 14733 verifyFormat("Block b = ^int *(A *a, B *b) {}"); 14734 verifyFormat("BOOL (^aaa)(void) = ^BOOL {\n" 14735 "};"); 14736 14737 FormatStyle FourIndent = getLLVMStyle(); 14738 FourIndent.ObjCBlockIndentWidth = 4; 14739 verifyFormat("[operation setCompletionBlock:^{\n" 14740 " [self onOperationDone];\n" 14741 "}];", 14742 FourIndent); 14743 } 14744 14745 TEST_F(FormatTest, FormatsBlocksWithZeroColumnWidth) { 14746 FormatStyle ZeroColumn = getLLVMStyle(); 14747 ZeroColumn.ColumnLimit = 0; 14748 14749 verifyFormat("[[SessionService sharedService] " 14750 "loadWindowWithCompletionBlock:^(SessionWindow *window) {\n" 14751 " if (window) {\n" 14752 " [self windowDidLoad:window];\n" 14753 " } else {\n" 14754 " [self errorLoadingWindow];\n" 14755 " }\n" 14756 "}];", 14757 ZeroColumn); 14758 EXPECT_EQ("[[SessionService sharedService]\n" 14759 " loadWindowWithCompletionBlock:^(SessionWindow *window) {\n" 14760 " if (window) {\n" 14761 " [self windowDidLoad:window];\n" 14762 " } else {\n" 14763 " [self errorLoadingWindow];\n" 14764 " }\n" 14765 " }];", 14766 format("[[SessionService sharedService]\n" 14767 "loadWindowWithCompletionBlock:^(SessionWindow *window) {\n" 14768 " if (window) {\n" 14769 " [self windowDidLoad:window];\n" 14770 " } else {\n" 14771 " [self errorLoadingWindow];\n" 14772 " }\n" 14773 "}];", 14774 ZeroColumn)); 14775 verifyFormat("[myObject doSomethingWith:arg1\n" 14776 " firstBlock:^(Foo *a) {\n" 14777 " // ...\n" 14778 " int i;\n" 14779 " }\n" 14780 " secondBlock:^(Bar *b) {\n" 14781 " // ...\n" 14782 " int i;\n" 14783 " }\n" 14784 " thirdBlock:^Foo(Bar *b) {\n" 14785 " // ...\n" 14786 " int i;\n" 14787 " }];", 14788 ZeroColumn); 14789 verifyFormat("f(^{\n" 14790 " @autoreleasepool {\n" 14791 " if (a) {\n" 14792 " g();\n" 14793 " }\n" 14794 " }\n" 14795 "});", 14796 ZeroColumn); 14797 verifyFormat("void (^largeBlock)(void) = ^{\n" 14798 " // ...\n" 14799 "};", 14800 ZeroColumn); 14801 14802 ZeroColumn.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always; 14803 EXPECT_EQ("void (^largeBlock)(void) = ^{ int i; };", 14804 format("void (^largeBlock)(void) = ^{ int i; };", ZeroColumn)); 14805 ZeroColumn.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Never; 14806 EXPECT_EQ("void (^largeBlock)(void) = ^{\n" 14807 " int i;\n" 14808 "};", 14809 format("void (^largeBlock)(void) = ^{ int i; };", ZeroColumn)); 14810 } 14811 14812 TEST_F(FormatTest, SupportsCRLF) { 14813 EXPECT_EQ("int a;\r\n" 14814 "int b;\r\n" 14815 "int c;\r\n", 14816 format("int a;\r\n" 14817 " int b;\r\n" 14818 " int c;\r\n", 14819 getLLVMStyle())); 14820 EXPECT_EQ("int a;\r\n" 14821 "int b;\r\n" 14822 "int c;\r\n", 14823 format("int a;\r\n" 14824 " int b;\n" 14825 " int c;\r\n", 14826 getLLVMStyle())); 14827 EXPECT_EQ("int a;\n" 14828 "int b;\n" 14829 "int c;\n", 14830 format("int a;\r\n" 14831 " int b;\n" 14832 " int c;\n", 14833 getLLVMStyle())); 14834 EXPECT_EQ("\"aaaaaaa \"\r\n" 14835 "\"bbbbbbb\";\r\n", 14836 format("\"aaaaaaa bbbbbbb\";\r\n", getLLVMStyleWithColumns(10))); 14837 EXPECT_EQ("#define A \\\r\n" 14838 " b; \\\r\n" 14839 " c; \\\r\n" 14840 " d;\r\n", 14841 format("#define A \\\r\n" 14842 " b; \\\r\n" 14843 " c; d; \r\n", 14844 getGoogleStyle())); 14845 14846 EXPECT_EQ("/*\r\n" 14847 "multi line block comments\r\n" 14848 "should not introduce\r\n" 14849 "an extra carriage return\r\n" 14850 "*/\r\n", 14851 format("/*\r\n" 14852 "multi line block comments\r\n" 14853 "should not introduce\r\n" 14854 "an extra carriage return\r\n" 14855 "*/\r\n")); 14856 EXPECT_EQ("/*\r\n" 14857 "\r\n" 14858 "*/", 14859 format("/*\r\n" 14860 " \r\r\r\n" 14861 "*/")); 14862 14863 FormatStyle style = getLLVMStyle(); 14864 14865 style.DeriveLineEnding = true; 14866 style.UseCRLF = false; 14867 EXPECT_EQ("union FooBarBazQux {\n" 14868 " int foo;\n" 14869 " int bar;\n" 14870 " int baz;\n" 14871 "};", 14872 format("union FooBarBazQux {\r\n" 14873 " int foo;\n" 14874 " int bar;\r\n" 14875 " int baz;\n" 14876 "};", 14877 style)); 14878 style.UseCRLF = true; 14879 EXPECT_EQ("union FooBarBazQux {\r\n" 14880 " int foo;\r\n" 14881 " int bar;\r\n" 14882 " int baz;\r\n" 14883 "};", 14884 format("union FooBarBazQux {\r\n" 14885 " int foo;\n" 14886 " int bar;\r\n" 14887 " int baz;\n" 14888 "};", 14889 style)); 14890 14891 style.DeriveLineEnding = false; 14892 style.UseCRLF = false; 14893 EXPECT_EQ("union FooBarBazQux {\n" 14894 " int foo;\n" 14895 " int bar;\n" 14896 " int baz;\n" 14897 " int qux;\n" 14898 "};", 14899 format("union FooBarBazQux {\r\n" 14900 " int foo;\n" 14901 " int bar;\r\n" 14902 " int baz;\n" 14903 " int qux;\r\n" 14904 "};", 14905 style)); 14906 style.UseCRLF = true; 14907 EXPECT_EQ("union FooBarBazQux {\r\n" 14908 " int foo;\r\n" 14909 " int bar;\r\n" 14910 " int baz;\r\n" 14911 " int qux;\r\n" 14912 "};", 14913 format("union FooBarBazQux {\r\n" 14914 " int foo;\n" 14915 " int bar;\r\n" 14916 " int baz;\n" 14917 " int qux;\n" 14918 "};", 14919 style)); 14920 14921 style.DeriveLineEnding = true; 14922 style.UseCRLF = false; 14923 EXPECT_EQ("union FooBarBazQux {\r\n" 14924 " int foo;\r\n" 14925 " int bar;\r\n" 14926 " int baz;\r\n" 14927 " int qux;\r\n" 14928 "};", 14929 format("union FooBarBazQux {\r\n" 14930 " int foo;\n" 14931 " int bar;\r\n" 14932 " int baz;\n" 14933 " int qux;\r\n" 14934 "};", 14935 style)); 14936 style.UseCRLF = true; 14937 EXPECT_EQ("union FooBarBazQux {\n" 14938 " int foo;\n" 14939 " int bar;\n" 14940 " int baz;\n" 14941 " int qux;\n" 14942 "};", 14943 format("union FooBarBazQux {\r\n" 14944 " int foo;\n" 14945 " int bar;\r\n" 14946 " int baz;\n" 14947 " int qux;\n" 14948 "};", 14949 style)); 14950 } 14951 14952 TEST_F(FormatTest, MunchSemicolonAfterBlocks) { 14953 verifyFormat("MY_CLASS(C) {\n" 14954 " int i;\n" 14955 " int j;\n" 14956 "};"); 14957 } 14958 14959 TEST_F(FormatTest, ConfigurableContinuationIndentWidth) { 14960 FormatStyle TwoIndent = getLLVMStyleWithColumns(15); 14961 TwoIndent.ContinuationIndentWidth = 2; 14962 14963 EXPECT_EQ("int i =\n" 14964 " longFunction(\n" 14965 " arg);", 14966 format("int i = longFunction(arg);", TwoIndent)); 14967 14968 FormatStyle SixIndent = getLLVMStyleWithColumns(20); 14969 SixIndent.ContinuationIndentWidth = 6; 14970 14971 EXPECT_EQ("int i =\n" 14972 " longFunction(\n" 14973 " arg);", 14974 format("int i = longFunction(arg);", SixIndent)); 14975 } 14976 14977 TEST_F(FormatTest, WrappedClosingParenthesisIndent) { 14978 FormatStyle Style = getLLVMStyle(); 14979 verifyFormat("int Foo::getter(\n" 14980 " //\n" 14981 ") const {\n" 14982 " return foo;\n" 14983 "}", 14984 Style); 14985 verifyFormat("void Foo::setter(\n" 14986 " //\n" 14987 ") {\n" 14988 " foo = 1;\n" 14989 "}", 14990 Style); 14991 } 14992 14993 TEST_F(FormatTest, SpacesInAngles) { 14994 FormatStyle Spaces = getLLVMStyle(); 14995 Spaces.SpacesInAngles = true; 14996 14997 verifyFormat("static_cast< int >(arg);", Spaces); 14998 verifyFormat("template < typename T0, typename T1 > void f() {}", Spaces); 14999 verifyFormat("f< int, float >();", Spaces); 15000 verifyFormat("template <> g() {}", Spaces); 15001 verifyFormat("template < std::vector< int > > f() {}", Spaces); 15002 verifyFormat("std::function< void(int, int) > fct;", Spaces); 15003 verifyFormat("void inFunction() { std::function< void(int, int) > fct; }", 15004 Spaces); 15005 15006 Spaces.Standard = FormatStyle::LS_Cpp03; 15007 Spaces.SpacesInAngles = true; 15008 verifyFormat("A< A< int > >();", Spaces); 15009 15010 Spaces.SpacesInAngles = false; 15011 verifyFormat("A<A<int> >();", Spaces); 15012 15013 Spaces.Standard = FormatStyle::LS_Cpp11; 15014 Spaces.SpacesInAngles = true; 15015 verifyFormat("A< A< int > >();", Spaces); 15016 15017 Spaces.SpacesInAngles = false; 15018 verifyFormat("A<A<int>>();", Spaces); 15019 } 15020 15021 TEST_F(FormatTest, SpaceAfterTemplateKeyword) { 15022 FormatStyle Style = getLLVMStyle(); 15023 Style.SpaceAfterTemplateKeyword = false; 15024 verifyFormat("template<int> void foo();", Style); 15025 } 15026 15027 TEST_F(FormatTest, TripleAngleBrackets) { 15028 verifyFormat("f<<<1, 1>>>();"); 15029 verifyFormat("f<<<1, 1, 1, s>>>();"); 15030 verifyFormat("f<<<a, b, c, d>>>();"); 15031 EXPECT_EQ("f<<<1, 1>>>();", format("f <<< 1, 1 >>> ();")); 15032 verifyFormat("f<param><<<1, 1>>>();"); 15033 verifyFormat("f<1><<<1, 1>>>();"); 15034 EXPECT_EQ("f<param><<<1, 1>>>();", format("f< param > <<< 1, 1 >>> ();")); 15035 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" 15036 "aaaaaaaaaaa<<<\n 1, 1>>>();"); 15037 verifyFormat("aaaaaaaaaaaaaaa<aaaaaaaaa, aaaaaaaaaa, aaaaaaaaaaaaaa>\n" 15038 " <<<aaaaaaaaa, aaaaaaaaaa, aaaaaaaaaaaaaaaaaa>>>();"); 15039 } 15040 15041 TEST_F(FormatTest, MergeLessLessAtEnd) { 15042 verifyFormat("<<"); 15043 EXPECT_EQ("< < <", format("\\\n<<<")); 15044 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" 15045 "aaallvm::outs() <<"); 15046 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" 15047 "aaaallvm::outs()\n <<"); 15048 } 15049 15050 TEST_F(FormatTest, HandleUnbalancedImplicitBracesAcrossPPBranches) { 15051 std::string code = "#if A\n" 15052 "#if B\n" 15053 "a.\n" 15054 "#endif\n" 15055 " a = 1;\n" 15056 "#else\n" 15057 "#endif\n" 15058 "#if C\n" 15059 "#else\n" 15060 "#endif\n"; 15061 EXPECT_EQ(code, format(code)); 15062 } 15063 15064 TEST_F(FormatTest, HandleConflictMarkers) { 15065 // Git/SVN conflict markers. 15066 EXPECT_EQ("int a;\n" 15067 "void f() {\n" 15068 " callme(some(parameter1,\n" 15069 "<<<<<<< text by the vcs\n" 15070 " parameter2),\n" 15071 "||||||| text by the vcs\n" 15072 " parameter2),\n" 15073 " parameter3,\n" 15074 "======= text by the vcs\n" 15075 " parameter2, parameter3),\n" 15076 ">>>>>>> text by the vcs\n" 15077 " otherparameter);\n", 15078 format("int a;\n" 15079 "void f() {\n" 15080 " callme(some(parameter1,\n" 15081 "<<<<<<< text by the vcs\n" 15082 " parameter2),\n" 15083 "||||||| text by the vcs\n" 15084 " parameter2),\n" 15085 " parameter3,\n" 15086 "======= text by the vcs\n" 15087 " parameter2,\n" 15088 " parameter3),\n" 15089 ">>>>>>> text by the vcs\n" 15090 " otherparameter);\n")); 15091 15092 // Perforce markers. 15093 EXPECT_EQ("void f() {\n" 15094 " function(\n" 15095 ">>>> text by the vcs\n" 15096 " parameter,\n" 15097 "==== text by the vcs\n" 15098 " parameter,\n" 15099 "==== text by the vcs\n" 15100 " parameter,\n" 15101 "<<<< text by the vcs\n" 15102 " parameter);\n", 15103 format("void f() {\n" 15104 " function(\n" 15105 ">>>> text by the vcs\n" 15106 " parameter,\n" 15107 "==== text by the vcs\n" 15108 " parameter,\n" 15109 "==== text by the vcs\n" 15110 " parameter,\n" 15111 "<<<< text by the vcs\n" 15112 " parameter);\n")); 15113 15114 EXPECT_EQ("<<<<<<<\n" 15115 "|||||||\n" 15116 "=======\n" 15117 ">>>>>>>", 15118 format("<<<<<<<\n" 15119 "|||||||\n" 15120 "=======\n" 15121 ">>>>>>>")); 15122 15123 EXPECT_EQ("<<<<<<<\n" 15124 "|||||||\n" 15125 "int i;\n" 15126 "=======\n" 15127 ">>>>>>>", 15128 format("<<<<<<<\n" 15129 "|||||||\n" 15130 "int i;\n" 15131 "=======\n" 15132 ">>>>>>>")); 15133 15134 // FIXME: Handle parsing of macros around conflict markers correctly: 15135 EXPECT_EQ("#define Macro \\\n" 15136 "<<<<<<<\n" 15137 "Something \\\n" 15138 "|||||||\n" 15139 "Else \\\n" 15140 "=======\n" 15141 "Other \\\n" 15142 ">>>>>>>\n" 15143 " End int i;\n", 15144 format("#define Macro \\\n" 15145 "<<<<<<<\n" 15146 " Something \\\n" 15147 "|||||||\n" 15148 " Else \\\n" 15149 "=======\n" 15150 " Other \\\n" 15151 ">>>>>>>\n" 15152 " End\n" 15153 "int i;\n")); 15154 } 15155 15156 TEST_F(FormatTest, DisableRegions) { 15157 EXPECT_EQ("int i;\n" 15158 "// clang-format off\n" 15159 " int j;\n" 15160 "// clang-format on\n" 15161 "int k;", 15162 format(" int i;\n" 15163 " // clang-format off\n" 15164 " int j;\n" 15165 " // clang-format on\n" 15166 " int k;")); 15167 EXPECT_EQ("int i;\n" 15168 "/* clang-format off */\n" 15169 " int j;\n" 15170 "/* clang-format on */\n" 15171 "int k;", 15172 format(" int i;\n" 15173 " /* clang-format off */\n" 15174 " int j;\n" 15175 " /* clang-format on */\n" 15176 " int k;")); 15177 15178 // Don't reflow comments within disabled regions. 15179 EXPECT_EQ("// clang-format off\n" 15180 "// long long long long long long line\n" 15181 "/* clang-format on */\n" 15182 "/* long long long\n" 15183 " * long long long\n" 15184 " * line */\n" 15185 "int i;\n" 15186 "/* clang-format off */\n" 15187 "/* long long long long long long line */\n", 15188 format("// clang-format off\n" 15189 "// long long long long long long line\n" 15190 "/* clang-format on */\n" 15191 "/* long long long long long long line */\n" 15192 "int i;\n" 15193 "/* clang-format off */\n" 15194 "/* long long long long long long line */\n", 15195 getLLVMStyleWithColumns(20))); 15196 } 15197 15198 TEST_F(FormatTest, DoNotCrashOnInvalidInput) { 15199 format("? ) ="); 15200 verifyNoCrash("#define a\\\n /**/}"); 15201 } 15202 15203 TEST_F(FormatTest, FormatsTableGenCode) { 15204 FormatStyle Style = getLLVMStyle(); 15205 Style.Language = FormatStyle::LK_TableGen; 15206 verifyFormat("include \"a.td\"\ninclude \"b.td\"", Style); 15207 } 15208 15209 TEST_F(FormatTest, ArrayOfTemplates) { 15210 EXPECT_EQ("auto a = new unique_ptr<int>[10];", 15211 format("auto a = new unique_ptr<int > [ 10];")); 15212 15213 FormatStyle Spaces = getLLVMStyle(); 15214 Spaces.SpacesInSquareBrackets = true; 15215 EXPECT_EQ("auto a = new unique_ptr<int>[ 10 ];", 15216 format("auto a = new unique_ptr<int > [10];", Spaces)); 15217 } 15218 15219 TEST_F(FormatTest, ArrayAsTemplateType) { 15220 EXPECT_EQ("auto a = unique_ptr<Foo<Bar>[10]>;", 15221 format("auto a = unique_ptr < Foo < Bar>[ 10]> ;")); 15222 15223 FormatStyle Spaces = getLLVMStyle(); 15224 Spaces.SpacesInSquareBrackets = true; 15225 EXPECT_EQ("auto a = unique_ptr<Foo<Bar>[ 10 ]>;", 15226 format("auto a = unique_ptr < Foo < Bar>[10]> ;", Spaces)); 15227 } 15228 15229 TEST_F(FormatTest, NoSpaceAfterSuper) { verifyFormat("__super::FooBar();"); } 15230 15231 TEST(FormatStyle, GetStyleWithEmptyFileName) { 15232 llvm::vfs::InMemoryFileSystem FS; 15233 auto Style1 = getStyle("file", "", "Google", "", &FS); 15234 ASSERT_TRUE((bool)Style1); 15235 ASSERT_EQ(*Style1, getGoogleStyle()); 15236 } 15237 15238 TEST(FormatStyle, GetStyleOfFile) { 15239 llvm::vfs::InMemoryFileSystem FS; 15240 // Test 1: format file in the same directory. 15241 ASSERT_TRUE( 15242 FS.addFile("/a/.clang-format", 0, 15243 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: LLVM"))); 15244 ASSERT_TRUE( 15245 FS.addFile("/a/test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int i;"))); 15246 auto Style1 = getStyle("file", "/a/.clang-format", "Google", "", &FS); 15247 ASSERT_TRUE((bool)Style1); 15248 ASSERT_EQ(*Style1, getLLVMStyle()); 15249 15250 // Test 2.1: fallback to default. 15251 ASSERT_TRUE( 15252 FS.addFile("/b/test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int i;"))); 15253 auto Style2 = getStyle("file", "/b/test.cpp", "Mozilla", "", &FS); 15254 ASSERT_TRUE((bool)Style2); 15255 ASSERT_EQ(*Style2, getMozillaStyle()); 15256 15257 // Test 2.2: no format on 'none' fallback style. 15258 Style2 = getStyle("file", "/b/test.cpp", "none", "", &FS); 15259 ASSERT_TRUE((bool)Style2); 15260 ASSERT_EQ(*Style2, getNoStyle()); 15261 15262 // Test 2.3: format if config is found with no based style while fallback is 15263 // 'none'. 15264 ASSERT_TRUE(FS.addFile("/b/.clang-format", 0, 15265 llvm::MemoryBuffer::getMemBuffer("IndentWidth: 2"))); 15266 Style2 = getStyle("file", "/b/test.cpp", "none", "", &FS); 15267 ASSERT_TRUE((bool)Style2); 15268 ASSERT_EQ(*Style2, getLLVMStyle()); 15269 15270 // Test 2.4: format if yaml with no based style, while fallback is 'none'. 15271 Style2 = getStyle("{}", "a.h", "none", "", &FS); 15272 ASSERT_TRUE((bool)Style2); 15273 ASSERT_EQ(*Style2, getLLVMStyle()); 15274 15275 // Test 3: format file in parent directory. 15276 ASSERT_TRUE( 15277 FS.addFile("/c/.clang-format", 0, 15278 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google"))); 15279 ASSERT_TRUE(FS.addFile("/c/sub/sub/sub/test.cpp", 0, 15280 llvm::MemoryBuffer::getMemBuffer("int i;"))); 15281 auto Style3 = getStyle("file", "/c/sub/sub/sub/test.cpp", "LLVM", "", &FS); 15282 ASSERT_TRUE((bool)Style3); 15283 ASSERT_EQ(*Style3, getGoogleStyle()); 15284 15285 // Test 4: error on invalid fallback style 15286 auto Style4 = getStyle("file", "a.h", "KungFu", "", &FS); 15287 ASSERT_FALSE((bool)Style4); 15288 llvm::consumeError(Style4.takeError()); 15289 15290 // Test 5: error on invalid yaml on command line 15291 auto Style5 = getStyle("{invalid_key=invalid_value}", "a.h", "LLVM", "", &FS); 15292 ASSERT_FALSE((bool)Style5); 15293 llvm::consumeError(Style5.takeError()); 15294 15295 // Test 6: error on invalid style 15296 auto Style6 = getStyle("KungFu", "a.h", "LLVM", "", &FS); 15297 ASSERT_FALSE((bool)Style6); 15298 llvm::consumeError(Style6.takeError()); 15299 15300 // Test 7: found config file, error on parsing it 15301 ASSERT_TRUE( 15302 FS.addFile("/d/.clang-format", 0, 15303 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: LLVM\n" 15304 "InvalidKey: InvalidValue"))); 15305 ASSERT_TRUE( 15306 FS.addFile("/d/test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int i;"))); 15307 auto Style7 = getStyle("file", "/d/.clang-format", "LLVM", "", &FS); 15308 ASSERT_FALSE((bool)Style7); 15309 llvm::consumeError(Style7.takeError()); 15310 15311 // Test 8: inferred per-language defaults apply. 15312 auto StyleTd = getStyle("file", "x.td", "llvm", "", &FS); 15313 ASSERT_TRUE((bool)StyleTd); 15314 ASSERT_EQ(*StyleTd, getLLVMStyle(FormatStyle::LK_TableGen)); 15315 } 15316 15317 TEST_F(ReplacementTest, FormatCodeAfterReplacements) { 15318 // Column limit is 20. 15319 std::string Code = "Type *a =\n" 15320 " new Type();\n" 15321 "g(iiiii, 0, jjjjj,\n" 15322 " 0, kkkkk, 0, mm);\n" 15323 "int bad = format ;"; 15324 std::string Expected = "auto a = new Type();\n" 15325 "g(iiiii, nullptr,\n" 15326 " jjjjj, nullptr,\n" 15327 " kkkkk, nullptr,\n" 15328 " mm);\n" 15329 "int bad = format ;"; 15330 FileID ID = Context.createInMemoryFile("format.cpp", Code); 15331 tooling::Replacements Replaces = toReplacements( 15332 {tooling::Replacement(Context.Sources, Context.getLocation(ID, 1, 1), 6, 15333 "auto "), 15334 tooling::Replacement(Context.Sources, Context.getLocation(ID, 3, 10), 1, 15335 "nullptr"), 15336 tooling::Replacement(Context.Sources, Context.getLocation(ID, 4, 3), 1, 15337 "nullptr"), 15338 tooling::Replacement(Context.Sources, Context.getLocation(ID, 4, 13), 1, 15339 "nullptr")}); 15340 15341 format::FormatStyle Style = format::getLLVMStyle(); 15342 Style.ColumnLimit = 20; // Set column limit to 20 to increase readibility. 15343 auto FormattedReplaces = formatReplacements(Code, Replaces, Style); 15344 EXPECT_TRUE(static_cast<bool>(FormattedReplaces)) 15345 << llvm::toString(FormattedReplaces.takeError()) << "\n"; 15346 auto Result = applyAllReplacements(Code, *FormattedReplaces); 15347 EXPECT_TRUE(static_cast<bool>(Result)); 15348 EXPECT_EQ(Expected, *Result); 15349 } 15350 15351 TEST_F(ReplacementTest, SortIncludesAfterReplacement) { 15352 std::string Code = "#include \"a.h\"\n" 15353 "#include \"c.h\"\n" 15354 "\n" 15355 "int main() {\n" 15356 " return 0;\n" 15357 "}"; 15358 std::string Expected = "#include \"a.h\"\n" 15359 "#include \"b.h\"\n" 15360 "#include \"c.h\"\n" 15361 "\n" 15362 "int main() {\n" 15363 " return 0;\n" 15364 "}"; 15365 FileID ID = Context.createInMemoryFile("fix.cpp", Code); 15366 tooling::Replacements Replaces = toReplacements( 15367 {tooling::Replacement(Context.Sources, Context.getLocation(ID, 1, 1), 0, 15368 "#include \"b.h\"\n")}); 15369 15370 format::FormatStyle Style = format::getLLVMStyle(); 15371 Style.SortIncludes = true; 15372 auto FormattedReplaces = formatReplacements(Code, Replaces, Style); 15373 EXPECT_TRUE(static_cast<bool>(FormattedReplaces)) 15374 << llvm::toString(FormattedReplaces.takeError()) << "\n"; 15375 auto Result = applyAllReplacements(Code, *FormattedReplaces); 15376 EXPECT_TRUE(static_cast<bool>(Result)); 15377 EXPECT_EQ(Expected, *Result); 15378 } 15379 15380 TEST_F(FormatTest, FormatSortsUsingDeclarations) { 15381 EXPECT_EQ("using std::cin;\n" 15382 "using std::cout;", 15383 format("using std::cout;\n" 15384 "using std::cin;", 15385 getGoogleStyle())); 15386 } 15387 15388 TEST_F(FormatTest, UTF8CharacterLiteralCpp03) { 15389 format::FormatStyle Style = format::getLLVMStyle(); 15390 Style.Standard = FormatStyle::LS_Cpp03; 15391 // cpp03 recognize this string as identifier u8 and literal character 'a' 15392 EXPECT_EQ("auto c = u8 'a';", format("auto c = u8'a';", Style)); 15393 } 15394 15395 TEST_F(FormatTest, UTF8CharacterLiteralCpp11) { 15396 // u8'a' is a C++17 feature, utf8 literal character, LS_Cpp11 covers 15397 // all modes, including C++11, C++14 and C++17 15398 EXPECT_EQ("auto c = u8'a';", format("auto c = u8'a';")); 15399 } 15400 15401 TEST_F(FormatTest, DoNotFormatLikelyXml) { 15402 EXPECT_EQ("<!-- ;> -->", format("<!-- ;> -->", getGoogleStyle())); 15403 EXPECT_EQ(" <!-- >; -->", format(" <!-- >; -->", getGoogleStyle())); 15404 } 15405 15406 TEST_F(FormatTest, StructuredBindings) { 15407 // Structured bindings is a C++17 feature. 15408 // all modes, including C++11, C++14 and C++17 15409 verifyFormat("auto [a, b] = f();"); 15410 EXPECT_EQ("auto [a, b] = f();", format("auto[a, b] = f();")); 15411 EXPECT_EQ("const auto [a, b] = f();", format("const auto[a, b] = f();")); 15412 EXPECT_EQ("auto const [a, b] = f();", format("auto const[a, b] = f();")); 15413 EXPECT_EQ("auto const volatile [a, b] = f();", 15414 format("auto const volatile[a, b] = f();")); 15415 EXPECT_EQ("auto [a, b, c] = f();", format("auto [ a , b,c ] = f();")); 15416 EXPECT_EQ("auto &[a, b, c] = f();", 15417 format("auto &[ a , b,c ] = f();")); 15418 EXPECT_EQ("auto &&[a, b, c] = f();", 15419 format("auto &&[ a , b,c ] = f();")); 15420 EXPECT_EQ("auto const &[a, b] = f();", format("auto const&[a, b] = f();")); 15421 EXPECT_EQ("auto const volatile &&[a, b] = f();", 15422 format("auto const volatile &&[a, b] = f();")); 15423 EXPECT_EQ("auto const &&[a, b] = f();", 15424 format("auto const && [a, b] = f();")); 15425 EXPECT_EQ("const auto &[a, b] = f();", 15426 format("const auto & [a, b] = f();")); 15427 EXPECT_EQ("const auto volatile &&[a, b] = f();", 15428 format("const auto volatile &&[a, b] = f();")); 15429 EXPECT_EQ("volatile const auto &&[a, b] = f();", 15430 format("volatile const auto &&[a, b] = f();")); 15431 EXPECT_EQ("const auto &&[a, b] = f();", 15432 format("const auto && [a, b] = f();")); 15433 15434 // Make sure we don't mistake structured bindings for lambdas. 15435 FormatStyle PointerMiddle = getLLVMStyle(); 15436 PointerMiddle.PointerAlignment = FormatStyle::PAS_Middle; 15437 verifyFormat("auto [a1, b]{A * i};", getGoogleStyle()); 15438 verifyFormat("auto [a2, b]{A * i};", getLLVMStyle()); 15439 verifyFormat("auto [a3, b]{A * i};", PointerMiddle); 15440 verifyFormat("auto const [a1, b]{A * i};", getGoogleStyle()); 15441 verifyFormat("auto const [a2, b]{A * i};", getLLVMStyle()); 15442 verifyFormat("auto const [a3, b]{A * i};", PointerMiddle); 15443 verifyFormat("auto const& [a1, b]{A * i};", getGoogleStyle()); 15444 verifyFormat("auto const &[a2, b]{A * i};", getLLVMStyle()); 15445 verifyFormat("auto const & [a3, b]{A * i};", PointerMiddle); 15446 verifyFormat("auto const&& [a1, b]{A * i};", getGoogleStyle()); 15447 verifyFormat("auto const &&[a2, b]{A * i};", getLLVMStyle()); 15448 verifyFormat("auto const && [a3, b]{A * i};", PointerMiddle); 15449 15450 EXPECT_EQ("for (const auto &&[a, b] : some_range) {\n}", 15451 format("for (const auto && [a, b] : some_range) {\n}")); 15452 EXPECT_EQ("for (const auto &[a, b] : some_range) {\n}", 15453 format("for (const auto & [a, b] : some_range) {\n}")); 15454 EXPECT_EQ("for (const auto [a, b] : some_range) {\n}", 15455 format("for (const auto[a, b] : some_range) {\n}")); 15456 EXPECT_EQ("auto [x, y](expr);", format("auto[x,y] (expr);")); 15457 EXPECT_EQ("auto &[x, y](expr);", format("auto & [x,y] (expr);")); 15458 EXPECT_EQ("auto &&[x, y](expr);", format("auto && [x,y] (expr);")); 15459 EXPECT_EQ("auto const &[x, y](expr);", 15460 format("auto const & [x,y] (expr);")); 15461 EXPECT_EQ("auto const &&[x, y](expr);", 15462 format("auto const && [x,y] (expr);")); 15463 EXPECT_EQ("auto [x, y]{expr};", format("auto[x,y] {expr};")); 15464 EXPECT_EQ("auto const &[x, y]{expr};", 15465 format("auto const & [x,y] {expr};")); 15466 EXPECT_EQ("auto const &&[x, y]{expr};", 15467 format("auto const && [x,y] {expr};")); 15468 15469 format::FormatStyle Spaces = format::getLLVMStyle(); 15470 Spaces.SpacesInSquareBrackets = true; 15471 verifyFormat("auto [ a, b ] = f();", Spaces); 15472 verifyFormat("auto &&[ a, b ] = f();", Spaces); 15473 verifyFormat("auto &[ a, b ] = f();", Spaces); 15474 verifyFormat("auto const &&[ a, b ] = f();", Spaces); 15475 verifyFormat("auto const &[ a, b ] = f();", Spaces); 15476 } 15477 15478 TEST_F(FormatTest, FileAndCode) { 15479 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.cc", "")); 15480 EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.m", "")); 15481 EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.mm", "")); 15482 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "")); 15483 EXPECT_EQ(FormatStyle::LK_ObjC, 15484 guessLanguage("foo.h", "@interface Foo\n@end\n")); 15485 EXPECT_EQ( 15486 FormatStyle::LK_ObjC, 15487 guessLanguage("foo.h", "#define TRY(x, y) @try { x; } @finally { y; }")); 15488 EXPECT_EQ(FormatStyle::LK_ObjC, 15489 guessLanguage("foo.h", "#define AVAIL(x) @available(x, *))")); 15490 EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.h", "@class Foo;")); 15491 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo", "")); 15492 EXPECT_EQ(FormatStyle::LK_ObjC, 15493 guessLanguage("foo", "@interface Foo\n@end\n")); 15494 EXPECT_EQ(FormatStyle::LK_ObjC, 15495 guessLanguage("foo.h", "int DoStuff(CGRect rect);\n")); 15496 EXPECT_EQ( 15497 FormatStyle::LK_ObjC, 15498 guessLanguage("foo.h", 15499 "#define MY_POINT_MAKE(x, y) CGPointMake((x), (y));\n")); 15500 EXPECT_EQ( 15501 FormatStyle::LK_Cpp, 15502 guessLanguage("foo.h", "#define FOO(...) auto bar = [] __VA_ARGS__;")); 15503 } 15504 15505 TEST_F(FormatTest, GuessLanguageWithCpp11AttributeSpecifiers) { 15506 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "[[noreturn]];")); 15507 EXPECT_EQ(FormatStyle::LK_ObjC, 15508 guessLanguage("foo.h", "array[[calculator getIndex]];")); 15509 EXPECT_EQ(FormatStyle::LK_Cpp, 15510 guessLanguage("foo.h", "[[noreturn, deprecated(\"so sorry\")]];")); 15511 EXPECT_EQ( 15512 FormatStyle::LK_Cpp, 15513 guessLanguage("foo.h", "[[noreturn, deprecated(\"gone, sorry\")]];")); 15514 EXPECT_EQ(FormatStyle::LK_ObjC, 15515 guessLanguage("foo.h", "[[noreturn foo] bar];")); 15516 EXPECT_EQ(FormatStyle::LK_Cpp, 15517 guessLanguage("foo.h", "[[clang::fallthrough]];")); 15518 EXPECT_EQ(FormatStyle::LK_ObjC, 15519 guessLanguage("foo.h", "[[clang:fallthrough] foo];")); 15520 EXPECT_EQ(FormatStyle::LK_Cpp, 15521 guessLanguage("foo.h", "[[gsl::suppress(\"type\")]];")); 15522 EXPECT_EQ(FormatStyle::LK_Cpp, 15523 guessLanguage("foo.h", "[[using clang: fallthrough]];")); 15524 EXPECT_EQ(FormatStyle::LK_ObjC, 15525 guessLanguage("foo.h", "[[abusing clang:fallthrough] bar];")); 15526 EXPECT_EQ(FormatStyle::LK_Cpp, 15527 guessLanguage("foo.h", "[[using gsl: suppress(\"type\")]];")); 15528 EXPECT_EQ( 15529 FormatStyle::LK_Cpp, 15530 guessLanguage("foo.h", "for (auto &&[endpoint, stream] : streams_)")); 15531 EXPECT_EQ( 15532 FormatStyle::LK_Cpp, 15533 guessLanguage("foo.h", 15534 "[[clang::callable_when(\"unconsumed\", \"unknown\")]]")); 15535 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "[[foo::bar, ...]]")); 15536 } 15537 15538 TEST_F(FormatTest, GuessLanguageWithCaret) { 15539 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "FOO(^);")); 15540 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "FOO(^, Bar);")); 15541 EXPECT_EQ(FormatStyle::LK_ObjC, 15542 guessLanguage("foo.h", "int(^)(char, float);")); 15543 EXPECT_EQ(FormatStyle::LK_ObjC, 15544 guessLanguage("foo.h", "int(^foo)(char, float);")); 15545 EXPECT_EQ(FormatStyle::LK_ObjC, 15546 guessLanguage("foo.h", "int(^foo[10])(char, float);")); 15547 EXPECT_EQ(FormatStyle::LK_ObjC, 15548 guessLanguage("foo.h", "int(^foo[kNumEntries])(char, float);")); 15549 EXPECT_EQ( 15550 FormatStyle::LK_ObjC, 15551 guessLanguage("foo.h", "int(^foo[(kNumEntries + 10)])(char, float);")); 15552 } 15553 15554 TEST_F(FormatTest, FormatsInlineAsmSymbolicNames) { 15555 // ASM symbolic names are identifiers that must be surrounded by [] without 15556 // space in between: 15557 // https://gcc.gnu.org/onlinedocs/gcc/Extended-Asm.html#InputOperands 15558 15559 // Example from https://bugs.llvm.org/show_bug.cgi?id=45108. 15560 verifyFormat(R"(// 15561 asm volatile("mrs %x[result], FPCR" : [result] "=r"(result)); 15562 )"); 15563 15564 // A list of several ASM symbolic names. 15565 verifyFormat(R"(asm("mov %[e], %[d]" : [d] "=rm"(d), [e] "rm"(*e));)"); 15566 15567 // ASM symbolic names in inline ASM with inputs and outputs. 15568 verifyFormat(R"(// 15569 asm("cmoveq %1, %2, %[result]" 15570 : [result] "=r"(result) 15571 : "r"(test), "r"(new), "[result]"(old)); 15572 )"); 15573 15574 // ASM symbolic names in inline ASM with no outputs. 15575 verifyFormat(R"(asm("mov %[e], %[d]" : : [d] "=rm"(d), [e] "rm"(*e));)"); 15576 } 15577 15578 TEST_F(FormatTest, GuessedLanguageWithInlineAsmClobbers) { 15579 EXPECT_EQ(FormatStyle::LK_Cpp, 15580 guessLanguage("foo.h", "void f() {\n" 15581 " asm (\"mov %[e], %[d]\"\n" 15582 " : [d] \"=rm\" (d)\n" 15583 " [e] \"rm\" (*e));\n" 15584 "}")); 15585 EXPECT_EQ(FormatStyle::LK_Cpp, 15586 guessLanguage("foo.h", "void f() {\n" 15587 " _asm (\"mov %[e], %[d]\"\n" 15588 " : [d] \"=rm\" (d)\n" 15589 " [e] \"rm\" (*e));\n" 15590 "}")); 15591 EXPECT_EQ(FormatStyle::LK_Cpp, 15592 guessLanguage("foo.h", "void f() {\n" 15593 " __asm (\"mov %[e], %[d]\"\n" 15594 " : [d] \"=rm\" (d)\n" 15595 " [e] \"rm\" (*e));\n" 15596 "}")); 15597 EXPECT_EQ(FormatStyle::LK_Cpp, 15598 guessLanguage("foo.h", "void f() {\n" 15599 " __asm__ (\"mov %[e], %[d]\"\n" 15600 " : [d] \"=rm\" (d)\n" 15601 " [e] \"rm\" (*e));\n" 15602 "}")); 15603 EXPECT_EQ(FormatStyle::LK_Cpp, 15604 guessLanguage("foo.h", "void f() {\n" 15605 " asm (\"mov %[e], %[d]\"\n" 15606 " : [d] \"=rm\" (d),\n" 15607 " [e] \"rm\" (*e));\n" 15608 "}")); 15609 EXPECT_EQ(FormatStyle::LK_Cpp, 15610 guessLanguage("foo.h", "void f() {\n" 15611 " asm volatile (\"mov %[e], %[d]\"\n" 15612 " : [d] \"=rm\" (d)\n" 15613 " [e] \"rm\" (*e));\n" 15614 "}")); 15615 } 15616 15617 TEST_F(FormatTest, GuessLanguageWithChildLines) { 15618 EXPECT_EQ(FormatStyle::LK_Cpp, 15619 guessLanguage("foo.h", "#define FOO ({ std::string s; })")); 15620 EXPECT_EQ(FormatStyle::LK_ObjC, 15621 guessLanguage("foo.h", "#define FOO ({ NSString *s; })")); 15622 EXPECT_EQ( 15623 FormatStyle::LK_Cpp, 15624 guessLanguage("foo.h", "#define FOO ({ foo(); ({ std::string s; }) })")); 15625 EXPECT_EQ( 15626 FormatStyle::LK_ObjC, 15627 guessLanguage("foo.h", "#define FOO ({ foo(); ({ NSString *s; }) })")); 15628 } 15629 15630 TEST_F(FormatTest, TypenameMacros) { 15631 std::vector<std::string> TypenameMacros = {"STACK_OF", "LIST", "TAILQ_ENTRY"}; 15632 15633 // Test case reported in https://bugs.llvm.org/show_bug.cgi?id=30353 15634 FormatStyle Google = getGoogleStyleWithColumns(0); 15635 Google.TypenameMacros = TypenameMacros; 15636 verifyFormat("struct foo {\n" 15637 " int bar;\n" 15638 " TAILQ_ENTRY(a) bleh;\n" 15639 "};", 15640 Google); 15641 15642 FormatStyle Macros = getLLVMStyle(); 15643 Macros.TypenameMacros = TypenameMacros; 15644 15645 verifyFormat("STACK_OF(int) a;", Macros); 15646 verifyFormat("STACK_OF(int) *a;", Macros); 15647 verifyFormat("STACK_OF(int const *) *a;", Macros); 15648 verifyFormat("STACK_OF(int *const) *a;", Macros); 15649 verifyFormat("STACK_OF(int, string) a;", Macros); 15650 verifyFormat("STACK_OF(LIST(int)) a;", Macros); 15651 verifyFormat("STACK_OF(LIST(int)) a, b;", Macros); 15652 verifyFormat("for (LIST(int) *a = NULL; a;) {\n}", Macros); 15653 verifyFormat("STACK_OF(int) f(LIST(int) *arg);", Macros); 15654 15655 Macros.PointerAlignment = FormatStyle::PAS_Left; 15656 verifyFormat("STACK_OF(int)* a;", Macros); 15657 verifyFormat("STACK_OF(int*)* a;", Macros); 15658 } 15659 15660 TEST_F(FormatTest, AmbersandInLamda) { 15661 // Test case reported in https://bugs.llvm.org/show_bug.cgi?id=41899 15662 FormatStyle AlignStyle = getLLVMStyle(); 15663 AlignStyle.PointerAlignment = FormatStyle::PAS_Left; 15664 verifyFormat("auto lambda = [&a = a]() { a = 2; };", AlignStyle); 15665 AlignStyle.PointerAlignment = FormatStyle::PAS_Right; 15666 verifyFormat("auto lambda = [&a = a]() { a = 2; };", AlignStyle); 15667 } 15668 15669 TEST_F(FormatTest, SpacesInConditionalStatement) { 15670 FormatStyle Spaces = getLLVMStyle(); 15671 Spaces.SpacesInConditionalStatement = true; 15672 verifyFormat("for ( int i = 0; i; i++ )\n continue;", Spaces); 15673 verifyFormat("if ( !a )\n return;", Spaces); 15674 verifyFormat("if ( a )\n return;", Spaces); 15675 verifyFormat("if constexpr ( a )\n return;", Spaces); 15676 verifyFormat("switch ( a )\ncase 1:\n return;", Spaces); 15677 verifyFormat("while ( a )\n return;", Spaces); 15678 verifyFormat("while ( (a && b) )\n return;", Spaces); 15679 verifyFormat("do {\n} while ( 1 != 0 );", Spaces); 15680 verifyFormat("try {\n} catch ( const std::exception & ) {\n}", Spaces); 15681 // Check that space on the left of "::" is inserted as expected at beginning 15682 // of condition. 15683 verifyFormat("while ( ::func() )\n return;", Spaces); 15684 } 15685 15686 TEST_F(FormatTest, AlternativeOperators) { 15687 // Test case for ensuring alternate operators are not 15688 // combined with their right most neighbour. 15689 verifyFormat("int a and b;"); 15690 verifyFormat("int a and_eq b;"); 15691 verifyFormat("int a bitand b;"); 15692 verifyFormat("int a bitor b;"); 15693 verifyFormat("int a compl b;"); 15694 verifyFormat("int a not b;"); 15695 verifyFormat("int a not_eq b;"); 15696 verifyFormat("int a or b;"); 15697 verifyFormat("int a xor b;"); 15698 verifyFormat("int a xor_eq b;"); 15699 verifyFormat("return this not_eq bitand other;"); 15700 verifyFormat("bool operator not_eq(const X bitand other)"); 15701 15702 verifyFormat("int a and 5;"); 15703 verifyFormat("int a and_eq 5;"); 15704 verifyFormat("int a bitand 5;"); 15705 verifyFormat("int a bitor 5;"); 15706 verifyFormat("int a compl 5;"); 15707 verifyFormat("int a not 5;"); 15708 verifyFormat("int a not_eq 5;"); 15709 verifyFormat("int a or 5;"); 15710 verifyFormat("int a xor 5;"); 15711 verifyFormat("int a xor_eq 5;"); 15712 15713 verifyFormat("int a compl(5);"); 15714 verifyFormat("int a not(5);"); 15715 15716 /* FIXME handle alternate tokens 15717 * https://en.cppreference.com/w/cpp/language/operator_alternative 15718 // alternative tokens 15719 verifyFormat("compl foo();"); // ~foo(); 15720 verifyFormat("foo() <%%>;"); // foo(); 15721 verifyFormat("void foo() <%%>;"); // void foo(){} 15722 verifyFormat("int a <:1:>;"); // int a[1];[ 15723 verifyFormat("%:define ABC abc"); // #define ABC abc 15724 verifyFormat("%:%:"); // ## 15725 */ 15726 } 15727 15728 TEST_F(FormatTest, STLWhileNotDefineChed) { 15729 verifyFormat("#if defined(while)\n" 15730 "#define while EMIT WARNING C4005\n" 15731 "#endif // while"); 15732 } 15733 15734 TEST_F(FormatTest, OperatorSpacing) { 15735 FormatStyle Style = getLLVMStyle(); 15736 Style.PointerAlignment = FormatStyle::PAS_Right; 15737 verifyFormat("Foo::operator*();", Style); 15738 verifyFormat("Foo::operator void *();", Style); 15739 verifyFormat("Foo::operator void **();", Style); 15740 verifyFormat("Foo::operator()(void *);", Style); 15741 verifyFormat("Foo::operator*(void *);", Style); 15742 verifyFormat("Foo::operator*();", Style); 15743 verifyFormat("Foo::operator**();", Style); 15744 verifyFormat("Foo::operator&();", Style); 15745 verifyFormat("Foo::operator<int> *();", Style); 15746 verifyFormat("Foo::operator<Foo> *();", Style); 15747 verifyFormat("Foo::operator<int> **();", Style); 15748 verifyFormat("Foo::operator<Foo> **();", Style); 15749 verifyFormat("Foo::operator<int> &();", Style); 15750 verifyFormat("Foo::operator<Foo> &();", Style); 15751 verifyFormat("Foo::operator<int> &&();", Style); 15752 verifyFormat("Foo::operator<Foo> &&();", Style); 15753 verifyFormat("operator*(int (*)(), class Foo);", Style); 15754 15755 verifyFormat("Foo::operator&();", Style); 15756 verifyFormat("Foo::operator void &();", Style); 15757 verifyFormat("Foo::operator()(void &);", Style); 15758 verifyFormat("Foo::operator&(void &);", Style); 15759 verifyFormat("Foo::operator&();", Style); 15760 verifyFormat("operator&(int (&)(), class Foo);", Style); 15761 15762 verifyFormat("Foo::operator&&();", Style); 15763 verifyFormat("Foo::operator**();", Style); 15764 verifyFormat("Foo::operator void &&();", Style); 15765 verifyFormat("Foo::operator()(void &&);", Style); 15766 verifyFormat("Foo::operator&&(void &&);", Style); 15767 verifyFormat("Foo::operator&&();", Style); 15768 verifyFormat("operator&&(int(&&)(), class Foo);", Style); 15769 verifyFormat("operator const nsTArrayRight<E> &()", Style); 15770 verifyFormat("[[nodiscard]] operator const nsTArrayRight<E, Allocator> &()", 15771 Style); 15772 verifyFormat("operator void **()", Style); 15773 verifyFormat("operator const FooRight<Object> &()", Style); 15774 verifyFormat("operator const FooRight<Object> *()", Style); 15775 verifyFormat("operator const FooRight<Object> **()", Style); 15776 15777 Style.PointerAlignment = FormatStyle::PAS_Left; 15778 verifyFormat("Foo::operator*();", Style); 15779 verifyFormat("Foo::operator**();", Style); 15780 verifyFormat("Foo::operator void*();", Style); 15781 verifyFormat("Foo::operator void**();", Style); 15782 verifyFormat("Foo::operator/*comment*/ void*();", Style); 15783 verifyFormat("Foo::operator/*a*/ const /*b*/ void*();", Style); 15784 verifyFormat("Foo::operator/*a*/ volatile /*b*/ void*();", Style); 15785 verifyFormat("Foo::operator()(void*);", Style); 15786 verifyFormat("Foo::operator*(void*);", Style); 15787 verifyFormat("Foo::operator*();", Style); 15788 verifyFormat("Foo::operator<int>*();", Style); 15789 verifyFormat("Foo::operator<Foo>*();", Style); 15790 verifyFormat("Foo::operator<int>**();", Style); 15791 verifyFormat("Foo::operator<Foo>**();", Style); 15792 verifyFormat("Foo::operator<int>&();", Style); 15793 verifyFormat("Foo::operator<Foo>&();", Style); 15794 verifyFormat("Foo::operator<int>&&();", Style); 15795 verifyFormat("Foo::operator<Foo>&&();", Style); 15796 verifyFormat("operator*(int (*)(), class Foo);", Style); 15797 15798 verifyFormat("Foo::operator&();", Style); 15799 verifyFormat("Foo::operator void&();", Style); 15800 verifyFormat("Foo::operator/*comment*/ void&();", Style); 15801 verifyFormat("Foo::operator/*a*/ const /*b*/ void&();", Style); 15802 verifyFormat("Foo::operator/*a*/ volatile /*b*/ void&();", Style); 15803 verifyFormat("Foo::operator()(void&);", Style); 15804 verifyFormat("Foo::operator&(void&);", Style); 15805 verifyFormat("Foo::operator&();", Style); 15806 verifyFormat("operator&(int (&)(), class Foo);", Style); 15807 15808 verifyFormat("Foo::operator&&();", Style); 15809 verifyFormat("Foo::operator void&&();", Style); 15810 verifyFormat("Foo::operator/*comment*/ void&&();", Style); 15811 verifyFormat("Foo::operator/*a*/ const /*b*/ void&&();", Style); 15812 verifyFormat("Foo::operator/*a*/ volatile /*b*/ void&&();", Style); 15813 verifyFormat("Foo::operator()(void&&);", Style); 15814 verifyFormat("Foo::operator&&(void&&);", Style); 15815 verifyFormat("Foo::operator&&();", Style); 15816 verifyFormat("operator&&(int(&&)(), class Foo);", Style); 15817 verifyFormat("operator const nsTArrayLeft<E>&()", Style); 15818 verifyFormat("[[nodiscard]] operator const nsTArrayLeft<E, Allocator>&()", 15819 Style); 15820 verifyFormat("operator void**()", Style); 15821 verifyFormat("operator const FooLeft<Object>&()", Style); 15822 verifyFormat("operator const FooLeft<Object>*()", Style); 15823 verifyFormat("operator const FooLeft<Object>**()", Style); 15824 15825 // PR45107 15826 verifyFormat("operator Vector<String>&();", Style); 15827 verifyFormat("operator const Vector<String>&();", Style); 15828 verifyFormat("operator foo::Bar*();", Style); 15829 verifyFormat("operator const Foo<X>::Bar<Y>*();", Style); 15830 verifyFormat("operator/*a*/ const /*b*/ Foo /*c*/<X> /*d*/ ::Bar<Y>*();", 15831 Style); 15832 15833 Style.PointerAlignment = FormatStyle::PAS_Middle; 15834 verifyFormat("Foo::operator*();", Style); 15835 verifyFormat("Foo::operator void *();", Style); 15836 verifyFormat("Foo::operator()(void *);", Style); 15837 verifyFormat("Foo::operator*(void *);", Style); 15838 verifyFormat("Foo::operator*();", Style); 15839 verifyFormat("operator*(int (*)(), class Foo);", Style); 15840 15841 verifyFormat("Foo::operator&();", Style); 15842 verifyFormat("Foo::operator void &();", Style); 15843 verifyFormat("Foo::operator()(void &);", Style); 15844 verifyFormat("Foo::operator&(void &);", Style); 15845 verifyFormat("Foo::operator&();", Style); 15846 verifyFormat("operator&(int (&)(), class Foo);", Style); 15847 15848 verifyFormat("Foo::operator&&();", Style); 15849 verifyFormat("Foo::operator void &&();", Style); 15850 verifyFormat("Foo::operator()(void &&);", Style); 15851 verifyFormat("Foo::operator&&(void &&);", Style); 15852 verifyFormat("Foo::operator&&();", Style); 15853 verifyFormat("operator&&(int(&&)(), class Foo);", Style); 15854 } 15855 15856 } // namespace 15857 } // namespace format 15858 } // namespace clang 15859