1 //===--- Format.h - Format C++ code -----------------------------*- C++ -*-===// 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 /// \file 10 /// Various functions to configurably format source code. 11 /// 12 //===----------------------------------------------------------------------===// 13 14 #ifndef LLVM_CLANG_FORMAT_FORMAT_H 15 #define LLVM_CLANG_FORMAT_FORMAT_H 16 17 #include "clang/Basic/LangOptions.h" 18 #include "clang/Tooling/Core/Replacement.h" 19 #include "clang/Tooling/Inclusions/IncludeStyle.h" 20 #include "llvm/ADT/ArrayRef.h" 21 #include "llvm/Support/Regex.h" 22 #include <system_error> 23 24 namespace llvm { 25 namespace vfs { 26 class FileSystem; 27 } 28 } // namespace llvm 29 30 namespace clang { 31 32 class Lexer; 33 class SourceManager; 34 class DiagnosticConsumer; 35 36 namespace format { 37 38 enum class ParseError { 39 Success = 0, 40 Error, 41 Unsuitable, 42 BinPackTrailingCommaConflict 43 }; 44 class ParseErrorCategory final : public std::error_category { 45 public: 46 const char *name() const noexcept override; 47 std::string message(int EV) const override; 48 }; 49 const std::error_category &getParseCategory(); 50 std::error_code make_error_code(ParseError e); 51 52 /// The ``FormatStyle`` is used to configure the formatting to follow 53 /// specific guidelines. 54 struct FormatStyle { 55 /// The extra indent or outdent of access modifiers, e.g. ``public:``. 56 int AccessModifierOffset; 57 58 /// Different styles for aligning after open brackets. 59 enum BracketAlignmentStyle { 60 /// Align parameters on the open bracket, e.g.: 61 /// \code 62 /// someLongFunction(argument1, 63 /// argument2); 64 /// \endcode 65 BAS_Align, 66 /// Don't align, instead use ``ContinuationIndentWidth``, e.g.: 67 /// \code 68 /// someLongFunction(argument1, 69 /// argument2); 70 /// \endcode 71 BAS_DontAlign, 72 /// Always break after an open bracket, if the parameters don't fit 73 /// on a single line, e.g.: 74 /// \code 75 /// someLongFunction( 76 /// argument1, argument2); 77 /// \endcode 78 BAS_AlwaysBreak, 79 }; 80 81 /// If ``true``, horizontally aligns arguments after an open bracket. 82 /// 83 /// This applies to round brackets (parentheses), angle brackets and square 84 /// brackets. 85 BracketAlignmentStyle AlignAfterOpenBracket; 86 87 /// \brief If ``true``, aligns consecutive C/C++ preprocessor macros. 88 /// 89 /// This will align C/C++ preprocessor macros of consecutive lines. 90 /// Will result in formattings like 91 /// \code 92 /// #define SHORT_NAME 42 93 /// #define LONGER_NAME 0x007f 94 /// #define EVEN_LONGER_NAME (2) 95 /// #define foo(x) (x * x) 96 /// #define bar(y, z) (y + z) 97 /// \endcode 98 bool AlignConsecutiveMacros; 99 100 /// If ``true``, aligns consecutive assignments. 101 /// 102 /// This will align the assignment operators of consecutive lines. This 103 /// will result in formattings like 104 /// \code 105 /// int aaaa = 12; 106 /// int b = 23; 107 /// int ccc = 23; 108 /// \endcode 109 bool AlignConsecutiveAssignments; 110 111 /// If ``true``, aligns consecutive bitfield members. 112 /// 113 /// This will align the bitfield separators of consecutive lines. This 114 /// will result in formattings like 115 /// \code 116 /// int aaaa : 1; 117 /// int b : 12; 118 /// int ccc : 8; 119 /// \endcode 120 bool AlignConsecutiveBitFields; 121 122 /// If ``true``, aligns consecutive declarations. 123 /// 124 /// This will align the declaration names of consecutive lines. This 125 /// will result in formattings like 126 /// \code 127 /// int aaaa = 12; 128 /// float b = 23; 129 /// std::string ccc = 23; 130 /// \endcode 131 bool AlignConsecutiveDeclarations; 132 133 /// Different styles for aligning escaped newlines. 134 enum EscapedNewlineAlignmentStyle { 135 /// Don't align escaped newlines. 136 /// \code 137 /// #define A \ 138 /// int aaaa; \ 139 /// int b; \ 140 /// int dddddddddd; 141 /// \endcode 142 ENAS_DontAlign, 143 /// Align escaped newlines as far left as possible. 144 /// \code 145 /// true: 146 /// #define A \ 147 /// int aaaa; \ 148 /// int b; \ 149 /// int dddddddddd; 150 /// 151 /// false: 152 /// \endcode 153 ENAS_Left, 154 /// Align escaped newlines in the right-most column. 155 /// \code 156 /// #define A \ 157 /// int aaaa; \ 158 /// int b; \ 159 /// int dddddddddd; 160 /// \endcode 161 ENAS_Right, 162 }; 163 164 /// Options for aligning backslashes in escaped newlines. 165 EscapedNewlineAlignmentStyle AlignEscapedNewlines; 166 167 /// Different styles for aligning operands. 168 enum OperandAlignmentStyle { 169 /// Do not align operands of binary and ternary expressions. 170 /// The wrapped lines are indented ``ContinuationIndentWidth`` spaces from 171 /// the start of the line. 172 OAS_DontAlign, 173 /// Horizontally align operands of binary and ternary expressions. 174 /// 175 /// Specifically, this aligns operands of a single expression that needs 176 /// to be split over multiple lines, e.g.: 177 /// \code 178 /// int aaa = bbbbbbbbbbbbbbb + 179 /// ccccccccccccccc; 180 /// \endcode 181 /// 182 /// When ``BreakBeforeBinaryOperators`` is set, the wrapped operator is 183 /// aligned with the operand on the first line. 184 /// \code 185 /// int aaa = bbbbbbbbbbbbbbb 186 /// + ccccccccccccccc; 187 /// \endcode 188 OAS_Align, 189 /// Horizontally align operands of binary and ternary expressions. 190 /// 191 /// This is similar to ``AO_Align``, except when 192 /// ``BreakBeforeBinaryOperators`` is set, the operator is un-indented so 193 /// that the wrapped operand is aligned with the operand on the first line. 194 /// \code 195 /// int aaa = bbbbbbbbbbbbbbb 196 /// + ccccccccccccccc; 197 /// \endcode 198 OAS_AlignAfterOperator, 199 }; 200 201 /// If ``true``, horizontally align operands of binary and ternary 202 /// expressions. 203 OperandAlignmentStyle AlignOperands; 204 205 /// If ``true``, aligns trailing comments. 206 /// \code 207 /// true: false: 208 /// int a; // My comment a vs. int a; // My comment a 209 /// int b = 2; // comment b int b = 2; // comment about b 210 /// \endcode 211 bool AlignTrailingComments; 212 213 /// \brief If a function call or braced initializer list doesn't fit on a 214 /// line, allow putting all arguments onto the next line, even if 215 /// ``BinPackArguments`` is ``false``. 216 /// \code 217 /// true: 218 /// callFunction( 219 /// a, b, c, d); 220 /// 221 /// false: 222 /// callFunction(a, 223 /// b, 224 /// c, 225 /// d); 226 /// \endcode 227 bool AllowAllArgumentsOnNextLine; 228 229 /// \brief If a constructor definition with a member initializer list doesn't 230 /// fit on a single line, allow putting all member initializers onto the next 231 /// line, if ```ConstructorInitializerAllOnOneLineOrOnePerLine``` is true. 232 /// Note that this parameter has no effect if 233 /// ```ConstructorInitializerAllOnOneLineOrOnePerLine``` is false. 234 /// \code 235 /// true: 236 /// MyClass::MyClass() : 237 /// member0(0), member1(2) {} 238 /// 239 /// false: 240 /// MyClass::MyClass() : 241 /// member0(0), 242 /// member1(2) {} 243 bool AllowAllConstructorInitializersOnNextLine; 244 245 /// If the function declaration doesn't fit on a line, 246 /// allow putting all parameters of a function declaration onto 247 /// the next line even if ``BinPackParameters`` is ``false``. 248 /// \code 249 /// true: 250 /// void myFunction( 251 /// int a, int b, int c, int d, int e); 252 /// 253 /// false: 254 /// void myFunction(int a, 255 /// int b, 256 /// int c, 257 /// int d, 258 /// int e); 259 /// \endcode 260 bool AllowAllParametersOfDeclarationOnNextLine; 261 262 /// Allow short enums on a single line. 263 /// \code 264 /// true: 265 /// enum { A, B } myEnum; 266 /// 267 /// false: 268 /// enum 269 /// { 270 /// A, 271 /// B 272 /// } myEnum; 273 /// \endcode 274 bool AllowShortEnumsOnASingleLine; 275 276 /// Different styles for merging short blocks containing at most one 277 /// statement. 278 enum ShortBlockStyle { 279 /// Never merge blocks into a single line. 280 /// \code 281 /// while (true) { 282 /// } 283 /// while (true) { 284 /// continue; 285 /// } 286 /// \endcode 287 SBS_Never, 288 /// Only merge empty blocks. 289 /// \code 290 /// while (true) {} 291 /// while (true) { 292 /// continue; 293 /// } 294 /// \endcode 295 SBS_Empty, 296 /// Always merge short blocks into a single line. 297 /// \code 298 /// while (true) {} 299 /// while (true) { continue; } 300 /// \endcode 301 SBS_Always, 302 }; 303 304 /// Dependent on the value, ``while (true) { continue; }`` can be put on a 305 /// single line. 306 ShortBlockStyle AllowShortBlocksOnASingleLine; 307 308 /// If ``true``, short case labels will be contracted to a single line. 309 /// \code 310 /// true: false: 311 /// switch (a) { vs. switch (a) { 312 /// case 1: x = 1; break; case 1: 313 /// case 2: return; x = 1; 314 /// } break; 315 /// case 2: 316 /// return; 317 /// } 318 /// \endcode 319 bool AllowShortCaseLabelsOnASingleLine; 320 321 /// Different styles for merging short functions containing at most one 322 /// statement. 323 enum ShortFunctionStyle { 324 /// Never merge functions into a single line. 325 SFS_None, 326 /// Only merge functions defined inside a class. Same as "inline", 327 /// except it does not implies "empty": i.e. top level empty functions 328 /// are not merged either. 329 /// \code 330 /// class Foo { 331 /// void f() { foo(); } 332 /// }; 333 /// void f() { 334 /// foo(); 335 /// } 336 /// void f() { 337 /// } 338 /// \endcode 339 SFS_InlineOnly, 340 /// Only merge empty functions. 341 /// \code 342 /// void f() {} 343 /// void f2() { 344 /// bar2(); 345 /// } 346 /// \endcode 347 SFS_Empty, 348 /// Only merge functions defined inside a class. Implies "empty". 349 /// \code 350 /// class Foo { 351 /// void f() { foo(); } 352 /// }; 353 /// void f() { 354 /// foo(); 355 /// } 356 /// void f() {} 357 /// \endcode 358 SFS_Inline, 359 /// Merge all functions fitting on a single line. 360 /// \code 361 /// class Foo { 362 /// void f() { foo(); } 363 /// }; 364 /// void f() { bar(); } 365 /// \endcode 366 SFS_All, 367 }; 368 369 /// Dependent on the value, ``int f() { return 0; }`` can be put on a 370 /// single line. 371 ShortFunctionStyle AllowShortFunctionsOnASingleLine; 372 373 /// Different styles for handling short if lines 374 enum ShortIfStyle { 375 /// Never put short ifs on the same line. 376 /// \code 377 /// if (a) 378 /// return ; 379 /// else { 380 /// return; 381 /// } 382 /// \endcode 383 SIS_Never, 384 /// Without else put short ifs on the same line only if 385 /// the else is not a compound statement. 386 /// \code 387 /// if (a) return; 388 /// else 389 /// return; 390 /// \endcode 391 SIS_WithoutElse, 392 /// Always put short ifs on the same line if 393 /// the else is not a compound statement or not. 394 /// \code 395 /// if (a) return; 396 /// else { 397 /// return; 398 /// } 399 /// \endcode 400 SIS_Always, 401 }; 402 403 /// If ``true``, ``if (a) return;`` can be put on a single line. 404 ShortIfStyle AllowShortIfStatementsOnASingleLine; 405 406 /// Different styles for merging short lambdas containing at most one 407 /// statement. 408 enum ShortLambdaStyle { 409 /// Never merge lambdas into a single line. 410 SLS_None, 411 /// Only merge empty lambdas. 412 /// \code 413 /// auto lambda = [](int a) {} 414 /// auto lambda2 = [](int a) { 415 /// return a; 416 /// }; 417 /// \endcode 418 SLS_Empty, 419 /// Merge lambda into a single line if argument of a function. 420 /// \code 421 /// auto lambda = [](int a) { 422 /// return a; 423 /// }; 424 /// sort(a.begin(), a.end(), ()[] { return x < y; }) 425 /// \endcode 426 SLS_Inline, 427 /// Merge all lambdas fitting on a single line. 428 /// \code 429 /// auto lambda = [](int a) {} 430 /// auto lambda2 = [](int a) { return a; }; 431 /// \endcode 432 SLS_All, 433 }; 434 435 /// Dependent on the value, ``auto lambda []() { return 0; }`` can be put on a 436 /// single line. 437 ShortLambdaStyle AllowShortLambdasOnASingleLine; 438 439 /// If ``true``, ``while (true) continue;`` can be put on a single 440 /// line. 441 bool AllowShortLoopsOnASingleLine; 442 443 /// Different ways to break after the function definition return type. 444 /// This option is **deprecated** and is retained for backwards compatibility. 445 enum DefinitionReturnTypeBreakingStyle { 446 /// Break after return type automatically. 447 /// ``PenaltyReturnTypeOnItsOwnLine`` is taken into account. 448 DRTBS_None, 449 /// Always break after the return type. 450 DRTBS_All, 451 /// Always break after the return types of top-level functions. 452 DRTBS_TopLevel, 453 }; 454 455 /// Different ways to break after the function definition or 456 /// declaration return type. 457 enum ReturnTypeBreakingStyle { 458 /// Break after return type automatically. 459 /// ``PenaltyReturnTypeOnItsOwnLine`` is taken into account. 460 /// \code 461 /// class A { 462 /// int f() { return 0; }; 463 /// }; 464 /// int f(); 465 /// int f() { return 1; } 466 /// \endcode 467 RTBS_None, 468 /// Always break after the return type. 469 /// \code 470 /// class A { 471 /// int 472 /// f() { 473 /// return 0; 474 /// }; 475 /// }; 476 /// int 477 /// f(); 478 /// int 479 /// f() { 480 /// return 1; 481 /// } 482 /// \endcode 483 RTBS_All, 484 /// Always break after the return types of top-level functions. 485 /// \code 486 /// class A { 487 /// int f() { return 0; }; 488 /// }; 489 /// int 490 /// f(); 491 /// int 492 /// f() { 493 /// return 1; 494 /// } 495 /// \endcode 496 RTBS_TopLevel, 497 /// Always break after the return type of function definitions. 498 /// \code 499 /// class A { 500 /// int 501 /// f() { 502 /// return 0; 503 /// }; 504 /// }; 505 /// int f(); 506 /// int 507 /// f() { 508 /// return 1; 509 /// } 510 /// \endcode 511 RTBS_AllDefinitions, 512 /// Always break after the return type of top-level definitions. 513 /// \code 514 /// class A { 515 /// int f() { return 0; }; 516 /// }; 517 /// int f(); 518 /// int 519 /// f() { 520 /// return 1; 521 /// } 522 /// \endcode 523 RTBS_TopLevelDefinitions, 524 }; 525 526 /// The function definition return type breaking style to use. This 527 /// option is **deprecated** and is retained for backwards compatibility. 528 DefinitionReturnTypeBreakingStyle AlwaysBreakAfterDefinitionReturnType; 529 530 /// The function declaration return type breaking style to use. 531 ReturnTypeBreakingStyle AlwaysBreakAfterReturnType; 532 533 /// If ``true``, always break before multiline string literals. 534 /// 535 /// This flag is mean to make cases where there are multiple multiline strings 536 /// in a file look more consistent. Thus, it will only take effect if wrapping 537 /// the string at that point leads to it being indented 538 /// ``ContinuationIndentWidth`` spaces from the start of the line. 539 /// \code 540 /// true: false: 541 /// aaaa = vs. aaaa = "bbbb" 542 /// "bbbb" "cccc"; 543 /// "cccc"; 544 /// \endcode 545 bool AlwaysBreakBeforeMultilineStrings; 546 547 /// Different ways to break after the template declaration. 548 enum BreakTemplateDeclarationsStyle { 549 /// Do not force break before declaration. 550 /// ``PenaltyBreakTemplateDeclaration`` is taken into account. 551 /// \code 552 /// template <typename T> T foo() { 553 /// } 554 /// template <typename T> T foo(int aaaaaaaaaaaaaaaaaaaaa, 555 /// int bbbbbbbbbbbbbbbbbbbbb) { 556 /// } 557 /// \endcode 558 BTDS_No, 559 /// Force break after template declaration only when the following 560 /// declaration spans multiple lines. 561 /// \code 562 /// template <typename T> T foo() { 563 /// } 564 /// template <typename T> 565 /// T foo(int aaaaaaaaaaaaaaaaaaaaa, 566 /// int bbbbbbbbbbbbbbbbbbbbb) { 567 /// } 568 /// \endcode 569 BTDS_MultiLine, 570 /// Always break after template declaration. 571 /// \code 572 /// template <typename T> 573 /// T foo() { 574 /// } 575 /// template <typename T> 576 /// T foo(int aaaaaaaaaaaaaaaaaaaaa, 577 /// int bbbbbbbbbbbbbbbbbbbbb) { 578 /// } 579 /// \endcode 580 BTDS_Yes 581 }; 582 583 /// The template declaration breaking style to use. 584 BreakTemplateDeclarationsStyle AlwaysBreakTemplateDeclarations; 585 586 /// If ``false``, a function call's arguments will either be all on the 587 /// same line or will have one line each. 588 /// \code 589 /// true: 590 /// void f() { 591 /// f(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaa, 592 /// aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa); 593 /// } 594 /// 595 /// false: 596 /// void f() { 597 /// f(aaaaaaaaaaaaaaaaaaaa, 598 /// aaaaaaaaaaaaaaaaaaaa, 599 /// aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa); 600 /// } 601 /// \endcode 602 bool BinPackArguments; 603 604 /// The style of inserting trailing commas into container literals. 605 enum TrailingCommaStyle { 606 /// Do not insert trailing commas. 607 TCS_None, 608 /// Insert trailing commas in container literals that were wrapped over 609 /// multiple lines. Note that this is conceptually incompatible with 610 /// bin-packing, because the trailing comma is used as an indicator 611 /// that a container should be formatted one-per-line (i.e. not bin-packed). 612 /// So inserting a trailing comma counteracts bin-packing. 613 TCS_Wrapped, 614 }; 615 616 /// If set to ``TCS_Wrapped`` will insert trailing commas in container 617 /// literals (arrays and objects) that wrap across multiple lines. 618 /// It is currently only available for JavaScript 619 /// and disabled by default ``TCS_None``. 620 /// ``InsertTrailingCommas`` cannot be used together with ``BinPackArguments`` 621 /// as inserting the comma disables bin-packing. 622 /// \code 623 /// TSC_Wrapped: 624 /// const someArray = [ 625 /// aaaaaaaaaaaaaaaaaaaaaaaaaa, 626 /// aaaaaaaaaaaaaaaaaaaaaaaaaa, 627 /// aaaaaaaaaaaaaaaaaaaaaaaaaa, 628 /// // ^ inserted 629 /// ] 630 /// \endcode 631 TrailingCommaStyle InsertTrailingCommas; 632 633 /// If ``false``, a function declaration's or function definition's 634 /// parameters will either all be on the same line or will have one line each. 635 /// \code 636 /// true: 637 /// void f(int aaaaaaaaaaaaaaaaaaaa, int aaaaaaaaaaaaaaaaaaaa, 638 /// int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {} 639 /// 640 /// false: 641 /// void f(int aaaaaaaaaaaaaaaaaaaa, 642 /// int aaaaaaaaaaaaaaaaaaaa, 643 /// int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {} 644 /// \endcode 645 bool BinPackParameters; 646 647 /// The style of wrapping parameters on the same line (bin-packed) or 648 /// on one line each. 649 enum BinPackStyle { 650 /// Automatically determine parameter bin-packing behavior. 651 BPS_Auto, 652 /// Always bin-pack parameters. 653 BPS_Always, 654 /// Never bin-pack parameters. 655 BPS_Never, 656 }; 657 658 /// The style of breaking before or after binary operators. 659 enum BinaryOperatorStyle { 660 /// Break after operators. 661 /// \code 662 /// LooooooooooongType loooooooooooooooooooooongVariable = 663 /// someLooooooooooooooooongFunction(); 664 /// 665 /// bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa + 666 /// aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == 667 /// aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa && 668 /// aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa > 669 /// ccccccccccccccccccccccccccccccccccccccccc; 670 /// \endcode 671 BOS_None, 672 /// Break before operators that aren't assignments. 673 /// \code 674 /// LooooooooooongType loooooooooooooooooooooongVariable = 675 /// someLooooooooooooooooongFunction(); 676 /// 677 /// bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa 678 /// + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa 679 /// == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa 680 /// && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa 681 /// > ccccccccccccccccccccccccccccccccccccccccc; 682 /// \endcode 683 BOS_NonAssignment, 684 /// Break before operators. 685 /// \code 686 /// LooooooooooongType loooooooooooooooooooooongVariable 687 /// = someLooooooooooooooooongFunction(); 688 /// 689 /// bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa 690 /// + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa 691 /// == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa 692 /// && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa 693 /// > ccccccccccccccccccccccccccccccccccccccccc; 694 /// \endcode 695 BOS_All, 696 }; 697 698 /// The way to wrap binary operators. 699 BinaryOperatorStyle BreakBeforeBinaryOperators; 700 701 /// Different ways to attach braces to their surrounding context. 702 enum BraceBreakingStyle { 703 /// Always attach braces to surrounding context. 704 /// \code 705 /// try { 706 /// foo(); 707 /// } catch () { 708 /// } 709 /// void foo() { bar(); } 710 /// class foo {}; 711 /// if (foo()) { 712 /// } else { 713 /// } 714 /// enum X : int { A, B }; 715 /// \endcode 716 BS_Attach, 717 /// Like ``Attach``, but break before braces on function, namespace and 718 /// class definitions. 719 /// \code 720 /// try { 721 /// foo(); 722 /// } catch () { 723 /// } 724 /// void foo() { bar(); } 725 /// class foo 726 /// { 727 /// }; 728 /// if (foo()) { 729 /// } else { 730 /// } 731 /// enum X : int { A, B }; 732 /// \endcode 733 BS_Linux, 734 /// Like ``Attach``, but break before braces on enum, function, and record 735 /// definitions. 736 /// \code 737 /// try { 738 /// foo(); 739 /// } catch () { 740 /// } 741 /// void foo() { bar(); } 742 /// class foo 743 /// { 744 /// }; 745 /// if (foo()) { 746 /// } else { 747 /// } 748 /// enum X : int { A, B }; 749 /// \endcode 750 BS_Mozilla, 751 /// Like ``Attach``, but break before function definitions, ``catch``, and 752 /// ``else``. 753 /// \code 754 /// try { 755 /// foo(); 756 /// } 757 /// catch () { 758 /// } 759 /// void foo() { bar(); } 760 /// class foo { 761 /// }; 762 /// if (foo()) { 763 /// } 764 /// else { 765 /// } 766 /// enum X : int { A, B }; 767 /// \endcode 768 BS_Stroustrup, 769 /// Always break before braces. 770 /// \code 771 /// try 772 /// { 773 /// foo(); 774 /// } 775 /// catch () 776 /// { 777 /// } 778 /// void foo() { bar(); } 779 /// class foo 780 /// { 781 /// }; 782 /// if (foo()) 783 /// { 784 /// } 785 /// else 786 /// { 787 /// } 788 /// enum X : int 789 /// { 790 /// A, 791 /// B 792 /// }; 793 /// \endcode 794 BS_Allman, 795 /// Like ``Allman`` but always indent braces and line up code with braces. 796 /// \code 797 /// try 798 /// { 799 /// foo(); 800 /// } 801 /// catch () 802 /// { 803 /// } 804 /// void foo() { bar(); } 805 /// class foo 806 /// { 807 /// }; 808 /// if (foo()) 809 /// { 810 /// } 811 /// else 812 /// { 813 /// } 814 /// enum X : int 815 /// { 816 /// A, 817 /// B 818 /// }; 819 /// \endcode 820 BS_Whitesmiths, 821 /// Always break before braces and add an extra level of indentation to 822 /// braces of control statements, not to those of class, function 823 /// or other definitions. 824 /// \code 825 /// try 826 /// { 827 /// foo(); 828 /// } 829 /// catch () 830 /// { 831 /// } 832 /// void foo() { bar(); } 833 /// class foo 834 /// { 835 /// }; 836 /// if (foo()) 837 /// { 838 /// } 839 /// else 840 /// { 841 /// } 842 /// enum X : int 843 /// { 844 /// A, 845 /// B 846 /// }; 847 /// \endcode 848 BS_GNU, 849 /// Like ``Attach``, but break before functions. 850 /// \code 851 /// try { 852 /// foo(); 853 /// } catch () { 854 /// } 855 /// void foo() { bar(); } 856 /// class foo { 857 /// }; 858 /// if (foo()) { 859 /// } else { 860 /// } 861 /// enum X : int { A, B }; 862 /// \endcode 863 BS_WebKit, 864 /// Configure each individual brace in `BraceWrapping`. 865 BS_Custom 866 }; 867 868 /// The brace breaking style to use. 869 BraceBreakingStyle BreakBeforeBraces; 870 871 /// Different ways to wrap braces after control statements. 872 enum BraceWrappingAfterControlStatementStyle { 873 /// Never wrap braces after a control statement. 874 /// \code 875 /// if (foo()) { 876 /// } else { 877 /// } 878 /// for (int i = 0; i < 10; ++i) { 879 /// } 880 /// \endcode 881 BWACS_Never, 882 /// Only wrap braces after a multi-line control statement. 883 /// \code 884 /// if (foo && bar && 885 /// baz) 886 /// { 887 /// quux(); 888 /// } 889 /// while (foo || bar) { 890 /// } 891 /// \endcode 892 BWACS_MultiLine, 893 /// Always wrap braces after a control statement. 894 /// \code 895 /// if (foo()) 896 /// { 897 /// } else 898 /// {} 899 /// for (int i = 0; i < 10; ++i) 900 /// {} 901 /// \endcode 902 BWACS_Always 903 }; 904 905 /// Precise control over the wrapping of braces. 906 /// \code 907 /// # Should be declared this way: 908 /// BreakBeforeBraces: Custom 909 /// BraceWrapping: 910 /// AfterClass: true 911 /// \endcode 912 struct BraceWrappingFlags { 913 /// Wrap case labels. 914 /// \code 915 /// false: true: 916 /// switch (foo) { vs. switch (foo) { 917 /// case 1: { case 1: 918 /// bar(); { 919 /// break; bar(); 920 /// } break; 921 /// default: { } 922 /// plop(); default: 923 /// } { 924 /// } plop(); 925 /// } 926 /// } 927 /// \endcode 928 bool AfterCaseLabel; 929 /// Wrap class definitions. 930 /// \code 931 /// true: 932 /// class foo {}; 933 /// 934 /// false: 935 /// class foo 936 /// {}; 937 /// \endcode 938 bool AfterClass; 939 940 /// Wrap control statements (``if``/``for``/``while``/``switch``/..). 941 BraceWrappingAfterControlStatementStyle AfterControlStatement; 942 /// Wrap enum definitions. 943 /// \code 944 /// true: 945 /// enum X : int 946 /// { 947 /// B 948 /// }; 949 /// 950 /// false: 951 /// enum X : int { B }; 952 /// \endcode 953 bool AfterEnum; 954 /// Wrap function definitions. 955 /// \code 956 /// true: 957 /// void foo() 958 /// { 959 /// bar(); 960 /// bar2(); 961 /// } 962 /// 963 /// false: 964 /// void foo() { 965 /// bar(); 966 /// bar2(); 967 /// } 968 /// \endcode 969 bool AfterFunction; 970 /// Wrap namespace definitions. 971 /// \code 972 /// true: 973 /// namespace 974 /// { 975 /// int foo(); 976 /// int bar(); 977 /// } 978 /// 979 /// false: 980 /// namespace { 981 /// int foo(); 982 /// int bar(); 983 /// } 984 /// \endcode 985 bool AfterNamespace; 986 /// Wrap ObjC definitions (interfaces, implementations...). 987 /// \note @autoreleasepool and @synchronized blocks are wrapped 988 /// according to `AfterControlStatement` flag. 989 bool AfterObjCDeclaration; 990 /// Wrap struct definitions. 991 /// \code 992 /// true: 993 /// struct foo 994 /// { 995 /// int x; 996 /// }; 997 /// 998 /// false: 999 /// struct foo { 1000 /// int x; 1001 /// }; 1002 /// \endcode 1003 bool AfterStruct; 1004 /// Wrap union definitions. 1005 /// \code 1006 /// true: 1007 /// union foo 1008 /// { 1009 /// int x; 1010 /// } 1011 /// 1012 /// false: 1013 /// union foo { 1014 /// int x; 1015 /// } 1016 /// \endcode 1017 bool AfterUnion; 1018 /// Wrap extern blocks. 1019 /// \code 1020 /// true: 1021 /// extern "C" 1022 /// { 1023 /// int foo(); 1024 /// } 1025 /// 1026 /// false: 1027 /// extern "C" { 1028 /// int foo(); 1029 /// } 1030 /// \endcode 1031 bool AfterExternBlock; // Partially superseded by IndentExternBlock 1032 /// Wrap before ``catch``. 1033 /// \code 1034 /// true: 1035 /// try { 1036 /// foo(); 1037 /// } 1038 /// catch () { 1039 /// } 1040 /// 1041 /// false: 1042 /// try { 1043 /// foo(); 1044 /// } catch () { 1045 /// } 1046 /// \endcode 1047 bool BeforeCatch; 1048 /// Wrap before ``else``. 1049 /// \code 1050 /// true: 1051 /// if (foo()) { 1052 /// } 1053 /// else { 1054 /// } 1055 /// 1056 /// false: 1057 /// if (foo()) { 1058 /// } else { 1059 /// } 1060 /// \endcode 1061 bool BeforeElse; 1062 /// Wrap lambda block. 1063 /// \code 1064 /// true: 1065 /// connect( 1066 /// []() 1067 /// { 1068 /// foo(); 1069 /// bar(); 1070 /// }); 1071 /// 1072 /// false: 1073 /// connect([]() { 1074 /// foo(); 1075 /// bar(); 1076 /// }); 1077 /// \endcode 1078 bool BeforeLambdaBody; 1079 /// Wrap before ``while``. 1080 /// \code 1081 /// true: 1082 /// do { 1083 /// foo(); 1084 /// } 1085 /// while (1); 1086 /// 1087 /// false: 1088 /// do { 1089 /// foo(); 1090 /// } while (1); 1091 /// \endcode 1092 bool BeforeWhile; 1093 /// Indent the wrapped braces themselves. 1094 bool IndentBraces; 1095 /// If ``false``, empty function body can be put on a single line. 1096 /// This option is used only if the opening brace of the function has 1097 /// already been wrapped, i.e. the `AfterFunction` brace wrapping mode is 1098 /// set, and the function could/should not be put on a single line (as per 1099 /// `AllowShortFunctionsOnASingleLine` and constructor formatting options). 1100 /// \code 1101 /// int f() vs. int f() 1102 /// {} { 1103 /// } 1104 /// \endcode 1105 /// 1106 bool SplitEmptyFunction; 1107 /// If ``false``, empty record (e.g. class, struct or union) body 1108 /// can be put on a single line. This option is used only if the opening 1109 /// brace of the record has already been wrapped, i.e. the `AfterClass` 1110 /// (for classes) brace wrapping mode is set. 1111 /// \code 1112 /// class Foo vs. class Foo 1113 /// {} { 1114 /// } 1115 /// \endcode 1116 /// 1117 bool SplitEmptyRecord; 1118 /// If ``false``, empty namespace body can be put on a single line. 1119 /// This option is used only if the opening brace of the namespace has 1120 /// already been wrapped, i.e. the `AfterNamespace` brace wrapping mode is 1121 /// set. 1122 /// \code 1123 /// namespace Foo vs. namespace Foo 1124 /// {} { 1125 /// } 1126 /// \endcode 1127 /// 1128 bool SplitEmptyNamespace; 1129 }; 1130 1131 /// Control of individual brace wrapping cases. 1132 /// 1133 /// If ``BreakBeforeBraces`` is set to ``BS_Custom``, use this to specify how 1134 /// each individual brace case should be handled. Otherwise, this is ignored. 1135 /// \code{.yaml} 1136 /// # Example of usage: 1137 /// BreakBeforeBraces: Custom 1138 /// BraceWrapping: 1139 /// AfterEnum: true 1140 /// AfterStruct: false 1141 /// SplitEmptyFunction: false 1142 /// \endcode 1143 BraceWrappingFlags BraceWrapping; 1144 1145 /// If ``true``, ternary operators will be placed after line breaks. 1146 /// \code 1147 /// true: 1148 /// veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongDescription 1149 /// ? firstValue 1150 /// : SecondValueVeryVeryVeryVeryLong; 1151 /// 1152 /// false: 1153 /// veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongDescription ? 1154 /// firstValue : 1155 /// SecondValueVeryVeryVeryVeryLong; 1156 /// \endcode 1157 bool BreakBeforeTernaryOperators; 1158 1159 /// Different ways to break initializers. 1160 enum BreakConstructorInitializersStyle { 1161 /// Break constructor initializers before the colon and after the commas. 1162 /// \code 1163 /// Constructor() 1164 /// : initializer1(), 1165 /// initializer2() 1166 /// \endcode 1167 BCIS_BeforeColon, 1168 /// Break constructor initializers before the colon and commas, and align 1169 /// the commas with the colon. 1170 /// \code 1171 /// Constructor() 1172 /// : initializer1() 1173 /// , initializer2() 1174 /// \endcode 1175 BCIS_BeforeComma, 1176 /// Break constructor initializers after the colon and commas. 1177 /// \code 1178 /// Constructor() : 1179 /// initializer1(), 1180 /// initializer2() 1181 /// \endcode 1182 BCIS_AfterColon 1183 }; 1184 1185 /// The constructor initializers style to use. 1186 BreakConstructorInitializersStyle BreakConstructorInitializers; 1187 1188 /// Break after each annotation on a field in Java files. 1189 /// \code{.java} 1190 /// true: false: 1191 /// @Partial vs. @Partial @Mock DataLoad loader; 1192 /// @Mock 1193 /// DataLoad loader; 1194 /// \endcode 1195 bool BreakAfterJavaFieldAnnotations; 1196 1197 /// Allow breaking string literals when formatting. 1198 /// \code 1199 /// true: 1200 /// const char* x = "veryVeryVeryVeryVeryVe" 1201 /// "ryVeryVeryVeryVeryVery" 1202 /// "VeryLongString"; 1203 /// 1204 /// false: 1205 /// const char* x = 1206 /// "veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongString"; 1207 /// \endcode 1208 bool BreakStringLiterals; 1209 1210 /// The column limit. 1211 /// 1212 /// A column limit of ``0`` means that there is no column limit. In this case, 1213 /// clang-format will respect the input's line breaking decisions within 1214 /// statements unless they contradict other rules. 1215 unsigned ColumnLimit; 1216 1217 /// A regular expression that describes comments with special meaning, 1218 /// which should not be split into lines or otherwise changed. 1219 /// \code 1220 /// // CommentPragmas: '^ FOOBAR pragma:' 1221 /// // Will leave the following line unaffected 1222 /// #include <vector> // FOOBAR pragma: keep 1223 /// \endcode 1224 std::string CommentPragmas; 1225 1226 /// Different ways to break inheritance list. 1227 enum BreakInheritanceListStyle { 1228 /// Break inheritance list before the colon and after the commas. 1229 /// \code 1230 /// class Foo 1231 /// : Base1, 1232 /// Base2 1233 /// {}; 1234 /// \endcode 1235 BILS_BeforeColon, 1236 /// Break inheritance list before the colon and commas, and align 1237 /// the commas with the colon. 1238 /// \code 1239 /// class Foo 1240 /// : Base1 1241 /// , Base2 1242 /// {}; 1243 /// \endcode 1244 BILS_BeforeComma, 1245 /// Break inheritance list after the colon and commas. 1246 /// \code 1247 /// class Foo : 1248 /// Base1, 1249 /// Base2 1250 /// {}; 1251 /// \endcode 1252 BILS_AfterColon 1253 }; 1254 1255 /// The inheritance list style to use. 1256 BreakInheritanceListStyle BreakInheritanceList; 1257 1258 /// If ``true``, consecutive namespace declarations will be on the same 1259 /// line. If ``false``, each namespace is declared on a new line. 1260 /// \code 1261 /// true: 1262 /// namespace Foo { namespace Bar { 1263 /// }} 1264 /// 1265 /// false: 1266 /// namespace Foo { 1267 /// namespace Bar { 1268 /// } 1269 /// } 1270 /// \endcode 1271 /// 1272 /// If it does not fit on a single line, the overflowing namespaces get 1273 /// wrapped: 1274 /// \code 1275 /// namespace Foo { namespace Bar { 1276 /// namespace Extra { 1277 /// }}} 1278 /// \endcode 1279 bool CompactNamespaces; 1280 1281 // clang-format off 1282 /// If the constructor initializers don't fit on a line, put each 1283 /// initializer on its own line. 1284 /// \code 1285 /// true: 1286 /// SomeClass::Constructor() 1287 /// : aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa) { 1288 /// return 0; 1289 /// } 1290 /// 1291 /// false: 1292 /// SomeClass::Constructor() 1293 /// : aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaa), 1294 /// aaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa) { 1295 /// return 0; 1296 /// } 1297 /// \endcode 1298 bool ConstructorInitializerAllOnOneLineOrOnePerLine; 1299 // clang-format on 1300 1301 /// The number of characters to use for indentation of constructor 1302 /// initializer lists as well as inheritance lists. 1303 unsigned ConstructorInitializerIndentWidth; 1304 1305 /// Indent width for line continuations. 1306 /// \code 1307 /// ContinuationIndentWidth: 2 1308 /// 1309 /// int i = // VeryVeryVeryVeryVeryLongComment 1310 /// longFunction( // Again a long comment 1311 /// arg); 1312 /// \endcode 1313 unsigned ContinuationIndentWidth; 1314 1315 /// If ``true``, format braced lists as best suited for C++11 braced 1316 /// lists. 1317 /// 1318 /// Important differences: 1319 /// - No spaces inside the braced list. 1320 /// - No line break before the closing brace. 1321 /// - Indentation with the continuation indent, not with the block indent. 1322 /// 1323 /// Fundamentally, C++11 braced lists are formatted exactly like function 1324 /// calls would be formatted in their place. If the braced list follows a name 1325 /// (e.g. a type or variable name), clang-format formats as if the ``{}`` were 1326 /// the parentheses of a function call with that name. If there is no name, 1327 /// a zero-length name is assumed. 1328 /// \code 1329 /// true: false: 1330 /// vector<int> x{1, 2, 3, 4}; vs. vector<int> x{ 1, 2, 3, 4 }; 1331 /// vector<T> x{{}, {}, {}, {}}; vector<T> x{ {}, {}, {}, {} }; 1332 /// f(MyMap[{composite, key}]); f(MyMap[{ composite, key }]); 1333 /// new int[3]{1, 2, 3}; new int[3]{ 1, 2, 3 }; 1334 /// \endcode 1335 bool Cpp11BracedListStyle; 1336 1337 /// \brief Analyze the formatted file for the most used line ending (``\r\n`` 1338 /// or ``\n``). ``UseCRLF`` is only used as a fallback if none can be derived. 1339 bool DeriveLineEnding; 1340 1341 /// If ``true``, analyze the formatted file for the most common 1342 /// alignment of ``&`` and ``*``. 1343 /// Pointer and reference alignment styles are going to be updated according 1344 /// to the preferences found in the file. 1345 /// ``PointerAlignment`` is then used only as fallback. 1346 bool DerivePointerAlignment; 1347 1348 /// Disables formatting completely. 1349 bool DisableFormat; 1350 1351 /// If ``true``, clang-format detects whether function calls and 1352 /// definitions are formatted with one parameter per line. 1353 /// 1354 /// Each call can be bin-packed, one-per-line or inconclusive. If it is 1355 /// inconclusive, e.g. completely on one line, but a decision needs to be 1356 /// made, clang-format analyzes whether there are other bin-packed cases in 1357 /// the input file and act accordingly. 1358 /// 1359 /// NOTE: This is an experimental flag, that might go away or be renamed. Do 1360 /// not use this in config files, etc. Use at your own risk. 1361 bool ExperimentalAutoDetectBinPacking; 1362 1363 /// If ``true``, clang-format adds missing namespace end comments and 1364 /// fixes invalid existing ones. 1365 /// \code 1366 /// true: false: 1367 /// namespace a { vs. namespace a { 1368 /// foo(); foo(); 1369 /// } // namespace a } 1370 /// \endcode 1371 bool FixNamespaceComments; 1372 1373 /// A vector of macros that should be interpreted as foreach loops 1374 /// instead of as function calls. 1375 /// 1376 /// These are expected to be macros of the form: 1377 /// \code 1378 /// FOREACH(<variable-declaration>, ...) 1379 /// <loop-body> 1380 /// \endcode 1381 /// 1382 /// In the .clang-format configuration file, this can be configured like: 1383 /// \code{.yaml} 1384 /// ForEachMacros: ['RANGES_FOR', 'FOREACH'] 1385 /// \endcode 1386 /// 1387 /// For example: BOOST_FOREACH. 1388 std::vector<std::string> ForEachMacros; 1389 1390 /// \brief A vector of macros that should be interpreted as type declarations 1391 /// instead of as function calls. 1392 /// 1393 /// These are expected to be macros of the form: 1394 /// \code 1395 /// STACK_OF(...) 1396 /// \endcode 1397 /// 1398 /// In the .clang-format configuration file, this can be configured like: 1399 /// \code{.yaml} 1400 /// TypenameMacros: ['STACK_OF', 'LIST'] 1401 /// \endcode 1402 /// 1403 /// For example: OpenSSL STACK_OF, BSD LIST_ENTRY. 1404 std::vector<std::string> TypenameMacros; 1405 1406 /// A vector of macros that should be interpreted as complete 1407 /// statements. 1408 /// 1409 /// Typical macros are expressions, and require a semi-colon to be 1410 /// added; sometimes this is not the case, and this allows to make 1411 /// clang-format aware of such cases. 1412 /// 1413 /// For example: Q_UNUSED 1414 std::vector<std::string> StatementMacros; 1415 1416 /// A vector of macros which are used to open namespace blocks. 1417 /// 1418 /// These are expected to be macros of the form: 1419 /// \code 1420 /// NAMESPACE(<namespace-name>, ...) { 1421 /// <namespace-content> 1422 /// } 1423 /// \endcode 1424 /// 1425 /// For example: TESTSUITE 1426 std::vector<std::string> NamespaceMacros; 1427 1428 /// A vector of macros which are whitespace-sensitive and shouldn't be 1429 /// touched. 1430 /// 1431 /// These are expected to be macros of the form: 1432 /// \code 1433 /// STRINGIZE(...) 1434 /// \endcode 1435 /// 1436 /// For example: STRINGIZE 1437 std::vector<std::string> WhitespaceSensitiveMacros; 1438 1439 tooling::IncludeStyle IncludeStyle; 1440 1441 /// Indent case labels one level from the switch statement. 1442 /// 1443 /// When ``false``, use the same indentation level as for the switch 1444 /// statement. Switch statement body is always indented one level more than 1445 /// case labels (except the first block following the case label, which 1446 /// itself indents the code - unless IndentCaseBlocks is enabled). 1447 /// \code 1448 /// false: true: 1449 /// switch (fool) { vs. switch (fool) { 1450 /// case 1: case 1: 1451 /// bar(); bar(); 1452 /// break; break; 1453 /// default: default: 1454 /// plop(); plop(); 1455 /// } } 1456 /// \endcode 1457 bool IndentCaseLabels; 1458 1459 /// Indent case label blocks one level from the case label. 1460 /// 1461 /// When ``false``, the block following the case label uses the same 1462 /// indentation level as for the case label, treating the case label the same 1463 /// as an if-statement. 1464 /// When ``true``, the block gets indented as a scope block. 1465 /// \code 1466 /// false: true: 1467 /// switch (fool) { vs. switch (fool) { 1468 /// case 1: { case 1: 1469 /// bar(); { 1470 /// } break; bar(); 1471 /// default: { } 1472 /// plop(); break; 1473 /// } default: 1474 /// } { 1475 /// plop(); 1476 /// } 1477 /// } 1478 /// \endcode 1479 bool IndentCaseBlocks; 1480 1481 /// Indent goto labels. 1482 /// 1483 /// When ``false``, goto labels are flushed left. 1484 /// \code 1485 /// true: false: 1486 /// int f() { vs. int f() { 1487 /// if (foo()) { if (foo()) { 1488 /// label1: label1: 1489 /// bar(); bar(); 1490 /// } } 1491 /// label2: label2: 1492 /// return 1; return 1; 1493 /// } } 1494 /// \endcode 1495 bool IndentGotoLabels; 1496 1497 /// Options for indenting preprocessor directives. 1498 enum PPDirectiveIndentStyle { 1499 /// Does not indent any directives. 1500 /// \code 1501 /// #if FOO 1502 /// #if BAR 1503 /// #include <foo> 1504 /// #endif 1505 /// #endif 1506 /// \endcode 1507 PPDIS_None, 1508 /// Indents directives after the hash. 1509 /// \code 1510 /// #if FOO 1511 /// # if BAR 1512 /// # include <foo> 1513 /// # endif 1514 /// #endif 1515 /// \endcode 1516 PPDIS_AfterHash, 1517 /// Indents directives before the hash. 1518 /// \code 1519 /// #if FOO 1520 /// #if BAR 1521 /// #include <foo> 1522 /// #endif 1523 /// #endif 1524 /// \endcode 1525 PPDIS_BeforeHash 1526 }; 1527 1528 /// The preprocessor directive indenting style to use. 1529 PPDirectiveIndentStyle IndentPPDirectives; 1530 1531 /// Indents extern blocks 1532 enum IndentExternBlockStyle { 1533 /// Backwards compatible with AfterExternBlock's indenting. 1534 /// \code 1535 /// IndentExternBlock: AfterExternBlock 1536 /// BraceWrapping.AfterExternBlock: true 1537 /// extern "C" 1538 /// { 1539 /// void foo(); 1540 /// } 1541 /// \endcode 1542 /// 1543 /// \code 1544 /// IndentExternBlock: AfterExternBlock 1545 /// BraceWrapping.AfterExternBlock: false 1546 /// extern "C" { 1547 /// void foo(); 1548 /// } 1549 /// \endcode 1550 IEBS_AfterExternBlock, 1551 /// Does not indent extern blocks. 1552 /// \code 1553 /// extern "C" { 1554 /// void foo(); 1555 /// } 1556 /// \endcode 1557 IEBS_NoIndent, 1558 /// Indents extern blocks. 1559 /// \code 1560 /// extern "C" { 1561 /// void foo(); 1562 /// } 1563 /// \endcode 1564 IEBS_Indent, 1565 }; 1566 1567 /// IndentExternBlockStyle is the type of indenting of extern blocks. 1568 IndentExternBlockStyle IndentExternBlock; 1569 1570 /// The number of columns to use for indentation. 1571 /// \code 1572 /// IndentWidth: 3 1573 /// 1574 /// void f() { 1575 /// someFunction(); 1576 /// if (true, false) { 1577 /// f(); 1578 /// } 1579 /// } 1580 /// \endcode 1581 unsigned IndentWidth; 1582 1583 /// Indent if a function definition or declaration is wrapped after the 1584 /// type. 1585 /// \code 1586 /// true: 1587 /// LoooooooooooooooooooooooooooooooooooooooongReturnType 1588 /// LoooooooooooooooooooooooooooooooongFunctionDeclaration(); 1589 /// 1590 /// false: 1591 /// LoooooooooooooooooooooooooooooooooooooooongReturnType 1592 /// LoooooooooooooooooooooooooooooooongFunctionDeclaration(); 1593 /// \endcode 1594 bool IndentWrappedFunctionNames; 1595 1596 /// A vector of prefixes ordered by the desired groups for Java imports. 1597 /// 1598 /// Each group is separated by a newline. Static imports will also follow the 1599 /// same grouping convention above all non-static imports. One group's prefix 1600 /// can be a subset of another - the longest prefix is always matched. Within 1601 /// a group, the imports are ordered lexicographically. 1602 /// 1603 /// In the .clang-format configuration file, this can be configured like 1604 /// in the following yaml example. This will result in imports being 1605 /// formatted as in the Java example below. 1606 /// \code{.yaml} 1607 /// JavaImportGroups: ['com.example', 'com', 'org'] 1608 /// \endcode 1609 /// 1610 /// \code{.java} 1611 /// import static com.example.function1; 1612 /// 1613 /// import static com.test.function2; 1614 /// 1615 /// import static org.example.function3; 1616 /// 1617 /// import com.example.ClassA; 1618 /// import com.example.Test; 1619 /// import com.example.a.ClassB; 1620 /// 1621 /// import com.test.ClassC; 1622 /// 1623 /// import org.example.ClassD; 1624 /// \endcode 1625 std::vector<std::string> JavaImportGroups; 1626 1627 /// Quotation styles for JavaScript strings. Does not affect template 1628 /// strings. 1629 enum JavaScriptQuoteStyle { 1630 /// Leave string quotes as they are. 1631 /// \code{.js} 1632 /// string1 = "foo"; 1633 /// string2 = 'bar'; 1634 /// \endcode 1635 JSQS_Leave, 1636 /// Always use single quotes. 1637 /// \code{.js} 1638 /// string1 = 'foo'; 1639 /// string2 = 'bar'; 1640 /// \endcode 1641 JSQS_Single, 1642 /// Always use double quotes. 1643 /// \code{.js} 1644 /// string1 = "foo"; 1645 /// string2 = "bar"; 1646 /// \endcode 1647 JSQS_Double 1648 }; 1649 1650 /// The JavaScriptQuoteStyle to use for JavaScript strings. 1651 JavaScriptQuoteStyle JavaScriptQuotes; 1652 1653 // clang-format off 1654 /// Whether to wrap JavaScript import/export statements. 1655 /// \code{.js} 1656 /// true: 1657 /// import { 1658 /// VeryLongImportsAreAnnoying, 1659 /// VeryLongImportsAreAnnoying, 1660 /// VeryLongImportsAreAnnoying, 1661 /// } from 'some/module.js' 1662 /// 1663 /// false: 1664 /// import {VeryLongImportsAreAnnoying, VeryLongImportsAreAnnoying, VeryLongImportsAreAnnoying,} from "some/module.js" 1665 /// \endcode 1666 bool JavaScriptWrapImports; 1667 // clang-format on 1668 1669 /// If true, the empty line at the start of blocks is kept. 1670 /// \code 1671 /// true: false: 1672 /// if (foo) { vs. if (foo) { 1673 /// bar(); 1674 /// bar(); } 1675 /// } 1676 /// \endcode 1677 bool KeepEmptyLinesAtTheStartOfBlocks; 1678 1679 /// Supported languages. 1680 /// 1681 /// When stored in a configuration file, specifies the language, that the 1682 /// configuration targets. When passed to the ``reformat()`` function, enables 1683 /// syntax features specific to the language. 1684 enum LanguageKind { 1685 /// Do not use. 1686 LK_None, 1687 /// Should be used for C, C++. 1688 LK_Cpp, 1689 /// Should be used for C#. 1690 LK_CSharp, 1691 /// Should be used for Java. 1692 LK_Java, 1693 /// Should be used for JavaScript. 1694 LK_JavaScript, 1695 /// Should be used for Objective-C, Objective-C++. 1696 LK_ObjC, 1697 /// Should be used for Protocol Buffers 1698 /// (https://developers.google.com/protocol-buffers/). 1699 LK_Proto, 1700 /// Should be used for TableGen code. 1701 LK_TableGen, 1702 /// Should be used for Protocol Buffer messages in text format 1703 /// (https://developers.google.com/protocol-buffers/). 1704 LK_TextProto 1705 }; 1706 bool isCpp() const { return Language == LK_Cpp || Language == LK_ObjC; } 1707 bool isCSharp() const { return Language == LK_CSharp; } 1708 1709 /// Language, this format style is targeted at. 1710 LanguageKind Language; 1711 1712 /// A regular expression matching macros that start a block. 1713 /// \code 1714 /// # With: 1715 /// MacroBlockBegin: "^NS_MAP_BEGIN|\ 1716 /// NS_TABLE_HEAD$" 1717 /// MacroBlockEnd: "^\ 1718 /// NS_MAP_END|\ 1719 /// NS_TABLE_.*_END$" 1720 /// 1721 /// NS_MAP_BEGIN 1722 /// foo(); 1723 /// NS_MAP_END 1724 /// 1725 /// NS_TABLE_HEAD 1726 /// bar(); 1727 /// NS_TABLE_FOO_END 1728 /// 1729 /// # Without: 1730 /// NS_MAP_BEGIN 1731 /// foo(); 1732 /// NS_MAP_END 1733 /// 1734 /// NS_TABLE_HEAD 1735 /// bar(); 1736 /// NS_TABLE_FOO_END 1737 /// \endcode 1738 std::string MacroBlockBegin; 1739 1740 /// A regular expression matching macros that end a block. 1741 std::string MacroBlockEnd; 1742 1743 /// The maximum number of consecutive empty lines to keep. 1744 /// \code 1745 /// MaxEmptyLinesToKeep: 1 vs. MaxEmptyLinesToKeep: 0 1746 /// int f() { int f() { 1747 /// int = 1; int i = 1; 1748 /// i = foo(); 1749 /// i = foo(); return i; 1750 /// } 1751 /// return i; 1752 /// } 1753 /// \endcode 1754 unsigned MaxEmptyLinesToKeep; 1755 1756 /// Different ways to indent namespace contents. 1757 enum NamespaceIndentationKind { 1758 /// Don't indent in namespaces. 1759 /// \code 1760 /// namespace out { 1761 /// int i; 1762 /// namespace in { 1763 /// int i; 1764 /// } 1765 /// } 1766 /// \endcode 1767 NI_None, 1768 /// Indent only in inner namespaces (nested in other namespaces). 1769 /// \code 1770 /// namespace out { 1771 /// int i; 1772 /// namespace in { 1773 /// int i; 1774 /// } 1775 /// } 1776 /// \endcode 1777 NI_Inner, 1778 /// Indent in all namespaces. 1779 /// \code 1780 /// namespace out { 1781 /// int i; 1782 /// namespace in { 1783 /// int i; 1784 /// } 1785 /// } 1786 /// \endcode 1787 NI_All 1788 }; 1789 1790 /// The indentation used for namespaces. 1791 NamespaceIndentationKind NamespaceIndentation; 1792 1793 /// Controls bin-packing Objective-C protocol conformance list 1794 /// items into as few lines as possible when they go over ``ColumnLimit``. 1795 /// 1796 /// If ``Auto`` (the default), delegates to the value in 1797 /// ``BinPackParameters``. If that is ``true``, bin-packs Objective-C 1798 /// protocol conformance list items into as few lines as possible 1799 /// whenever they go over ``ColumnLimit``. 1800 /// 1801 /// If ``Always``, always bin-packs Objective-C protocol conformance 1802 /// list items into as few lines as possible whenever they go over 1803 /// ``ColumnLimit``. 1804 /// 1805 /// If ``Never``, lays out Objective-C protocol conformance list items 1806 /// onto individual lines whenever they go over ``ColumnLimit``. 1807 /// 1808 /// \code{.objc} 1809 /// Always (or Auto, if BinPackParameters=true): 1810 /// @interface ccccccccccccc () < 1811 /// ccccccccccccc, ccccccccccccc, 1812 /// ccccccccccccc, ccccccccccccc> { 1813 /// } 1814 /// 1815 /// Never (or Auto, if BinPackParameters=false): 1816 /// @interface ddddddddddddd () < 1817 /// ddddddddddddd, 1818 /// ddddddddddddd, 1819 /// ddddddddddddd, 1820 /// ddddddddddddd> { 1821 /// } 1822 /// \endcode 1823 BinPackStyle ObjCBinPackProtocolList; 1824 1825 /// The number of characters to use for indentation of ObjC blocks. 1826 /// \code{.objc} 1827 /// ObjCBlockIndentWidth: 4 1828 /// 1829 /// [operation setCompletionBlock:^{ 1830 /// [self onOperationDone]; 1831 /// }]; 1832 /// \endcode 1833 unsigned ObjCBlockIndentWidth; 1834 1835 /// Add a space after ``@property`` in Objective-C, i.e. use 1836 /// ``@property (readonly)`` instead of ``@property(readonly)``. 1837 bool ObjCSpaceAfterProperty; 1838 1839 /// Break parameters list into lines when there is nested block 1840 /// parameters in a fuction call. 1841 /// \code 1842 /// false: 1843 /// - (void)_aMethod 1844 /// { 1845 /// [self.test1 t:self w:self callback:^(typeof(self) self, NSNumber 1846 /// *u, NSNumber *v) { 1847 /// u = c; 1848 /// }] 1849 /// } 1850 /// true: 1851 /// - (void)_aMethod 1852 /// { 1853 /// [self.test1 t:self 1854 /// w:self 1855 /// callback:^(typeof(self) self, NSNumber *u, NSNumber *v) { 1856 /// u = c; 1857 /// }] 1858 /// } 1859 /// \endcode 1860 bool ObjCBreakBeforeNestedBlockParam; 1861 1862 /// Add a space in front of an Objective-C protocol list, i.e. use 1863 /// ``Foo <Protocol>`` instead of ``Foo<Protocol>``. 1864 bool ObjCSpaceBeforeProtocolList; 1865 1866 /// The penalty for breaking around an assignment operator. 1867 unsigned PenaltyBreakAssignment; 1868 1869 /// The penalty for breaking a function call after ``call(``. 1870 unsigned PenaltyBreakBeforeFirstCallParameter; 1871 1872 /// The penalty for each line break introduced inside a comment. 1873 unsigned PenaltyBreakComment; 1874 1875 /// The penalty for breaking before the first ``<<``. 1876 unsigned PenaltyBreakFirstLessLess; 1877 1878 /// The penalty for each line break introduced inside a string literal. 1879 unsigned PenaltyBreakString; 1880 1881 /// The penalty for breaking after template declaration. 1882 unsigned PenaltyBreakTemplateDeclaration; 1883 1884 /// The penalty for each character outside of the column limit. 1885 unsigned PenaltyExcessCharacter; 1886 1887 /// Penalty for putting the return type of a function onto its own 1888 /// line. 1889 unsigned PenaltyReturnTypeOnItsOwnLine; 1890 1891 /// The ``&`` and ``*`` alignment style. 1892 enum PointerAlignmentStyle { 1893 /// Align pointer to the left. 1894 /// \code 1895 /// int* a; 1896 /// \endcode 1897 PAS_Left, 1898 /// Align pointer to the right. 1899 /// \code 1900 /// int *a; 1901 /// \endcode 1902 PAS_Right, 1903 /// Align pointer in the middle. 1904 /// \code 1905 /// int * a; 1906 /// \endcode 1907 PAS_Middle 1908 }; 1909 1910 /// Pointer and reference alignment style. 1911 PointerAlignmentStyle PointerAlignment; 1912 1913 /// See documentation of ``RawStringFormats``. 1914 struct RawStringFormat { 1915 /// The language of this raw string. 1916 LanguageKind Language; 1917 /// A list of raw string delimiters that match this language. 1918 std::vector<std::string> Delimiters; 1919 /// A list of enclosing function names that match this language. 1920 std::vector<std::string> EnclosingFunctions; 1921 /// The canonical delimiter for this language. 1922 std::string CanonicalDelimiter; 1923 /// The style name on which this raw string format is based on. 1924 /// If not specified, the raw string format is based on the style that this 1925 /// format is based on. 1926 std::string BasedOnStyle; 1927 bool operator==(const RawStringFormat &Other) const { 1928 return Language == Other.Language && Delimiters == Other.Delimiters && 1929 EnclosingFunctions == Other.EnclosingFunctions && 1930 CanonicalDelimiter == Other.CanonicalDelimiter && 1931 BasedOnStyle == Other.BasedOnStyle; 1932 } 1933 }; 1934 1935 /// Defines hints for detecting supported languages code blocks in raw 1936 /// strings. 1937 /// 1938 /// A raw string with a matching delimiter or a matching enclosing function 1939 /// name will be reformatted assuming the specified language based on the 1940 /// style for that language defined in the .clang-format file. If no style has 1941 /// been defined in the .clang-format file for the specific language, a 1942 /// predefined style given by 'BasedOnStyle' is used. If 'BasedOnStyle' is not 1943 /// found, the formatting is based on llvm style. A matching delimiter takes 1944 /// precedence over a matching enclosing function name for determining the 1945 /// language of the raw string contents. 1946 /// 1947 /// If a canonical delimiter is specified, occurrences of other delimiters for 1948 /// the same language will be updated to the canonical if possible. 1949 /// 1950 /// There should be at most one specification per language and each delimiter 1951 /// and enclosing function should not occur in multiple specifications. 1952 /// 1953 /// To configure this in the .clang-format file, use: 1954 /// \code{.yaml} 1955 /// RawStringFormats: 1956 /// - Language: TextProto 1957 /// Delimiters: 1958 /// - 'pb' 1959 /// - 'proto' 1960 /// EnclosingFunctions: 1961 /// - 'PARSE_TEXT_PROTO' 1962 /// BasedOnStyle: google 1963 /// - Language: Cpp 1964 /// Delimiters: 1965 /// - 'cc' 1966 /// - 'cpp' 1967 /// BasedOnStyle: llvm 1968 /// CanonicalDelimiter: 'cc' 1969 /// \endcode 1970 std::vector<RawStringFormat> RawStringFormats; 1971 1972 // clang-format off 1973 /// If ``true``, clang-format will attempt to re-flow comments. 1974 /// \code 1975 /// false: 1976 /// // veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongComment with plenty of information 1977 /// /* second veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongComment with plenty of information */ 1978 /// 1979 /// true: 1980 /// // veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongComment with plenty of 1981 /// // information 1982 /// /* second veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongComment with plenty of 1983 /// * information */ 1984 /// \endcode 1985 bool ReflowComments; 1986 // clang-format on 1987 1988 /// If ``true``, clang-format will sort ``#includes``. 1989 /// \code 1990 /// false: true: 1991 /// #include "b.h" vs. #include "a.h" 1992 /// #include "a.h" #include "b.h" 1993 /// \endcode 1994 bool SortIncludes; 1995 1996 /// If ``true``, clang-format will sort using declarations. 1997 /// 1998 /// The order of using declarations is defined as follows: 1999 /// Split the strings by "::" and discard any initial empty strings. The last 2000 /// element of each list is a non-namespace name; all others are namespace 2001 /// names. Sort the lists of names lexicographically, where the sort order of 2002 /// individual names is that all non-namespace names come before all namespace 2003 /// names, and within those groups, names are in case-insensitive 2004 /// lexicographic order. 2005 /// \code 2006 /// false: true: 2007 /// using std::cout; vs. using std::cin; 2008 /// using std::cin; using std::cout; 2009 /// \endcode 2010 bool SortUsingDeclarations; 2011 2012 /// If ``true``, a space is inserted after C style casts. 2013 /// \code 2014 /// true: false: 2015 /// (int) i; vs. (int)i; 2016 /// \endcode 2017 bool SpaceAfterCStyleCast; 2018 2019 /// If ``true``, a space is inserted after the logical not operator (``!``). 2020 /// \code 2021 /// true: false: 2022 /// ! someExpression(); vs. !someExpression(); 2023 /// \endcode 2024 bool SpaceAfterLogicalNot; 2025 2026 /// If \c true, a space will be inserted after the 'template' keyword. 2027 /// \code 2028 /// true: false: 2029 /// template <int> void foo(); vs. template<int> void foo(); 2030 /// \endcode 2031 bool SpaceAfterTemplateKeyword; 2032 2033 /// If ``false``, spaces will be removed before assignment operators. 2034 /// \code 2035 /// true: false: 2036 /// int a = 5; vs. int a= 5; 2037 /// a += 42; a+= 42; 2038 /// \endcode 2039 bool SpaceBeforeAssignmentOperators; 2040 2041 /// If ``true``, a space will be inserted before a C++11 braced list 2042 /// used to initialize an object (after the preceding identifier or type). 2043 /// \code 2044 /// true: false: 2045 /// Foo foo { bar }; vs. Foo foo{ bar }; 2046 /// Foo {}; Foo{}; 2047 /// vector<int> { 1, 2, 3 }; vector<int>{ 1, 2, 3 }; 2048 /// new int[3] { 1, 2, 3 }; new int[3]{ 1, 2, 3 }; 2049 /// \endcode 2050 bool SpaceBeforeCpp11BracedList; 2051 2052 /// If ``false``, spaces will be removed before constructor initializer 2053 /// colon. 2054 /// \code 2055 /// true: false: 2056 /// Foo::Foo() : a(a) {} Foo::Foo(): a(a) {} 2057 /// \endcode 2058 bool SpaceBeforeCtorInitializerColon; 2059 2060 /// If ``false``, spaces will be removed before inheritance colon. 2061 /// \code 2062 /// true: false: 2063 /// class Foo : Bar {} vs. class Foo: Bar {} 2064 /// \endcode 2065 bool SpaceBeforeInheritanceColon; 2066 2067 /// Different ways to put a space before opening parentheses. 2068 enum SpaceBeforeParensOptions { 2069 /// Never put a space before opening parentheses. 2070 /// \code 2071 /// void f() { 2072 /// if(true) { 2073 /// f(); 2074 /// } 2075 /// } 2076 /// \endcode 2077 SBPO_Never, 2078 /// Put a space before opening parentheses only after control statement 2079 /// keywords (``for/if/while...``). 2080 /// \code 2081 /// void f() { 2082 /// if (true) { 2083 /// f(); 2084 /// } 2085 /// } 2086 /// \endcode 2087 SBPO_ControlStatements, 2088 /// Same as ``SBPO_ControlStatements`` except this option doesn't apply to 2089 /// ForEach macros. This is useful in projects where ForEach macros are 2090 /// treated as function calls instead of control statements. 2091 /// \code 2092 /// void f() { 2093 /// Q_FOREACH(...) { 2094 /// f(); 2095 /// } 2096 /// } 2097 /// \endcode 2098 SBPO_ControlStatementsExceptForEachMacros, 2099 /// Put a space before opening parentheses only if the parentheses are not 2100 /// empty i.e. '()' 2101 /// \code 2102 /// void() { 2103 /// if (true) { 2104 /// f(); 2105 /// g (x, y, z); 2106 /// } 2107 /// } 2108 /// \endcode 2109 SBPO_NonEmptyParentheses, 2110 /// Always put a space before opening parentheses, except when it's 2111 /// prohibited by the syntax rules (in function-like macro definitions) or 2112 /// when determined by other style rules (after unary operators, opening 2113 /// parentheses, etc.) 2114 /// \code 2115 /// void f () { 2116 /// if (true) { 2117 /// f (); 2118 /// } 2119 /// } 2120 /// \endcode 2121 SBPO_Always 2122 }; 2123 2124 /// Defines in which cases to put a space before opening parentheses. 2125 SpaceBeforeParensOptions SpaceBeforeParens; 2126 2127 /// If ``false``, spaces will be removed before range-based for loop 2128 /// colon. 2129 /// \code 2130 /// true: false: 2131 /// for (auto v : values) {} vs. for(auto v: values) {} 2132 /// \endcode 2133 bool SpaceBeforeRangeBasedForLoopColon; 2134 2135 /// If ``true``, spaces will be inserted into ``{}``. 2136 /// \code 2137 /// true: false: 2138 /// void f() { } vs. void f() {} 2139 /// while (true) { } while (true) {} 2140 /// \endcode 2141 bool SpaceInEmptyBlock; 2142 2143 /// If ``true``, spaces may be inserted into ``()``. 2144 /// \code 2145 /// true: false: 2146 /// void f( ) { vs. void f() { 2147 /// int x[] = {foo( ), bar( )}; int x[] = {foo(), bar()}; 2148 /// if (true) { if (true) { 2149 /// f( ); f(); 2150 /// } } 2151 /// } } 2152 /// \endcode 2153 bool SpaceInEmptyParentheses; 2154 2155 /// The number of spaces before trailing line comments 2156 /// (``//`` - comments). 2157 /// 2158 /// This does not affect trailing block comments (``/*`` - comments) as 2159 /// those commonly have different usage patterns and a number of special 2160 /// cases. 2161 /// \code 2162 /// SpacesBeforeTrailingComments: 3 2163 /// void f() { 2164 /// if (true) { // foo1 2165 /// f(); // bar 2166 /// } // foo 2167 /// } 2168 /// \endcode 2169 unsigned SpacesBeforeTrailingComments; 2170 2171 /// If ``true``, spaces will be inserted after ``<`` and before ``>`` 2172 /// in template argument lists. 2173 /// \code 2174 /// true: false: 2175 /// static_cast< int >(arg); vs. static_cast<int>(arg); 2176 /// std::function< void(int) > fct; std::function<void(int)> fct; 2177 /// \endcode 2178 bool SpacesInAngles; 2179 2180 /// If ``true``, spaces will be inserted around if/for/switch/while 2181 /// conditions. 2182 /// \code 2183 /// true: false: 2184 /// if ( a ) { ... } vs. if (a) { ... } 2185 /// while ( i < 5 ) { ... } while (i < 5) { ... } 2186 /// \endcode 2187 bool SpacesInConditionalStatement; 2188 2189 /// If ``true``, spaces are inserted inside container literals (e.g. 2190 /// ObjC and Javascript array and dict literals). 2191 /// \code{.js} 2192 /// true: false: 2193 /// var arr = [ 1, 2, 3 ]; vs. var arr = [1, 2, 3]; 2194 /// f({a : 1, b : 2, c : 3}); f({a: 1, b: 2, c: 3}); 2195 /// \endcode 2196 bool SpacesInContainerLiterals; 2197 2198 /// If ``true``, spaces may be inserted into C style casts. 2199 /// \code 2200 /// true: false: 2201 /// x = ( int32 )y vs. x = (int32)y 2202 /// \endcode 2203 bool SpacesInCStyleCastParentheses; 2204 2205 /// If ``true``, spaces will be inserted after ``(`` and before ``)``. 2206 /// \code 2207 /// true: false: 2208 /// t f( Deleted & ) & = delete; vs. t f(Deleted &) & = delete; 2209 /// \endcode 2210 bool SpacesInParentheses; 2211 2212 /// If ``true``, spaces will be inserted after ``[`` and before ``]``. 2213 /// Lambdas without arguments or unspecified size array declarations will not 2214 /// be affected. 2215 /// \code 2216 /// true: false: 2217 /// int a[ 5 ]; vs. int a[5]; 2218 /// std::unique_ptr<int[]> foo() {} // Won't be affected 2219 /// \endcode 2220 bool SpacesInSquareBrackets; 2221 2222 /// If ``true``, spaces will be before ``[``. 2223 /// Lambdas will not be affected. Only the first ``[`` will get a space added. 2224 /// \code 2225 /// true: false: 2226 /// int a [5]; vs. int a[5]; 2227 /// int a [5][5]; vs. int a[5][5]; 2228 /// \endcode 2229 bool SpaceBeforeSquareBrackets; 2230 2231 /// Supported language standards for parsing and formatting C++ constructs. 2232 /// \code 2233 /// Latest: vector<set<int>> 2234 /// c++03 vs. vector<set<int> > 2235 /// \endcode 2236 /// 2237 /// The correct way to spell a specific language version is e.g. ``c++11``. 2238 /// The historical aliases ``Cpp03`` and ``Cpp11`` are deprecated. 2239 enum LanguageStandard { 2240 /// Parse and format as C++03. 2241 /// ``Cpp03`` is a deprecated alias for ``c++03`` 2242 LS_Cpp03, // c++03 2243 /// Parse and format as C++11. 2244 LS_Cpp11, // c++11 2245 /// Parse and format as C++14. 2246 LS_Cpp14, // c++14 2247 /// Parse and format as C++17. 2248 LS_Cpp17, // c++17 2249 /// Parse and format as C++20. 2250 LS_Cpp20, // c++20 2251 /// Parse and format using the latest supported language version. 2252 /// ``Cpp11`` is a deprecated alias for ``Latest`` 2253 LS_Latest, 2254 /// Automatic detection based on the input. 2255 LS_Auto, 2256 }; 2257 2258 /// Parse and format C++ constructs compatible with this standard. 2259 /// \code 2260 /// c++03: latest: 2261 /// vector<set<int> > x; vs. vector<set<int>> x; 2262 /// \endcode 2263 LanguageStandard Standard; 2264 2265 /// The number of columns used for tab stops. 2266 unsigned TabWidth; 2267 2268 /// Different ways to use tab in formatting. 2269 enum UseTabStyle { 2270 /// Never use tab. 2271 UT_Never, 2272 /// Use tabs only for indentation. 2273 UT_ForIndentation, 2274 /// Fill all leading whitespace with tabs, and use spaces for alignment that 2275 /// appears within a line (e.g. consecutive assignments and declarations). 2276 UT_ForContinuationAndIndentation, 2277 /// Use tabs for line continuation and indentation, and spaces for 2278 /// alignment. 2279 UT_AlignWithSpaces, 2280 /// Use tabs whenever we need to fill whitespace that spans at least from 2281 /// one tab stop to the next one. 2282 UT_Always 2283 }; 2284 2285 /// \brief Use ``\r\n`` instead of ``\n`` for line breaks. 2286 /// Also used as fallback if ``DeriveLineEnding`` is true. 2287 bool UseCRLF; 2288 2289 /// The way to use tab characters in the resulting file. 2290 UseTabStyle UseTab; 2291 2292 bool operator==(const FormatStyle &R) const { 2293 return AccessModifierOffset == R.AccessModifierOffset && 2294 AlignAfterOpenBracket == R.AlignAfterOpenBracket && 2295 AlignConsecutiveAssignments == R.AlignConsecutiveAssignments && 2296 AlignConsecutiveBitFields == R.AlignConsecutiveBitFields && 2297 AlignConsecutiveDeclarations == R.AlignConsecutiveDeclarations && 2298 AlignEscapedNewlines == R.AlignEscapedNewlines && 2299 AlignOperands == R.AlignOperands && 2300 AlignTrailingComments == R.AlignTrailingComments && 2301 AllowAllArgumentsOnNextLine == R.AllowAllArgumentsOnNextLine && 2302 AllowAllConstructorInitializersOnNextLine == 2303 R.AllowAllConstructorInitializersOnNextLine && 2304 AllowAllParametersOfDeclarationOnNextLine == 2305 R.AllowAllParametersOfDeclarationOnNextLine && 2306 AllowShortEnumsOnASingleLine == R.AllowShortEnumsOnASingleLine && 2307 AllowShortBlocksOnASingleLine == R.AllowShortBlocksOnASingleLine && 2308 AllowShortCaseLabelsOnASingleLine == 2309 R.AllowShortCaseLabelsOnASingleLine && 2310 AllowShortFunctionsOnASingleLine == 2311 R.AllowShortFunctionsOnASingleLine && 2312 AllowShortIfStatementsOnASingleLine == 2313 R.AllowShortIfStatementsOnASingleLine && 2314 AllowShortLambdasOnASingleLine == R.AllowShortLambdasOnASingleLine && 2315 AllowShortLoopsOnASingleLine == R.AllowShortLoopsOnASingleLine && 2316 AlwaysBreakAfterReturnType == R.AlwaysBreakAfterReturnType && 2317 AlwaysBreakBeforeMultilineStrings == 2318 R.AlwaysBreakBeforeMultilineStrings && 2319 AlwaysBreakTemplateDeclarations == 2320 R.AlwaysBreakTemplateDeclarations && 2321 BinPackArguments == R.BinPackArguments && 2322 BinPackParameters == R.BinPackParameters && 2323 BreakBeforeBinaryOperators == R.BreakBeforeBinaryOperators && 2324 BreakBeforeBraces == R.BreakBeforeBraces && 2325 BreakBeforeTernaryOperators == R.BreakBeforeTernaryOperators && 2326 BreakConstructorInitializers == R.BreakConstructorInitializers && 2327 CompactNamespaces == R.CompactNamespaces && 2328 BreakAfterJavaFieldAnnotations == R.BreakAfterJavaFieldAnnotations && 2329 BreakStringLiterals == R.BreakStringLiterals && 2330 ColumnLimit == R.ColumnLimit && CommentPragmas == R.CommentPragmas && 2331 BreakInheritanceList == R.BreakInheritanceList && 2332 ConstructorInitializerAllOnOneLineOrOnePerLine == 2333 R.ConstructorInitializerAllOnOneLineOrOnePerLine && 2334 ConstructorInitializerIndentWidth == 2335 R.ConstructorInitializerIndentWidth && 2336 ContinuationIndentWidth == R.ContinuationIndentWidth && 2337 Cpp11BracedListStyle == R.Cpp11BracedListStyle && 2338 DeriveLineEnding == R.DeriveLineEnding && 2339 DerivePointerAlignment == R.DerivePointerAlignment && 2340 DisableFormat == R.DisableFormat && 2341 ExperimentalAutoDetectBinPacking == 2342 R.ExperimentalAutoDetectBinPacking && 2343 FixNamespaceComments == R.FixNamespaceComments && 2344 ForEachMacros == R.ForEachMacros && 2345 IncludeStyle.IncludeBlocks == R.IncludeStyle.IncludeBlocks && 2346 IncludeStyle.IncludeCategories == R.IncludeStyle.IncludeCategories && 2347 IncludeStyle.IncludeIsMainRegex == 2348 R.IncludeStyle.IncludeIsMainRegex && 2349 IncludeStyle.IncludeIsMainSourceRegex == 2350 R.IncludeStyle.IncludeIsMainSourceRegex && 2351 IndentCaseLabels == R.IndentCaseLabels && 2352 IndentCaseBlocks == R.IndentCaseBlocks && 2353 IndentGotoLabels == R.IndentGotoLabels && 2354 IndentPPDirectives == R.IndentPPDirectives && 2355 IndentExternBlock == R.IndentExternBlock && 2356 IndentWidth == R.IndentWidth && Language == R.Language && 2357 IndentWrappedFunctionNames == R.IndentWrappedFunctionNames && 2358 JavaImportGroups == R.JavaImportGroups && 2359 JavaScriptQuotes == R.JavaScriptQuotes && 2360 JavaScriptWrapImports == R.JavaScriptWrapImports && 2361 KeepEmptyLinesAtTheStartOfBlocks == 2362 R.KeepEmptyLinesAtTheStartOfBlocks && 2363 MacroBlockBegin == R.MacroBlockBegin && 2364 MacroBlockEnd == R.MacroBlockEnd && 2365 MaxEmptyLinesToKeep == R.MaxEmptyLinesToKeep && 2366 NamespaceIndentation == R.NamespaceIndentation && 2367 NamespaceMacros == R.NamespaceMacros && 2368 ObjCBinPackProtocolList == R.ObjCBinPackProtocolList && 2369 ObjCBlockIndentWidth == R.ObjCBlockIndentWidth && 2370 ObjCBreakBeforeNestedBlockParam == 2371 R.ObjCBreakBeforeNestedBlockParam && 2372 ObjCSpaceAfterProperty == R.ObjCSpaceAfterProperty && 2373 ObjCSpaceBeforeProtocolList == R.ObjCSpaceBeforeProtocolList && 2374 PenaltyBreakAssignment == R.PenaltyBreakAssignment && 2375 PenaltyBreakBeforeFirstCallParameter == 2376 R.PenaltyBreakBeforeFirstCallParameter && 2377 PenaltyBreakComment == R.PenaltyBreakComment && 2378 PenaltyBreakFirstLessLess == R.PenaltyBreakFirstLessLess && 2379 PenaltyBreakString == R.PenaltyBreakString && 2380 PenaltyExcessCharacter == R.PenaltyExcessCharacter && 2381 PenaltyReturnTypeOnItsOwnLine == R.PenaltyReturnTypeOnItsOwnLine && 2382 PenaltyBreakTemplateDeclaration == 2383 R.PenaltyBreakTemplateDeclaration && 2384 PointerAlignment == R.PointerAlignment && 2385 RawStringFormats == R.RawStringFormats && 2386 SpaceAfterCStyleCast == R.SpaceAfterCStyleCast && 2387 SpaceAfterLogicalNot == R.SpaceAfterLogicalNot && 2388 SpaceAfterTemplateKeyword == R.SpaceAfterTemplateKeyword && 2389 SpaceBeforeAssignmentOperators == R.SpaceBeforeAssignmentOperators && 2390 SpaceBeforeCpp11BracedList == R.SpaceBeforeCpp11BracedList && 2391 SpaceBeforeCtorInitializerColon == 2392 R.SpaceBeforeCtorInitializerColon && 2393 SpaceBeforeInheritanceColon == R.SpaceBeforeInheritanceColon && 2394 SpaceBeforeParens == R.SpaceBeforeParens && 2395 SpaceBeforeRangeBasedForLoopColon == 2396 R.SpaceBeforeRangeBasedForLoopColon && 2397 SpaceInEmptyBlock == R.SpaceInEmptyBlock && 2398 SpaceInEmptyParentheses == R.SpaceInEmptyParentheses && 2399 SpacesBeforeTrailingComments == R.SpacesBeforeTrailingComments && 2400 SpacesInAngles == R.SpacesInAngles && 2401 SpacesInConditionalStatement == R.SpacesInConditionalStatement && 2402 SpacesInContainerLiterals == R.SpacesInContainerLiterals && 2403 SpacesInCStyleCastParentheses == R.SpacesInCStyleCastParentheses && 2404 SpacesInParentheses == R.SpacesInParentheses && 2405 SpacesInSquareBrackets == R.SpacesInSquareBrackets && 2406 SpaceBeforeSquareBrackets == R.SpaceBeforeSquareBrackets && 2407 Standard == R.Standard && TabWidth == R.TabWidth && 2408 StatementMacros == R.StatementMacros && UseTab == R.UseTab && 2409 UseCRLF == R.UseCRLF && TypenameMacros == R.TypenameMacros; 2410 } 2411 2412 llvm::Optional<FormatStyle> GetLanguageStyle(LanguageKind Language) const; 2413 2414 // Stores per-language styles. A FormatStyle instance inside has an empty 2415 // StyleSet. A FormatStyle instance returned by the Get method has its 2416 // StyleSet set to a copy of the originating StyleSet, effectively keeping the 2417 // internal representation of that StyleSet alive. 2418 // 2419 // The memory management and ownership reminds of a birds nest: chicks 2420 // leaving the nest take photos of the nest with them. 2421 struct FormatStyleSet { 2422 typedef std::map<FormatStyle::LanguageKind, FormatStyle> MapType; 2423 2424 llvm::Optional<FormatStyle> Get(FormatStyle::LanguageKind Language) const; 2425 2426 // Adds \p Style to this FormatStyleSet. Style must not have an associated 2427 // FormatStyleSet. 2428 // Style.Language should be different than LK_None. If this FormatStyleSet 2429 // already contains an entry for Style.Language, that gets replaced with the 2430 // passed Style. 2431 void Add(FormatStyle Style); 2432 2433 // Clears this FormatStyleSet. 2434 void Clear(); 2435 2436 private: 2437 std::shared_ptr<MapType> Styles; 2438 }; 2439 2440 static FormatStyleSet BuildStyleSetFromConfiguration( 2441 const FormatStyle &MainStyle, 2442 const std::vector<FormatStyle> &ConfigurationStyles); 2443 2444 private: 2445 FormatStyleSet StyleSet; 2446 2447 friend std::error_code parseConfiguration(StringRef Text, FormatStyle *Style); 2448 }; 2449 2450 /// Returns a format style complying with the LLVM coding standards: 2451 /// http://llvm.org/docs/CodingStandards.html. 2452 FormatStyle getLLVMStyle( 2453 FormatStyle::LanguageKind Language = FormatStyle::LanguageKind::LK_Cpp); 2454 2455 /// Returns a format style complying with one of Google's style guides: 2456 /// http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml. 2457 /// http://google-styleguide.googlecode.com/svn/trunk/javascriptguide.xml. 2458 /// https://developers.google.com/protocol-buffers/docs/style. 2459 FormatStyle getGoogleStyle(FormatStyle::LanguageKind Language); 2460 2461 /// Returns a format style complying with Chromium's style guide: 2462 /// http://www.chromium.org/developers/coding-style. 2463 FormatStyle getChromiumStyle(FormatStyle::LanguageKind Language); 2464 2465 /// Returns a format style complying with Mozilla's style guide: 2466 /// https://developer.mozilla.org/en-US/docs/Developer_Guide/Coding_Style. 2467 FormatStyle getMozillaStyle(); 2468 2469 /// Returns a format style complying with Webkit's style guide: 2470 /// http://www.webkit.org/coding/coding-style.html 2471 FormatStyle getWebKitStyle(); 2472 2473 /// Returns a format style complying with GNU Coding Standards: 2474 /// http://www.gnu.org/prep/standards/standards.html 2475 FormatStyle getGNUStyle(); 2476 2477 /// Returns a format style complying with Microsoft style guide: 2478 /// https://docs.microsoft.com/en-us/visualstudio/ide/editorconfig-code-style-settings-reference?view=vs-2017 2479 FormatStyle getMicrosoftStyle(FormatStyle::LanguageKind Language); 2480 2481 /// Returns style indicating formatting should be not applied at all. 2482 FormatStyle getNoStyle(); 2483 2484 /// Gets a predefined style for the specified language by name. 2485 /// 2486 /// Currently supported names: LLVM, Google, Chromium, Mozilla. Names are 2487 /// compared case-insensitively. 2488 /// 2489 /// Returns ``true`` if the Style has been set. 2490 bool getPredefinedStyle(StringRef Name, FormatStyle::LanguageKind Language, 2491 FormatStyle *Style); 2492 2493 /// Parse configuration from YAML-formatted text. 2494 /// 2495 /// Style->Language is used to get the base style, if the ``BasedOnStyle`` 2496 /// option is present. 2497 /// 2498 /// The FormatStyleSet of Style is reset. 2499 /// 2500 /// When ``BasedOnStyle`` is not present, options not present in the YAML 2501 /// document, are retained in \p Style. 2502 std::error_code parseConfiguration(StringRef Text, FormatStyle *Style); 2503 2504 /// Gets configuration in a YAML string. 2505 std::string configurationAsText(const FormatStyle &Style); 2506 2507 /// Returns the replacements necessary to sort all ``#include`` blocks 2508 /// that are affected by ``Ranges``. 2509 tooling::Replacements sortIncludes(const FormatStyle &Style, StringRef Code, 2510 ArrayRef<tooling::Range> Ranges, 2511 StringRef FileName, 2512 unsigned *Cursor = nullptr); 2513 2514 /// Returns the replacements corresponding to applying and formatting 2515 /// \p Replaces on success; otheriwse, return an llvm::Error carrying 2516 /// llvm::StringError. 2517 llvm::Expected<tooling::Replacements> 2518 formatReplacements(StringRef Code, const tooling::Replacements &Replaces, 2519 const FormatStyle &Style); 2520 2521 /// Returns the replacements corresponding to applying \p Replaces and 2522 /// cleaning up the code after that on success; otherwise, return an llvm::Error 2523 /// carrying llvm::StringError. 2524 /// This also supports inserting/deleting C++ #include directives: 2525 /// - If a replacement has offset UINT_MAX, length 0, and a replacement text 2526 /// that is an #include directive, this will insert the #include into the 2527 /// correct block in the \p Code. 2528 /// - If a replacement has offset UINT_MAX, length 1, and a replacement text 2529 /// that is the name of the header to be removed, the header will be removed 2530 /// from \p Code if it exists. 2531 /// The include manipulation is done via `tooling::HeaderInclude`, see its 2532 /// documentation for more details on how include insertion points are found and 2533 /// what edits are produced. 2534 llvm::Expected<tooling::Replacements> 2535 cleanupAroundReplacements(StringRef Code, const tooling::Replacements &Replaces, 2536 const FormatStyle &Style); 2537 2538 /// Represents the status of a formatting attempt. 2539 struct FormattingAttemptStatus { 2540 /// A value of ``false`` means that any of the affected ranges were not 2541 /// formatted due to a non-recoverable syntax error. 2542 bool FormatComplete = true; 2543 2544 /// If ``FormatComplete`` is false, ``Line`` records a one-based 2545 /// original line number at which a syntax error might have occurred. This is 2546 /// based on a best-effort analysis and could be imprecise. 2547 unsigned Line = 0; 2548 }; 2549 2550 /// Reformats the given \p Ranges in \p Code. 2551 /// 2552 /// Each range is extended on either end to its next bigger logic unit, i.e. 2553 /// everything that might influence its formatting or might be influenced by its 2554 /// formatting. 2555 /// 2556 /// Returns the ``Replacements`` necessary to make all \p Ranges comply with 2557 /// \p Style. 2558 /// 2559 /// If ``Status`` is non-null, its value will be populated with the status of 2560 /// this formatting attempt. See \c FormattingAttemptStatus. 2561 tooling::Replacements reformat(const FormatStyle &Style, StringRef Code, 2562 ArrayRef<tooling::Range> Ranges, 2563 StringRef FileName = "<stdin>", 2564 FormattingAttemptStatus *Status = nullptr); 2565 2566 /// Same as above, except if ``IncompleteFormat`` is non-null, its value 2567 /// will be set to true if any of the affected ranges were not formatted due to 2568 /// a non-recoverable syntax error. 2569 tooling::Replacements reformat(const FormatStyle &Style, StringRef Code, 2570 ArrayRef<tooling::Range> Ranges, 2571 StringRef FileName, bool *IncompleteFormat); 2572 2573 /// Clean up any erroneous/redundant code in the given \p Ranges in \p 2574 /// Code. 2575 /// 2576 /// Returns the ``Replacements`` that clean up all \p Ranges in \p Code. 2577 tooling::Replacements cleanup(const FormatStyle &Style, StringRef Code, 2578 ArrayRef<tooling::Range> Ranges, 2579 StringRef FileName = "<stdin>"); 2580 2581 /// Fix namespace end comments in the given \p Ranges in \p Code. 2582 /// 2583 /// Returns the ``Replacements`` that fix the namespace comments in all 2584 /// \p Ranges in \p Code. 2585 tooling::Replacements fixNamespaceEndComments(const FormatStyle &Style, 2586 StringRef Code, 2587 ArrayRef<tooling::Range> Ranges, 2588 StringRef FileName = "<stdin>"); 2589 2590 /// Sort consecutive using declarations in the given \p Ranges in 2591 /// \p Code. 2592 /// 2593 /// Returns the ``Replacements`` that sort the using declarations in all 2594 /// \p Ranges in \p Code. 2595 tooling::Replacements sortUsingDeclarations(const FormatStyle &Style, 2596 StringRef Code, 2597 ArrayRef<tooling::Range> Ranges, 2598 StringRef FileName = "<stdin>"); 2599 2600 /// Returns the ``LangOpts`` that the formatter expects you to set. 2601 /// 2602 /// \param Style determines specific settings for lexing mode. 2603 LangOptions getFormattingLangOpts(const FormatStyle &Style = getLLVMStyle()); 2604 2605 /// Description to be used for help text for a ``llvm::cl`` option for 2606 /// specifying format style. The description is closely related to the operation 2607 /// of ``getStyle()``. 2608 extern const char *StyleOptionHelpDescription; 2609 2610 /// The suggested format style to use by default. This allows tools using 2611 /// `getStyle` to have a consistent default style. 2612 /// Different builds can modify the value to the preferred styles. 2613 extern const char *DefaultFormatStyle; 2614 2615 /// The suggested predefined style to use as the fallback style in `getStyle`. 2616 /// Different builds can modify the value to the preferred styles. 2617 extern const char *DefaultFallbackStyle; 2618 2619 /// Construct a FormatStyle based on ``StyleName``. 2620 /// 2621 /// ``StyleName`` can take several forms: 2622 /// * "{<key>: <value>, ...}" - Set specic style parameters. 2623 /// * "<style name>" - One of the style names supported by 2624 /// getPredefinedStyle(). 2625 /// * "file" - Load style configuration from a file called ``.clang-format`` 2626 /// located in one of the parent directories of ``FileName`` or the current 2627 /// directory if ``FileName`` is empty. 2628 /// 2629 /// \param[in] StyleName Style name to interpret according to the description 2630 /// above. 2631 /// \param[in] FileName Path to start search for .clang-format if ``StyleName`` 2632 /// == "file". 2633 /// \param[in] FallbackStyle The name of a predefined style used to fallback to 2634 /// in case \p StyleName is "file" and no file can be found. 2635 /// \param[in] Code The actual code to be formatted. Used to determine the 2636 /// language if the filename isn't sufficient. 2637 /// \param[in] FS The underlying file system, in which the file resides. By 2638 /// default, the file system is the real file system. 2639 /// 2640 /// \returns FormatStyle as specified by ``StyleName``. If ``StyleName`` is 2641 /// "file" and no file is found, returns ``FallbackStyle``. If no style could be 2642 /// determined, returns an Error. 2643 llvm::Expected<FormatStyle> getStyle(StringRef StyleName, StringRef FileName, 2644 StringRef FallbackStyle, 2645 StringRef Code = "", 2646 llvm::vfs::FileSystem *FS = nullptr); 2647 2648 // Guesses the language from the ``FileName`` and ``Code`` to be formatted. 2649 // Defaults to FormatStyle::LK_Cpp. 2650 FormatStyle::LanguageKind guessLanguage(StringRef FileName, StringRef Code); 2651 2652 // Returns a string representation of ``Language``. 2653 inline StringRef getLanguageName(FormatStyle::LanguageKind Language) { 2654 switch (Language) { 2655 case FormatStyle::LK_Cpp: 2656 return "C++"; 2657 case FormatStyle::LK_CSharp: 2658 return "CSharp"; 2659 case FormatStyle::LK_ObjC: 2660 return "Objective-C"; 2661 case FormatStyle::LK_Java: 2662 return "Java"; 2663 case FormatStyle::LK_JavaScript: 2664 return "JavaScript"; 2665 case FormatStyle::LK_Proto: 2666 return "Proto"; 2667 case FormatStyle::LK_TableGen: 2668 return "TableGen"; 2669 case FormatStyle::LK_TextProto: 2670 return "TextProto"; 2671 default: 2672 return "Unknown"; 2673 } 2674 } 2675 2676 } // end namespace format 2677 } // end namespace clang 2678 2679 namespace std { 2680 template <> 2681 struct is_error_code_enum<clang::format::ParseError> : std::true_type {}; 2682 } // namespace std 2683 2684 #endif // LLVM_CLANG_FORMAT_FORMAT_H 2685