1//===--- Format.h - Format C++ code -----------------------------*- C++ -*-===// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file is distributed under the University of Illinois Open Source 6// License. See LICENSE.TXT for details. 7// 8//===----------------------------------------------------------------------===// 9/// 10/// \file 11/// Various functions to configurably format source code. 12/// 13//===----------------------------------------------------------------------===// 14 15#ifndef LLVM_CLANG_FORMAT_FORMAT_H 16#define LLVM_CLANG_FORMAT_FORMAT_H 17 18#include "clang/Basic/LangOptions.h" 19#include "clang/Tooling/Core/Replacement.h" 20#include "llvm/ADT/ArrayRef.h" 21#include <system_error> 22 23namespace clang { 24 25class Lexer; 26class SourceManager; 27class DiagnosticConsumer; 28 29namespace vfs { 30class FileSystem; 31} 32 33namespace format { 34 35enum class ParseError { Success = 0, Error, Unsuitable }; 36class ParseErrorCategory final : public std::error_category { 37public: 38 const char *name() const noexcept override; 39 std::string message(int EV) const override; 40}; 41const std::error_category &getParseCategory(); 42std::error_code make_error_code(ParseError e); 43 44/// \brief The ``FormatStyle`` is used to configure the formatting to follow 45/// specific guidelines. 46struct FormatStyle { 47 /// \brief The extra indent or outdent of access modifiers, e.g. ``public:``. 48 int AccessModifierOffset; 49 50 /// \brief Different styles for aligning after open brackets. 51 enum BracketAlignmentStyle { 52 /// \brief Align parameters on the open bracket, e.g.: 53 /// \code 54 /// someLongFunction(argument1, 55 /// argument2); 56 /// \endcode 57 BAS_Align, 58 /// \brief Don't align, instead use ``ContinuationIndentWidth``, e.g.: 59 /// \code 60 /// someLongFunction(argument1, 61 /// argument2); 62 /// \endcode 63 BAS_DontAlign, 64 /// \brief Always break after an open bracket, if the parameters don't fit 65 /// on a single line, e.g.: 66 /// \code 67 /// someLongFunction( 68 /// argument1, argument2); 69 /// \endcode 70 BAS_AlwaysBreak, 71 }; 72 73 /// \brief If ``true``, horizontally aligns arguments after an open bracket. 74 /// 75 /// This applies to round brackets (parentheses), angle brackets and square 76 /// brackets. 77 BracketAlignmentStyle AlignAfterOpenBracket; 78 79 /// \brief If ``true``, aligns consecutive assignments. 80 /// 81 /// This will align the assignment operators of consecutive lines. This 82 /// will result in formattings like 83 /// \code 84 /// int aaaa = 12; 85 /// int b = 23; 86 /// int ccc = 23; 87 /// \endcode 88 bool AlignConsecutiveAssignments; 89 90 /// \brief If ``true``, aligns consecutive declarations. 91 /// 92 /// This will align the declaration names of consecutive lines. This 93 /// will result in formattings like 94 /// \code 95 /// int aaaa = 12; 96 /// float b = 23; 97 /// std::string ccc = 23; 98 /// \endcode 99 bool AlignConsecutiveDeclarations; 100 101 /// \brief Different styles for aligning escaped newlines. 102 enum EscapedNewlineAlignmentStyle { 103 /// \brief Don't align escaped newlines. 104 /// \code 105 /// #define A \ 106 /// int aaaa; \ 107 /// int b; \ 108 /// int dddddddddd; 109 /// \endcode 110 ENAS_DontAlign, 111 /// \brief Align escaped newlines as far left as possible. 112 /// \code 113 /// true: 114 /// #define A \ 115 /// int aaaa; \ 116 /// int b; \ 117 /// int dddddddddd; 118 /// 119 /// false: 120 /// \endcode 121 ENAS_Left, 122 /// \brief Align escaped newlines in the right-most column. 123 /// \code 124 /// #define A \ 125 /// int aaaa; \ 126 /// int b; \ 127 /// int dddddddddd; 128 /// \endcode 129 ENAS_Right, 130 }; 131 132 /// \brief Options for aligning backslashes in escaped newlines. 133 EscapedNewlineAlignmentStyle AlignEscapedNewlines; 134 135 /// \brief If ``true``, horizontally align operands of binary and ternary 136 /// expressions. 137 /// 138 /// Specifically, this aligns operands of a single expression that needs to be 139 /// split over multiple lines, e.g.: 140 /// \code 141 /// int aaa = bbbbbbbbbbbbbbb + 142 /// ccccccccccccccc; 143 /// \endcode 144 bool AlignOperands; 145 146 /// \brief If ``true``, aligns trailing comments. 147 /// \code 148 /// true: false: 149 /// int a; // My comment a vs. int a; // My comment a 150 /// int b = 2; // comment b int b = 2; // comment about b 151 /// \endcode 152 bool AlignTrailingComments; 153 154 /// \brief If the function declaration doesn't fit on a line, 155 /// allow putting all parameters of a function declaration onto 156 /// the next line even if ``BinPackParameters`` is ``false``. 157 /// \code 158 /// true: 159 /// void myFunction( 160 /// int a, int b, int c, int d, int e); 161 /// 162 /// false: 163 /// void myFunction(int a, 164 /// int b, 165 /// int c, 166 /// int d, 167 /// int e); 168 /// \endcode 169 bool AllowAllParametersOfDeclarationOnNextLine; 170 171 /// \brief Allows contracting simple braced statements to a single line. 172 /// 173 /// E.g., this allows ``if (a) { return; }`` to be put on a single line. 174 bool AllowShortBlocksOnASingleLine; 175 176 /// \brief If ``true``, short case labels will be contracted to a single line. 177 /// \code 178 /// true: false: 179 /// switch (a) { vs. switch (a) { 180 /// case 1: x = 1; break; case 1: 181 /// case 2: return; x = 1; 182 /// } break; 183 /// case 2: 184 /// return; 185 /// } 186 /// \endcode 187 bool AllowShortCaseLabelsOnASingleLine; 188 189 /// \brief Different styles for merging short functions containing at most one 190 /// statement. 191 enum ShortFunctionStyle { 192 /// \brief Never merge functions into a single line. 193 SFS_None, 194 /// \brief Only merge functions defined inside a class. Same as "inline", 195 /// except it does not implies "empty": i.e. top level empty functions 196 /// are not merged either. 197 /// \code 198 /// class Foo { 199 /// void f() { foo(); } 200 /// }; 201 /// void f() { 202 /// foo(); 203 /// } 204 /// void f() { 205 /// } 206 /// \endcode 207 SFS_InlineOnly, 208 /// \brief Only merge empty functions. 209 /// \code 210 /// void f() {} 211 /// void f2() { 212 /// bar2(); 213 /// } 214 /// \endcode 215 SFS_Empty, 216 /// \brief Only merge functions defined inside a class. Implies "empty". 217 /// \code 218 /// class Foo { 219 /// void f() { foo(); } 220 /// }; 221 /// void f() { 222 /// foo(); 223 /// } 224 /// void f() {} 225 /// \endcode 226 SFS_Inline, 227 /// \brief Merge all functions fitting on a single line. 228 /// \code 229 /// class Foo { 230 /// void f() { foo(); } 231 /// }; 232 /// void f() { bar(); } 233 /// \endcode 234 SFS_All, 235 }; 236 237 /// \brief Dependent on the value, ``int f() { return 0; }`` can be put on a 238 /// single line. 239 ShortFunctionStyle AllowShortFunctionsOnASingleLine; 240 241 /// \brief If ``true``, ``if (a) return;`` can be put on a single line. 242 bool AllowShortIfStatementsOnASingleLine; 243 244 /// \brief If ``true``, ``while (true) continue;`` can be put on a single 245 /// line. 246 bool AllowShortLoopsOnASingleLine; 247 248 /// \brief Different ways to break after the function definition return type. 249 /// This option is **deprecated** and is retained for backwards compatibility. 250 enum DefinitionReturnTypeBreakingStyle { 251 /// Break after return type automatically. 252 /// ``PenaltyReturnTypeOnItsOwnLine`` is taken into account. 253 DRTBS_None, 254 /// Always break after the return type. 255 DRTBS_All, 256 /// Always break after the return types of top-level functions. 257 DRTBS_TopLevel, 258 }; 259 260 /// \brief Different ways to break after the function definition or 261 /// declaration return type. 262 enum ReturnTypeBreakingStyle { 263 /// Break after return type automatically. 264 /// ``PenaltyReturnTypeOnItsOwnLine`` is taken into account. 265 /// \code 266 /// class A { 267 /// int f() { return 0; }; 268 /// }; 269 /// int f(); 270 /// int f() { return 1; } 271 /// \endcode 272 RTBS_None, 273 /// Always break after the return type. 274 /// \code 275 /// class A { 276 /// int 277 /// f() { 278 /// return 0; 279 /// }; 280 /// }; 281 /// int 282 /// f(); 283 /// int 284 /// f() { 285 /// return 1; 286 /// } 287 /// \endcode 288 RTBS_All, 289 /// Always break after the return types of top-level functions. 290 /// \code 291 /// class A { 292 /// int f() { return 0; }; 293 /// }; 294 /// int 295 /// f(); 296 /// int 297 /// f() { 298 /// return 1; 299 /// } 300 /// \endcode 301 RTBS_TopLevel, 302 /// Always break after the return type of function definitions. 303 /// \code 304 /// class A { 305 /// int 306 /// f() { 307 /// return 0; 308 /// }; 309 /// }; 310 /// int f(); 311 /// int 312 /// f() { 313 /// return 1; 314 /// } 315 /// \endcode 316 RTBS_AllDefinitions, 317 /// Always break after the return type of top-level definitions. 318 /// \code 319 /// class A { 320 /// int f() { return 0; }; 321 /// }; 322 /// int f(); 323 /// int 324 /// f() { 325 /// return 1; 326 /// } 327 /// \endcode 328 RTBS_TopLevelDefinitions, 329 }; 330 331 /// \brief The function definition return type breaking style to use. This 332 /// option is **deprecated** and is retained for backwards compatibility. 333 DefinitionReturnTypeBreakingStyle AlwaysBreakAfterDefinitionReturnType; 334 335 /// \brief The function declaration return type breaking style to use. 336 ReturnTypeBreakingStyle AlwaysBreakAfterReturnType; 337 338 /// \brief If ``true``, always break before multiline string literals. 339 /// 340 /// This flag is mean to make cases where there are multiple multiline strings 341 /// in a file look more consistent. Thus, it will only take effect if wrapping 342 /// the string at that point leads to it being indented 343 /// ``ContinuationIndentWidth`` spaces from the start of the line. 344 /// \code 345 /// true: false: 346 /// aaaa = vs. aaaa = "bbbb" 347 /// "bbbb" "cccc"; 348 /// "cccc"; 349 /// \endcode 350 bool AlwaysBreakBeforeMultilineStrings; 351 352 /// \brief If ``true``, always break after the ``template<...>`` of a template 353 /// declaration. 354 /// \code 355 /// true: false: 356 /// template <typename T> vs. template <typename T> class C {}; 357 /// class C {}; 358 /// \endcode 359 bool AlwaysBreakTemplateDeclarations; 360 361 /// \brief If ``false``, a function call's arguments will either be all on the 362 /// same line or will have one line each. 363 /// \code 364 /// true: 365 /// void f() { 366 /// f(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaa, 367 /// aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa); 368 /// } 369 /// 370 /// false: 371 /// void f() { 372 /// f(aaaaaaaaaaaaaaaaaaaa, 373 /// aaaaaaaaaaaaaaaaaaaa, 374 /// aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa); 375 /// } 376 /// \endcode 377 bool BinPackArguments; 378 379 /// \brief If ``false``, a function declaration's or function definition's 380 /// parameters will either all be on the same line or will have one line each. 381 /// \code 382 /// true: 383 /// void f(int aaaaaaaaaaaaaaaaaaaa, int aaaaaaaaaaaaaaaaaaaa, 384 /// int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {} 385 /// 386 /// false: 387 /// void f(int aaaaaaaaaaaaaaaaaaaa, 388 /// int aaaaaaaaaaaaaaaaaaaa, 389 /// int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {} 390 /// \endcode 391 bool BinPackParameters; 392 393 /// \brief The style of breaking before or after binary operators. 394 enum BinaryOperatorStyle { 395 /// Break after operators. 396 /// \code 397 /// LooooooooooongType loooooooooooooooooooooongVariable = 398 /// someLooooooooooooooooongFunction(); 399 /// 400 /// bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa + 401 /// aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == 402 /// aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa && 403 /// aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa > 404 /// ccccccccccccccccccccccccccccccccccccccccc; 405 /// \endcode 406 BOS_None, 407 /// Break before operators that aren't assignments. 408 /// \code 409 /// LooooooooooongType loooooooooooooooooooooongVariable = 410 /// someLooooooooooooooooongFunction(); 411 /// 412 /// bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa 413 /// + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa 414 /// == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa 415 /// && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa 416 /// > ccccccccccccccccccccccccccccccccccccccccc; 417 /// \endcode 418 BOS_NonAssignment, 419 /// Break before operators. 420 /// \code 421 /// LooooooooooongType loooooooooooooooooooooongVariable 422 /// = someLooooooooooooooooongFunction(); 423 /// 424 /// bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa 425 /// + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa 426 /// == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa 427 /// && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa 428 /// > ccccccccccccccccccccccccccccccccccccccccc; 429 /// \endcode 430 BOS_All, 431 }; 432 433 /// \brief The way to wrap binary operators. 434 BinaryOperatorStyle BreakBeforeBinaryOperators; 435 436 /// \brief Different ways to attach braces to their surrounding context. 437 enum BraceBreakingStyle { 438 /// Always attach braces to surrounding context. 439 /// \code 440 /// try { 441 /// foo(); 442 /// } catch () { 443 /// } 444 /// void foo() { bar(); } 445 /// class foo {}; 446 /// if (foo()) { 447 /// } else { 448 /// } 449 /// enum X : int { A, B }; 450 /// \endcode 451 BS_Attach, 452 /// Like ``Attach``, but break before braces on function, namespace and 453 /// class definitions. 454 /// \code 455 /// try { 456 /// foo(); 457 /// } catch () { 458 /// } 459 /// void foo() { bar(); } 460 /// class foo 461 /// { 462 /// }; 463 /// if (foo()) { 464 /// } else { 465 /// } 466 /// enum X : int { A, B }; 467 /// \endcode 468 BS_Linux, 469 /// Like ``Attach``, but break before braces on enum, function, and record 470 /// definitions. 471 /// \code 472 /// try { 473 /// foo(); 474 /// } catch () { 475 /// } 476 /// void foo() { bar(); } 477 /// class foo 478 /// { 479 /// }; 480 /// if (foo()) { 481 /// } else { 482 /// } 483 /// enum X : int { A, B }; 484 /// \endcode 485 BS_Mozilla, 486 /// Like ``Attach``, but break before function definitions, ``catch``, and 487 /// ``else``. 488 /// \code 489 /// try { 490 /// foo(); 491 /// } catch () { 492 /// } 493 /// void foo() { bar(); } 494 /// class foo 495 /// { 496 /// }; 497 /// if (foo()) { 498 /// } else { 499 /// } 500 /// enum X : int 501 /// { 502 /// A, 503 /// B 504 /// }; 505 /// \endcode 506 BS_Stroustrup, 507 /// Always break before braces. 508 /// \code 509 /// try { 510 /// foo(); 511 /// } 512 /// catch () { 513 /// } 514 /// void foo() { bar(); } 515 /// class foo { 516 /// }; 517 /// if (foo()) { 518 /// } 519 /// else { 520 /// } 521 /// enum X : int { A, B }; 522 /// \endcode 523 BS_Allman, 524 /// Always break before braces and add an extra level of indentation to 525 /// braces of control statements, not to those of class, function 526 /// or other definitions. 527 /// \code 528 /// try 529 /// { 530 /// foo(); 531 /// } 532 /// catch () 533 /// { 534 /// } 535 /// void foo() { bar(); } 536 /// class foo 537 /// { 538 /// }; 539 /// if (foo()) 540 /// { 541 /// } 542 /// else 543 /// { 544 /// } 545 /// enum X : int 546 /// { 547 /// A, 548 /// B 549 /// }; 550 /// \endcode 551 BS_GNU, 552 /// Like ``Attach``, but break before functions. 553 /// \code 554 /// try { 555 /// foo(); 556 /// } catch () { 557 /// } 558 /// void foo() { bar(); } 559 /// class foo { 560 /// }; 561 /// if (foo()) { 562 /// } else { 563 /// } 564 /// enum X : int { A, B }; 565 /// \endcode 566 BS_WebKit, 567 /// Configure each individual brace in `BraceWrapping`. 568 BS_Custom 569 }; 570 571 /// \brief The brace breaking style to use. 572 BraceBreakingStyle BreakBeforeBraces; 573 574 /// \brief Precise control over the wrapping of braces. 575 /// \code 576 /// # Should be declared this way: 577 /// BreakBeforeBraces: Custom 578 /// BraceWrapping: 579 /// AfterClass: true 580 /// \endcode 581 struct BraceWrappingFlags { 582 /// \brief Wrap class definitions. 583 /// \code 584 /// true: 585 /// class foo {}; 586 /// 587 /// false: 588 /// class foo 589 /// {}; 590 /// \endcode 591 bool AfterClass; 592 /// \brief Wrap control statements (``if``/``for``/``while``/``switch``/..). 593 /// \code 594 /// true: 595 /// if (foo()) 596 /// { 597 /// } else 598 /// {} 599 /// for (int i = 0; i < 10; ++i) 600 /// {} 601 /// 602 /// false: 603 /// if (foo()) { 604 /// } else { 605 /// } 606 /// for (int i = 0; i < 10; ++i) { 607 /// } 608 /// \endcode 609 bool AfterControlStatement; 610 /// \brief Wrap enum definitions. 611 /// \code 612 /// true: 613 /// enum X : int 614 /// { 615 /// B 616 /// }; 617 /// 618 /// false: 619 /// enum X : int { B }; 620 /// \endcode 621 bool AfterEnum; 622 /// \brief Wrap function definitions. 623 /// \code 624 /// true: 625 /// void foo() 626 /// { 627 /// bar(); 628 /// bar2(); 629 /// } 630 /// 631 /// false: 632 /// void foo() { 633 /// bar(); 634 /// bar2(); 635 /// } 636 /// \endcode 637 bool AfterFunction; 638 /// \brief Wrap namespace definitions. 639 /// \code 640 /// true: 641 /// namespace 642 /// { 643 /// int foo(); 644 /// int bar(); 645 /// } 646 /// 647 /// false: 648 /// namespace { 649 /// int foo(); 650 /// int bar(); 651 /// } 652 /// \endcode 653 bool AfterNamespace; 654 /// \brief Wrap ObjC definitions (``@autoreleasepool``, interfaces, ..). 655 bool AfterObjCDeclaration; 656 /// \brief Wrap struct definitions. 657 /// \code 658 /// true: 659 /// struct foo 660 /// { 661 /// int x; 662 /// }; 663 /// 664 /// false: 665 /// struct foo { 666 /// int x; 667 /// }; 668 /// \endcode 669 bool AfterStruct; 670 /// \brief Wrap union definitions. 671 /// \code 672 /// true: 673 /// union foo 674 /// { 675 /// int x; 676 /// } 677 /// 678 /// false: 679 /// union foo { 680 /// int x; 681 /// } 682 /// \endcode 683 bool AfterUnion; 684 /// \brief Wrap extern blocks. 685 /// \code 686 /// true: 687 /// extern "C" 688 /// { 689 /// int foo(); 690 /// } 691 /// 692 /// false: 693 /// extern "C" { 694 /// int foo(); 695 /// } 696 /// \endcode 697 bool AfterExternBlock; 698 /// \brief Wrap before ``catch``. 699 /// \code 700 /// true: 701 /// try { 702 /// foo(); 703 /// } 704 /// catch () { 705 /// } 706 /// 707 /// false: 708 /// try { 709 /// foo(); 710 /// } catch () { 711 /// } 712 /// \endcode 713 bool BeforeCatch; 714 /// \brief Wrap before ``else``. 715 /// \code 716 /// true: 717 /// if (foo()) { 718 /// } 719 /// else { 720 /// } 721 /// 722 /// false: 723 /// if (foo()) { 724 /// } else { 725 /// } 726 /// \endcode 727 bool BeforeElse; 728 /// \brief Indent the wrapped braces themselves. 729 bool IndentBraces; 730 /// \brief If ``false``, empty function body can be put on a single line. 731 /// This option is used only if the opening brace of the function has 732 /// already been wrapped, i.e. the `AfterFunction` brace wrapping mode is 733 /// set, and the function could/should not be put on a single line (as per 734 /// `AllowShortFunctionsOnASingleLine` and constructor formatting options). 735 /// \code 736 /// int f() vs. inf f() 737 /// {} { 738 /// } 739 /// \endcode 740 /// 741 bool SplitEmptyFunction; 742 /// \brief If ``false``, empty record (e.g. class, struct or union) body 743 /// can be put on a single line. This option is used only if the opening 744 /// brace of the record has already been wrapped, i.e. the `AfterClass` 745 /// (for classes) brace wrapping mode is set. 746 /// \code 747 /// class Foo vs. class Foo 748 /// {} { 749 /// } 750 /// \endcode 751 /// 752 bool SplitEmptyRecord; 753 /// \brief If ``false``, empty namespace body can be put on a single line. 754 /// This option is used only if the opening brace of the namespace has 755 /// already been wrapped, i.e. the `AfterNamespace` brace wrapping mode is 756 /// set. 757 /// \code 758 /// namespace Foo vs. namespace Foo 759 /// {} { 760 /// } 761 /// \endcode 762 /// 763 bool SplitEmptyNamespace; 764 }; 765 766 /// \brief Control of individual brace wrapping cases. 767 /// 768 /// If ``BreakBeforeBraces`` is set to ``BS_Custom``, use this to specify how 769 /// each individual brace case should be handled. Otherwise, this is ignored. 770 /// \code{.yaml} 771 /// # Example of usage: 772 /// BreakBeforeBraces: Custom 773 /// BraceWrapping: 774 /// AfterEnum: true 775 /// AfterStruct: false 776 /// SplitEmptyFunction: false 777 /// \endcode 778 BraceWrappingFlags BraceWrapping; 779 780 /// \brief If ``true``, ternary operators will be placed after line breaks. 781 /// \code 782 /// true: 783 /// veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongDescription 784 /// ? firstValue 785 /// : SecondValueVeryVeryVeryVeryLong; 786 /// 787 /// false: 788 /// veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongDescription ? 789 /// firstValue : 790 /// SecondValueVeryVeryVeryVeryLong; 791 /// \endcode 792 bool BreakBeforeTernaryOperators; 793 794 /// \brief Different ways to break initializers. 795 enum BreakConstructorInitializersStyle { 796 /// Break constructor initializers before the colon and after the commas. 797 /// \code 798 /// Constructor() 799 /// : initializer1(), 800 /// initializer2() 801 /// \endcode 802 BCIS_BeforeColon, 803 /// Break constructor initializers before the colon and commas, and align 804 /// the commas with the colon. 805 /// \code 806 /// Constructor() 807 /// : initializer1() 808 /// , initializer2() 809 /// \endcode 810 BCIS_BeforeComma, 811 /// Break constructor initializers after the colon and commas. 812 /// \code 813 /// Constructor() : 814 /// initializer1(), 815 /// initializer2() 816 /// \endcode 817 BCIS_AfterColon 818 }; 819 820 /// \brief The constructor initializers style to use. 821 BreakConstructorInitializersStyle BreakConstructorInitializers; 822 823 /// \brief Break after each annotation on a field in Java files. 824 /// \code{.java} 825 /// true: false: 826 /// @Partial vs. @Partial @Mock DataLoad loader; 827 /// @Mock 828 /// DataLoad loader; 829 /// \endcode 830 bool BreakAfterJavaFieldAnnotations; 831 832 /// \brief Allow breaking string literals when formatting. 833 bool BreakStringLiterals; 834 835 /// \brief The column limit. 836 /// 837 /// A column limit of ``0`` means that there is no column limit. In this case, 838 /// clang-format will respect the input's line breaking decisions within 839 /// statements unless they contradict other rules. 840 unsigned ColumnLimit; 841 842 /// \brief A regular expression that describes comments with special meaning, 843 /// which should not be split into lines or otherwise changed. 844 /// \code 845 /// // CommentPragmas: '^ FOOBAR pragma:' 846 /// // Will leave the following line unaffected 847 /// #include <vector> // FOOBAR pragma: keep 848 /// \endcode 849 std::string CommentPragmas; 850 851 /// \brief If ``true``, in the class inheritance expression clang-format will 852 /// break before ``:`` and ``,`` if there is multiple inheritance. 853 /// \code 854 /// true: false: 855 /// class MyClass vs. class MyClass : public X, public Y { 856 /// : public X }; 857 /// , public Y { 858 /// }; 859 /// \endcode 860 bool BreakBeforeInheritanceComma; 861 862 /// \brief If ``true``, consecutive namespace declarations will be on the same 863 /// line. If ``false``, each namespace is declared on a new line. 864 /// \code 865 /// true: 866 /// namespace Foo { namespace Bar { 867 /// }} 868 /// 869 /// false: 870 /// namespace Foo { 871 /// namespace Bar { 872 /// } 873 /// } 874 /// \endcode 875 /// 876 /// If it does not fit on a single line, the overflowing namespaces get 877 /// wrapped: 878 /// \code 879 /// namespace Foo { namespace Bar { 880 /// namespace Extra { 881 /// }}} 882 /// \endcode 883 bool CompactNamespaces; 884 885 /// \brief If the constructor initializers don't fit on a line, put each 886 /// initializer on its own line. 887 /// \code 888 /// true: 889 /// SomeClass::Constructor() 890 /// : aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa) { 891 /// return 0; 892 /// } 893 /// 894 /// false: 895 /// SomeClass::Constructor() 896 /// : aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaa), 897 /// aaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa) { 898 /// return 0; 899 /// } 900 /// \endcode 901 bool ConstructorInitializerAllOnOneLineOrOnePerLine; 902 903 /// \brief The number of characters to use for indentation of constructor 904 /// initializer lists. 905 unsigned ConstructorInitializerIndentWidth; 906 907 /// \brief Indent width for line continuations. 908 /// \code 909 /// ContinuationIndentWidth: 2 910 /// 911 /// int i = // VeryVeryVeryVeryVeryLongComment 912 /// longFunction( // Again a long comment 913 /// arg); 914 /// \endcode 915 unsigned ContinuationIndentWidth; 916 917 /// \brief If ``true``, format braced lists as best suited for C++11 braced 918 /// lists. 919 /// 920 /// Important differences: 921 /// - No spaces inside the braced list. 922 /// - No line break before the closing brace. 923 /// - Indentation with the continuation indent, not with the block indent. 924 /// 925 /// Fundamentally, C++11 braced lists are formatted exactly like function 926 /// calls would be formatted in their place. If the braced list follows a name 927 /// (e.g. a type or variable name), clang-format formats as if the ``{}`` were 928 /// the parentheses of a function call with that name. If there is no name, 929 /// a zero-length name is assumed. 930 /// \code 931 /// true: false: 932 /// vector<int> x{1, 2, 3, 4}; vs. vector<int> x{ 1, 2, 3, 4 }; 933 /// vector<T> x{{}, {}, {}, {}}; vector<T> x{ {}, {}, {}, {} }; 934 /// f(MyMap[{composite, key}]); f(MyMap[{ composite, key }]); 935 /// new int[3]{1, 2, 3}; new int[3]{ 1, 2, 3 }; 936 /// \endcode 937 bool Cpp11BracedListStyle; 938 939 /// \brief If ``true``, analyze the formatted file for the most common 940 /// alignment of ``&`` and ``*``. 941 /// Pointer and reference alignment styles are going to be updated according 942 /// to the preferences found in the file. 943 /// ``PointerAlignment`` is then used only as fallback. 944 bool DerivePointerAlignment; 945 946 /// \brief Disables formatting completely. 947 bool DisableFormat; 948 949 /// \brief If ``true``, clang-format detects whether function calls and 950 /// definitions are formatted with one parameter per line. 951 /// 952 /// Each call can be bin-packed, one-per-line or inconclusive. If it is 953 /// inconclusive, e.g. completely on one line, but a decision needs to be 954 /// made, clang-format analyzes whether there are other bin-packed cases in 955 /// the input file and act accordingly. 956 /// 957 /// NOTE: This is an experimental flag, that might go away or be renamed. Do 958 /// not use this in config files, etc. Use at your own risk. 959 bool ExperimentalAutoDetectBinPacking; 960 961 /// \brief If ``true``, clang-format adds missing namespace end comments and 962 /// fixes invalid existing ones. 963 /// \code 964 /// true: false: 965 /// namespace a { vs. namespace a { 966 /// foo(); foo(); 967 /// } // namespace a; } 968 /// \endcode 969 bool FixNamespaceComments; 970 971 /// \brief A vector of macros that should be interpreted as foreach loops 972 /// instead of as function calls. 973 /// 974 /// These are expected to be macros of the form: 975 /// \code 976 /// FOREACH(<variable-declaration>, ...) 977 /// <loop-body> 978 /// \endcode 979 /// 980 /// In the .clang-format configuration file, this can be configured like: 981 /// \code{.yaml} 982 /// ForEachMacros: ['RANGES_FOR', 'FOREACH'] 983 /// \endcode 984 /// 985 /// For example: BOOST_FOREACH. 986 std::vector<std::string> ForEachMacros; 987 988 /// \brief See documentation of ``IncludeCategories``. 989 struct IncludeCategory { 990 /// \brief The regular expression that this category matches. 991 std::string Regex; 992 /// \brief The priority to assign to this category. 993 int Priority; 994 bool operator==(const IncludeCategory &Other) const { 995 return Regex == Other.Regex && Priority == Other.Priority; 996 } 997 }; 998 999 /// \brief Regular expressions denoting the different ``#include`` categories 1000 /// used for ordering ``#includes``. 1001 /// 1002 /// These regular expressions are matched against the filename of an include 1003 /// (including the <> or "") in order. The value belonging to the first 1004 /// matching regular expression is assigned and ``#includes`` are sorted first 1005 /// according to increasing category number and then alphabetically within 1006 /// each category. 1007 /// 1008 /// If none of the regular expressions match, INT_MAX is assigned as 1009 /// category. The main header for a source file automatically gets category 0. 1010 /// so that it is generally kept at the beginning of the ``#includes`` 1011 /// (http://llvm.org/docs/CodingStandards.html#include-style). However, you 1012 /// can also assign negative priorities if you have certain headers that 1013 /// always need to be first. 1014 /// 1015 /// To configure this in the .clang-format file, use: 1016 /// \code{.yaml} 1017 /// IncludeCategories: 1018 /// - Regex: '^"(llvm|llvm-c|clang|clang-c)/' 1019 /// Priority: 2 1020 /// - Regex: '^(<|"(gtest|gmock|isl|json)/)' 1021 /// Priority: 3 1022 /// - Regex: '.*' 1023 /// Priority: 1 1024 /// \endcode 1025 std::vector<IncludeCategory> IncludeCategories; 1026 1027 /// \brief Specify a regular expression of suffixes that are allowed in the 1028 /// file-to-main-include mapping. 1029 /// 1030 /// When guessing whether a #include is the "main" include (to assign 1031 /// category 0, see above), use this regex of allowed suffixes to the header 1032 /// stem. A partial match is done, so that: 1033 /// - "" means "arbitrary suffix" 1034 /// - "$" means "no suffix" 1035 /// 1036 /// For example, if configured to "(_test)?$", then a header a.h would be seen 1037 /// as the "main" include in both a.cc and a_test.cc. 1038 std::string IncludeIsMainRegex; 1039 1040 /// \brief Indent case labels one level from the switch statement. 1041 /// 1042 /// When ``false``, use the same indentation level as for the switch statement. 1043 /// Switch statement body is always indented one level more than case labels. 1044 /// \code 1045 /// false: true: 1046 /// switch (fool) { vs. switch (fool) { 1047 /// case 1: case 1: 1048 /// bar(); bar(); 1049 /// break; break; 1050 /// default: default: 1051 /// plop(); plop(); 1052 /// } } 1053 /// \endcode 1054 bool IndentCaseLabels; 1055 1056 /// \brief Options for indenting preprocessor directives. 1057 enum PPDirectiveIndentStyle { 1058 /// Does not indent any directives. 1059 /// \code 1060 /// #if FOO 1061 /// #if BAR 1062 /// #include <foo> 1063 /// #endif 1064 /// #endif 1065 /// \endcode 1066 PPDIS_None, 1067 /// Indents directives after the hash. 1068 /// \code 1069 /// #if FOO 1070 /// # if BAR 1071 /// # include <foo> 1072 /// # endif 1073 /// #endif 1074 /// \endcode 1075 PPDIS_AfterHash 1076 }; 1077 1078 /// \brief The preprocessor directive indenting style to use. 1079 PPDirectiveIndentStyle IndentPPDirectives; 1080 1081 /// \brief The number of columns to use for indentation. 1082 /// \code 1083 /// IndentWidth: 3 1084 /// 1085 /// void f() { 1086 /// someFunction(); 1087 /// if (true, false) { 1088 /// f(); 1089 /// } 1090 /// } 1091 /// \endcode 1092 unsigned IndentWidth; 1093 1094 /// \brief Indent if a function definition or declaration is wrapped after the 1095 /// type. 1096 /// \code 1097 /// true: 1098 /// LoooooooooooooooooooooooooooooooooooooooongReturnType 1099 /// LoooooooooooooooooooooooooooooooongFunctionDeclaration(); 1100 /// 1101 /// false: 1102 /// LoooooooooooooooooooooooooooooooooooooooongReturnType 1103 /// LoooooooooooooooooooooooooooooooongFunctionDeclaration(); 1104 /// \endcode 1105 bool IndentWrappedFunctionNames; 1106 1107 /// \brief Quotation styles for JavaScript strings. Does not affect template 1108 /// strings. 1109 enum JavaScriptQuoteStyle { 1110 /// Leave string quotes as they are. 1111 /// \code{.js} 1112 /// string1 = "foo"; 1113 /// string2 = 'bar'; 1114 /// \endcode 1115 JSQS_Leave, 1116 /// Always use single quotes. 1117 /// \code{.js} 1118 /// string1 = 'foo'; 1119 /// string2 = 'bar'; 1120 /// \endcode 1121 JSQS_Single, 1122 /// Always use double quotes. 1123 /// \code{.js} 1124 /// string1 = "foo"; 1125 /// string2 = "bar"; 1126 /// \endcode 1127 JSQS_Double 1128 }; 1129 1130 /// \brief The JavaScriptQuoteStyle to use for JavaScript strings. 1131 JavaScriptQuoteStyle JavaScriptQuotes; 1132 1133 /// \brief Whether to wrap JavaScript import/export statements. 1134 /// \code{.js} 1135 /// true: 1136 /// import { 1137 /// VeryLongImportsAreAnnoying, 1138 /// VeryLongImportsAreAnnoying, 1139 /// VeryLongImportsAreAnnoying, 1140 /// } from 'some/module.js' 1141 /// 1142 /// false: 1143 /// import {VeryLongImportsAreAnnoying, VeryLongImportsAreAnnoying, VeryLongImportsAreAnnoying,} from "some/module.js" 1144 /// \endcode 1145 bool JavaScriptWrapImports; 1146 1147 /// \brief If true, the empty line at the start of blocks is kept. 1148 /// \code 1149 /// true: false: 1150 /// if (foo) { vs. if (foo) { 1151 /// bar(); 1152 /// bar(); } 1153 /// } 1154 /// \endcode 1155 bool KeepEmptyLinesAtTheStartOfBlocks; 1156 1157 /// \brief Supported languages. 1158 /// 1159 /// When stored in a configuration file, specifies the language, that the 1160 /// configuration targets. When passed to the ``reformat()`` function, enables 1161 /// syntax features specific to the language. 1162 enum LanguageKind { 1163 /// Do not use. 1164 LK_None, 1165 /// Should be used for C, C++. 1166 LK_Cpp, 1167 /// Should be used for Java. 1168 LK_Java, 1169 /// Should be used for JavaScript. 1170 LK_JavaScript, 1171 /// Should be used for Objective-C, Objective-C++. 1172 LK_ObjC, 1173 /// Should be used for Protocol Buffers 1174 /// (https://developers.google.com/protocol-buffers/). 1175 LK_Proto, 1176 /// Should be used for TableGen code. 1177 LK_TableGen, 1178 /// Should be used for Protocol Buffer messages in text format 1179 /// (https://developers.google.com/protocol-buffers/). 1180 LK_TextProto 1181 }; 1182 bool isCpp() const { return Language == LK_Cpp || Language == LK_ObjC; } 1183 1184 /// \brief Language, this format style is targeted at. 1185 LanguageKind Language; 1186 1187 /// \brief A regular expression matching macros that start a block. 1188 /// \code 1189 /// # With: 1190 /// MacroBlockBegin: "^NS_MAP_BEGIN|\ 1191 /// NS_TABLE_HEAD$" 1192 /// MacroBlockEnd: "^\ 1193 /// NS_MAP_END|\ 1194 /// NS_TABLE_.*_END$" 1195 /// 1196 /// NS_MAP_BEGIN 1197 /// foo(); 1198 /// NS_MAP_END 1199 /// 1200 /// NS_TABLE_HEAD 1201 /// bar(); 1202 /// NS_TABLE_FOO_END 1203 /// 1204 /// # Without: 1205 /// NS_MAP_BEGIN 1206 /// foo(); 1207 /// NS_MAP_END 1208 /// 1209 /// NS_TABLE_HEAD 1210 /// bar(); 1211 /// NS_TABLE_FOO_END 1212 /// \endcode 1213 std::string MacroBlockBegin; 1214 1215 /// \brief A regular expression matching macros that end a block. 1216 std::string MacroBlockEnd; 1217 1218 /// \brief The maximum number of consecutive empty lines to keep. 1219 /// \code 1220 /// MaxEmptyLinesToKeep: 1 vs. MaxEmptyLinesToKeep: 0 1221 /// int f() { int f() { 1222 /// int = 1; int i = 1; 1223 /// i = foo(); 1224 /// i = foo(); return i; 1225 /// } 1226 /// return i; 1227 /// } 1228 /// \endcode 1229 unsigned MaxEmptyLinesToKeep; 1230 1231 /// \brief Different ways to indent namespace contents. 1232 enum NamespaceIndentationKind { 1233 /// Don't indent in namespaces. 1234 /// \code 1235 /// namespace out { 1236 /// int i; 1237 /// namespace in { 1238 /// int i; 1239 /// } 1240 /// } 1241 /// \endcode 1242 NI_None, 1243 /// Indent only in inner namespaces (nested in other namespaces). 1244 /// \code 1245 /// namespace out { 1246 /// int i; 1247 /// namespace in { 1248 /// int i; 1249 /// } 1250 /// } 1251 /// \endcode 1252 NI_Inner, 1253 /// Indent in all namespaces. 1254 /// \code 1255 /// namespace out { 1256 /// int i; 1257 /// namespace in { 1258 /// int i; 1259 /// } 1260 /// } 1261 /// \endcode 1262 NI_All 1263 }; 1264 1265 /// \brief The indentation used for namespaces. 1266 NamespaceIndentationKind NamespaceIndentation; 1267 1268 /// \brief The number of characters to use for indentation of ObjC blocks. 1269 /// \code{.objc} 1270 /// ObjCBlockIndentWidth: 4 1271 /// 1272 /// [operation setCompletionBlock:^{ 1273 /// [self onOperationDone]; 1274 /// }]; 1275 /// \endcode 1276 unsigned ObjCBlockIndentWidth; 1277 1278 /// \brief Add a space after ``@property`` in Objective-C, i.e. use 1279 /// ``@property (readonly)`` instead of ``@property(readonly)``. 1280 bool ObjCSpaceAfterProperty; 1281 1282 /// \brief Add a space in front of an Objective-C protocol list, i.e. use 1283 /// ``Foo <Protocol>`` instead of ``Foo<Protocol>``. 1284 bool ObjCSpaceBeforeProtocolList; 1285 1286 /// \brief The penalty for breaking around an assignment operator. 1287 unsigned PenaltyBreakAssignment; 1288 1289 /// \brief The penalty for breaking a function call after ``call(``. 1290 unsigned PenaltyBreakBeforeFirstCallParameter; 1291 1292 /// \brief The penalty for each line break introduced inside a comment. 1293 unsigned PenaltyBreakComment; 1294 1295 /// \brief The penalty for breaking before the first ``<<``. 1296 unsigned PenaltyBreakFirstLessLess; 1297 1298 /// \brief The penalty for each line break introduced inside a string literal. 1299 unsigned PenaltyBreakString; 1300 1301 /// \brief The penalty for each character outside of the column limit. 1302 unsigned PenaltyExcessCharacter; 1303 1304 /// \brief Penalty for putting the return type of a function onto its own 1305 /// line. 1306 unsigned PenaltyReturnTypeOnItsOwnLine; 1307 1308 /// \brief The ``&`` and ``*`` alignment style. 1309 enum PointerAlignmentStyle { 1310 /// Align pointer to the left. 1311 /// \code 1312 /// int* a; 1313 /// \endcode 1314 PAS_Left, 1315 /// Align pointer to the right. 1316 /// \code 1317 /// int *a; 1318 /// \endcode 1319 PAS_Right, 1320 /// Align pointer in the middle. 1321 /// \code 1322 /// int * a; 1323 /// \endcode 1324 PAS_Middle 1325 }; 1326 1327 /// \brief Pointer and reference alignment style. 1328 PointerAlignmentStyle PointerAlignment; 1329 1330 /// \brief If ``true``, clang-format will attempt to re-flow comments. 1331 /// \code 1332 /// false: 1333 /// // veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongComment with plenty of information 1334 /// /* second veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongComment with plenty of information */ 1335 /// 1336 /// true: 1337 /// // veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongComment with plenty of 1338 /// // information 1339 /// /* second veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongComment with plenty of 1340 /// * information */ 1341 /// \endcode 1342 bool ReflowComments; 1343 1344 /// \brief If ``true``, clang-format will sort ``#includes``. 1345 /// \code 1346 /// false: true: 1347 /// #include "b.h" vs. #include "a.h" 1348 /// #include "a.h" #include "b.h" 1349 /// \endcode 1350 bool SortIncludes; 1351 1352 /// \brief If ``true``, clang-format will sort using declarations. 1353 /// \code 1354 /// false: true: 1355 /// using std::cout; vs. using std::cin; 1356 /// using std::cin; using std::cout; 1357 /// \endcode 1358 bool SortUsingDeclarations; 1359 1360 /// \brief If ``true``, a space is inserted after C style casts. 1361 /// \code 1362 /// true: false: 1363 /// (int)i; vs. (int) i; 1364 /// \endcode 1365 bool SpaceAfterCStyleCast; 1366 1367 /// \brief If \c true, a space will be inserted after the 'template' keyword. 1368 /// \code 1369 /// true: false: 1370 /// template <int> void foo(); vs. template<int> void foo(); 1371 /// \endcode 1372 bool SpaceAfterTemplateKeyword; 1373 1374 /// \brief If ``false``, spaces will be removed before assignment operators. 1375 /// \code 1376 /// true: false: 1377 /// int a = 5; vs. int a=5; 1378 /// a += 42 a+=42; 1379 /// \endcode 1380 bool SpaceBeforeAssignmentOperators; 1381 1382 /// \brief Different ways to put a space before opening parentheses. 1383 enum SpaceBeforeParensOptions { 1384 /// Never put a space before opening parentheses. 1385 /// \code 1386 /// void f() { 1387 /// if(true) { 1388 /// f(); 1389 /// } 1390 /// } 1391 /// \endcode 1392 SBPO_Never, 1393 /// Put a space before opening parentheses only after control statement 1394 /// keywords (``for/if/while...``). 1395 /// \code 1396 /// void f() { 1397 /// if (true) { 1398 /// f(); 1399 /// } 1400 /// } 1401 /// \endcode 1402 SBPO_ControlStatements, 1403 /// Always put a space before opening parentheses, except when it's 1404 /// prohibited by the syntax rules (in function-like macro definitions) or 1405 /// when determined by other style rules (after unary operators, opening 1406 /// parentheses, etc.) 1407 /// \code 1408 /// void f () { 1409 /// if (true) { 1410 /// f (); 1411 /// } 1412 /// } 1413 /// \endcode 1414 SBPO_Always 1415 }; 1416 1417 /// \brief Defines in which cases to put a space before opening parentheses. 1418 SpaceBeforeParensOptions SpaceBeforeParens; 1419 1420 /// \brief If ``true``, spaces may be inserted into ``()``. 1421 /// \code 1422 /// true: false: 1423 /// void f( ) { vs. void f() { 1424 /// int x[] = {foo( ), bar( )}; int x[] = {foo(), bar()}; 1425 /// if (true) { if (true) { 1426 /// f( ); f(); 1427 /// } } 1428 /// } } 1429 /// \endcode 1430 bool SpaceInEmptyParentheses; 1431 1432 /// \brief The number of spaces before trailing line comments 1433 /// (``//`` - comments). 1434 /// 1435 /// This does not affect trailing block comments (``/*`` - comments) as 1436 /// those commonly have different usage patterns and a number of special 1437 /// cases. 1438 /// \code 1439 /// SpacesBeforeTrailingComments: 3 1440 /// void f() { 1441 /// if (true) { // foo1 1442 /// f(); // bar 1443 /// } // foo 1444 /// } 1445 /// \endcode 1446 unsigned SpacesBeforeTrailingComments; 1447 1448 /// \brief If ``true``, spaces will be inserted after ``<`` and before ``>`` 1449 /// in template argument lists. 1450 /// \code 1451 /// true: false: 1452 /// static_cast< int >(arg); vs. static_cast<int>(arg); 1453 /// std::function< void(int) > fct; std::function<void(int)> fct; 1454 /// \endcode 1455 bool SpacesInAngles; 1456 1457 /// \brief If ``true``, spaces are inserted inside container literals (e.g. 1458 /// ObjC and Javascript array and dict literals). 1459 /// \code{.js} 1460 /// true: false: 1461 /// var arr = [ 1, 2, 3 ]; vs. var arr = [1, 2, 3]; 1462 /// f({a : 1, b : 2, c : 3}); f({a: 1, b: 2, c: 3}); 1463 /// \endcode 1464 bool SpacesInContainerLiterals; 1465 1466 /// \brief If ``true``, spaces may be inserted into C style casts. 1467 /// \code 1468 /// true: false: 1469 /// x = ( int32 )y vs. x = (int32)y 1470 /// \endcode 1471 bool SpacesInCStyleCastParentheses; 1472 1473 /// \brief If ``true``, spaces will be inserted after ``(`` and before ``)``. 1474 /// \code 1475 /// true: false: 1476 /// t f( Deleted & ) & = delete; vs. t f(Deleted &) & = delete; 1477 /// \endcode 1478 bool SpacesInParentheses; 1479 1480 /// \brief If ``true``, spaces will be inserted after ``[`` and before ``]``. 1481 /// Lambdas or unspecified size array declarations will not be affected. 1482 /// \code 1483 /// true: false: 1484 /// int a[ 5 ]; vs. int a[5]; 1485 /// std::unique_ptr<int[]> foo() {} // Won't be affected 1486 /// \endcode 1487 bool SpacesInSquareBrackets; 1488 1489 /// \brief Supported language standards. 1490 enum LanguageStandard { 1491 /// Use C++03-compatible syntax. 1492 LS_Cpp03, 1493 /// Use features of C++11, C++14 and C++1z (e.g. ``A<A<int>>`` instead of 1494 /// ``A<A<int> >``). 1495 LS_Cpp11, 1496 /// Automatic detection based on the input. 1497 LS_Auto 1498 }; 1499 1500 /// \brief Format compatible with this standard, e.g. use ``A<A<int> >`` 1501 /// instead of ``A<A<int>>`` for ``LS_Cpp03``. 1502 LanguageStandard Standard; 1503 1504 /// \brief The number of columns used for tab stops. 1505 unsigned TabWidth; 1506 1507 /// \brief Different ways to use tab in formatting. 1508 enum UseTabStyle { 1509 /// Never use tab. 1510 UT_Never, 1511 /// Use tabs only for indentation. 1512 UT_ForIndentation, 1513 /// Use tabs only for line continuation and indentation. 1514 UT_ForContinuationAndIndentation, 1515 /// Use tabs whenever we need to fill whitespace that spans at least from 1516 /// one tab stop to the next one. 1517 UT_Always 1518 }; 1519 1520 /// \brief The way to use tab characters in the resulting file. 1521 UseTabStyle UseTab; 1522 1523 bool operator==(const FormatStyle &R) const { 1524 return AccessModifierOffset == R.AccessModifierOffset && 1525 AlignAfterOpenBracket == R.AlignAfterOpenBracket && 1526 AlignConsecutiveAssignments == R.AlignConsecutiveAssignments && 1527 AlignConsecutiveDeclarations == R.AlignConsecutiveDeclarations && 1528 AlignEscapedNewlines == R.AlignEscapedNewlines && 1529 AlignOperands == R.AlignOperands && 1530 AlignTrailingComments == R.AlignTrailingComments && 1531 AllowAllParametersOfDeclarationOnNextLine == 1532 R.AllowAllParametersOfDeclarationOnNextLine && 1533 AllowShortBlocksOnASingleLine == R.AllowShortBlocksOnASingleLine && 1534 AllowShortCaseLabelsOnASingleLine == 1535 R.AllowShortCaseLabelsOnASingleLine && 1536 AllowShortFunctionsOnASingleLine == 1537 R.AllowShortFunctionsOnASingleLine && 1538 AllowShortIfStatementsOnASingleLine == 1539 R.AllowShortIfStatementsOnASingleLine && 1540 AllowShortLoopsOnASingleLine == R.AllowShortLoopsOnASingleLine && 1541 AlwaysBreakAfterReturnType == R.AlwaysBreakAfterReturnType && 1542 AlwaysBreakBeforeMultilineStrings == 1543 R.AlwaysBreakBeforeMultilineStrings && 1544 AlwaysBreakTemplateDeclarations == 1545 R.AlwaysBreakTemplateDeclarations && 1546 BinPackArguments == R.BinPackArguments && 1547 BinPackParameters == R.BinPackParameters && 1548 BreakBeforeBinaryOperators == R.BreakBeforeBinaryOperators && 1549 BreakBeforeBraces == R.BreakBeforeBraces && 1550 BreakBeforeTernaryOperators == R.BreakBeforeTernaryOperators && 1551 BreakConstructorInitializers == R.BreakConstructorInitializers && 1552 CompactNamespaces == R.CompactNamespaces && 1553 BreakAfterJavaFieldAnnotations == R.BreakAfterJavaFieldAnnotations && 1554 BreakStringLiterals == R.BreakStringLiterals && 1555 ColumnLimit == R.ColumnLimit && CommentPragmas == R.CommentPragmas && 1556 BreakBeforeInheritanceComma == R.BreakBeforeInheritanceComma && 1557 ConstructorInitializerAllOnOneLineOrOnePerLine == 1558 R.ConstructorInitializerAllOnOneLineOrOnePerLine && 1559 ConstructorInitializerIndentWidth == 1560 R.ConstructorInitializerIndentWidth && 1561 ContinuationIndentWidth == R.ContinuationIndentWidth && 1562 Cpp11BracedListStyle == R.Cpp11BracedListStyle && 1563 DerivePointerAlignment == R.DerivePointerAlignment && 1564 DisableFormat == R.DisableFormat && 1565 ExperimentalAutoDetectBinPacking == 1566 R.ExperimentalAutoDetectBinPacking && 1567 FixNamespaceComments == R.FixNamespaceComments && 1568 ForEachMacros == R.ForEachMacros && 1569 IncludeCategories == R.IncludeCategories && 1570 IndentCaseLabels == R.IndentCaseLabels && 1571 IndentPPDirectives == R.IndentPPDirectives && 1572 IndentWidth == R.IndentWidth && Language == R.Language && 1573 IndentWrappedFunctionNames == R.IndentWrappedFunctionNames && 1574 JavaScriptQuotes == R.JavaScriptQuotes && 1575 JavaScriptWrapImports == R.JavaScriptWrapImports && 1576 KeepEmptyLinesAtTheStartOfBlocks == 1577 R.KeepEmptyLinesAtTheStartOfBlocks && 1578 MacroBlockBegin == R.MacroBlockBegin && 1579 MacroBlockEnd == R.MacroBlockEnd && 1580 MaxEmptyLinesToKeep == R.MaxEmptyLinesToKeep && 1581 NamespaceIndentation == R.NamespaceIndentation && 1582 ObjCBlockIndentWidth == R.ObjCBlockIndentWidth && 1583 ObjCSpaceAfterProperty == R.ObjCSpaceAfterProperty && 1584 ObjCSpaceBeforeProtocolList == R.ObjCSpaceBeforeProtocolList && 1585 PenaltyBreakAssignment == 1586 R.PenaltyBreakAssignment && 1587 PenaltyBreakBeforeFirstCallParameter == 1588 R.PenaltyBreakBeforeFirstCallParameter && 1589 PenaltyBreakComment == R.PenaltyBreakComment && 1590 PenaltyBreakFirstLessLess == R.PenaltyBreakFirstLessLess && 1591 PenaltyBreakString == R.PenaltyBreakString && 1592 PenaltyExcessCharacter == R.PenaltyExcessCharacter && 1593 PenaltyReturnTypeOnItsOwnLine == R.PenaltyReturnTypeOnItsOwnLine && 1594 PointerAlignment == R.PointerAlignment && 1595 SpaceAfterCStyleCast == R.SpaceAfterCStyleCast && 1596 SpaceAfterTemplateKeyword == R.SpaceAfterTemplateKeyword && 1597 SpaceBeforeAssignmentOperators == R.SpaceBeforeAssignmentOperators && 1598 SpaceBeforeParens == R.SpaceBeforeParens && 1599 SpaceInEmptyParentheses == R.SpaceInEmptyParentheses && 1600 SpacesBeforeTrailingComments == R.SpacesBeforeTrailingComments && 1601 SpacesInAngles == R.SpacesInAngles && 1602 SpacesInContainerLiterals == R.SpacesInContainerLiterals && 1603 SpacesInCStyleCastParentheses == R.SpacesInCStyleCastParentheses && 1604 SpacesInParentheses == R.SpacesInParentheses && 1605 SpacesInSquareBrackets == R.SpacesInSquareBrackets && 1606 Standard == R.Standard && TabWidth == R.TabWidth && 1607 UseTab == R.UseTab; 1608 } 1609}; 1610 1611/// \brief Returns a format style complying with the LLVM coding standards: 1612/// http://llvm.org/docs/CodingStandards.html. 1613FormatStyle getLLVMStyle(); 1614 1615/// \brief Returns a format style complying with one of Google's style guides: 1616/// http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml. 1617/// http://google-styleguide.googlecode.com/svn/trunk/javascriptguide.xml. 1618/// https://developers.google.com/protocol-buffers/docs/style. 1619FormatStyle getGoogleStyle(FormatStyle::LanguageKind Language); 1620 1621/// \brief Returns a format style complying with Chromium's style guide: 1622/// http://www.chromium.org/developers/coding-style. 1623FormatStyle getChromiumStyle(FormatStyle::LanguageKind Language); 1624 1625/// \brief Returns a format style complying with Mozilla's style guide: 1626/// https://developer.mozilla.org/en-US/docs/Developer_Guide/Coding_Style. 1627FormatStyle getMozillaStyle(); 1628 1629/// \brief Returns a format style complying with Webkit's style guide: 1630/// http://www.webkit.org/coding/coding-style.html 1631FormatStyle getWebKitStyle(); 1632 1633/// \brief Returns a format style complying with GNU Coding Standards: 1634/// http://www.gnu.org/prep/standards/standards.html 1635FormatStyle getGNUStyle(); 1636 1637/// \brief Returns style indicating formatting should be not applied at all. 1638FormatStyle getNoStyle(); 1639 1640/// \brief Gets a predefined style for the specified language by name. 1641/// 1642/// Currently supported names: LLVM, Google, Chromium, Mozilla. Names are 1643/// compared case-insensitively. 1644/// 1645/// Returns ``true`` if the Style has been set. 1646bool getPredefinedStyle(StringRef Name, FormatStyle::LanguageKind Language, 1647 FormatStyle *Style); 1648 1649/// \brief Parse configuration from YAML-formatted text. 1650/// 1651/// Style->Language is used to get the base style, if the ``BasedOnStyle`` 1652/// option is present. 1653/// 1654/// When ``BasedOnStyle`` is not present, options not present in the YAML 1655/// document, are retained in \p Style. 1656std::error_code parseConfiguration(StringRef Text, FormatStyle *Style); 1657 1658/// \brief Gets configuration in a YAML string. 1659std::string configurationAsText(const FormatStyle &Style); 1660 1661/// \brief Returns the replacements necessary to sort all ``#include`` blocks 1662/// that are affected by ``Ranges``. 1663tooling::Replacements sortIncludes(const FormatStyle &Style, StringRef Code, 1664 ArrayRef<tooling::Range> Ranges, 1665 StringRef FileName, 1666 unsigned *Cursor = nullptr); 1667 1668/// \brief Returns the replacements corresponding to applying and formatting 1669/// \p Replaces on success; otheriwse, return an llvm::Error carrying 1670/// llvm::StringError. 1671llvm::Expected<tooling::Replacements> 1672formatReplacements(StringRef Code, const tooling::Replacements &Replaces, 1673 const FormatStyle &Style); 1674 1675/// \brief Returns the replacements corresponding to applying \p Replaces and 1676/// cleaning up the code after that on success; otherwise, return an llvm::Error 1677/// carrying llvm::StringError. 1678/// This also supports inserting/deleting C++ #include directives: 1679/// - If a replacement has offset UINT_MAX, length 0, and a replacement text 1680/// that is an #include directive, this will insert the #include into the 1681/// correct block in the \p Code. When searching for points to insert new 1682/// header, this ignores #include's after the #include block(s) in the 1683/// beginning of a file to avoid inserting headers into code sections where 1684/// new #include's should not be added by default. These code sections 1685/// include: 1686/// - raw string literals (containing #include). 1687/// - #if blocks. 1688/// - Special #include's among declarations (e.g. functions). 1689/// - If a replacement has offset UINT_MAX, length 1, and a replacement text 1690/// that is the name of the header to be removed, the header will be removed 1691/// from \p Code if it exists. 1692llvm::Expected<tooling::Replacements> 1693cleanupAroundReplacements(StringRef Code, const tooling::Replacements &Replaces, 1694 const FormatStyle &Style); 1695 1696/// \brief Represents the status of a formatting attempt. 1697struct FormattingAttemptStatus { 1698 /// \brief A value of ``false`` means that any of the affected ranges were not 1699 /// formatted due to a non-recoverable syntax error. 1700 bool FormatComplete = true; 1701 1702 /// \brief If ``FormatComplete`` is false, ``Line`` records a one-based 1703 /// original line number at which a syntax error might have occurred. This is 1704 /// based on a best-effort analysis and could be imprecise. 1705 unsigned Line = 0; 1706}; 1707 1708/// \brief Reformats the given \p Ranges in \p Code. 1709/// 1710/// Each range is extended on either end to its next bigger logic unit, i.e. 1711/// everything that might influence its formatting or might be influenced by its 1712/// formatting. 1713/// 1714/// Returns the ``Replacements`` necessary to make all \p Ranges comply with 1715/// \p Style. 1716/// 1717/// If ``Status`` is non-null, its value will be populated with the status of 1718/// this formatting attempt. See \c FormattingAttemptStatus. 1719tooling::Replacements reformat(const FormatStyle &Style, StringRef Code, 1720 ArrayRef<tooling::Range> Ranges, 1721 StringRef FileName = "<stdin>", 1722 FormattingAttemptStatus *Status = nullptr); 1723 1724/// \brief Same as above, except if ``IncompleteFormat`` is non-null, its value 1725/// will be set to true if any of the affected ranges were not formatted due to 1726/// a non-recoverable syntax error. 1727tooling::Replacements reformat(const FormatStyle &Style, StringRef Code, 1728 ArrayRef<tooling::Range> Ranges, 1729 StringRef FileName, 1730 bool *IncompleteFormat); 1731 1732/// \brief Clean up any erroneous/redundant code in the given \p Ranges in \p 1733/// Code. 1734/// 1735/// Returns the ``Replacements`` that clean up all \p Ranges in \p Code. 1736tooling::Replacements cleanup(const FormatStyle &Style, StringRef Code, 1737 ArrayRef<tooling::Range> Ranges, 1738 StringRef FileName = "<stdin>"); 1739 1740/// \brief Fix namespace end comments in the given \p Ranges in \p Code. 1741/// 1742/// Returns the ``Replacements`` that fix the namespace comments in all 1743/// \p Ranges in \p Code. 1744tooling::Replacements fixNamespaceEndComments(const FormatStyle &Style, 1745 StringRef Code, 1746 ArrayRef<tooling::Range> Ranges, 1747 StringRef FileName = "<stdin>"); 1748 1749/// \brief Sort consecutive using declarations in the given \p Ranges in 1750/// \p Code. 1751/// 1752/// Returns the ``Replacements`` that sort the using declarations in all 1753/// \p Ranges in \p Code. 1754tooling::Replacements sortUsingDeclarations(const FormatStyle &Style, 1755 StringRef Code, 1756 ArrayRef<tooling::Range> Ranges, 1757 StringRef FileName = "<stdin>"); 1758 1759/// \brief Returns the ``LangOpts`` that the formatter expects you to set. 1760/// 1761/// \param Style determines specific settings for lexing mode. 1762LangOptions getFormattingLangOpts(const FormatStyle &Style = getLLVMStyle()); 1763 1764/// \brief Description to be used for help text for a ``llvm::cl`` option for 1765/// specifying format style. The description is closely related to the operation 1766/// of ``getStyle()``. 1767extern const char *StyleOptionHelpDescription; 1768 1769/// \brief Construct a FormatStyle based on ``StyleName``. 1770/// 1771/// ``StyleName`` can take several forms: 1772/// * "{<key>: <value>, ...}" - Set specic style parameters. 1773/// * "<style name>" - One of the style names supported by 1774/// getPredefinedStyle(). 1775/// * "file" - Load style configuration from a file called ``.clang-format`` 1776/// located in one of the parent directories of ``FileName`` or the current 1777/// directory if ``FileName`` is empty. 1778/// 1779/// \param[in] StyleName Style name to interpret according to the description 1780/// above. 1781/// \param[in] FileName Path to start search for .clang-format if ``StyleName`` 1782/// == "file". 1783/// \param[in] FallbackStyle The name of a predefined style used to fallback to 1784/// in case \p StyleName is "file" and no file can be found. 1785/// \param[in] Code The actual code to be formatted. Used to determine the 1786/// language if the filename isn't sufficient. 1787/// \param[in] FS The underlying file system, in which the file resides. By 1788/// default, the file system is the real file system. 1789/// 1790/// \returns FormatStyle as specified by ``StyleName``. If ``StyleName`` is 1791/// "file" and no file is found, returns ``FallbackStyle``. If no style could be 1792/// determined, returns an Error. 1793llvm::Expected<FormatStyle> getStyle(StringRef StyleName, StringRef FileName, 1794 StringRef FallbackStyle, 1795 StringRef Code = "", 1796 vfs::FileSystem *FS = nullptr); 1797 1798// \brief Returns a string representation of ``Language``. 1799inline StringRef getLanguageName(FormatStyle::LanguageKind Language) { 1800 switch (Language) { 1801 case FormatStyle::LK_Cpp: 1802 return "C++"; 1803 case FormatStyle::LK_ObjC: 1804 return "Objective-C"; 1805 case FormatStyle::LK_Java: 1806 return "Java"; 1807 case FormatStyle::LK_JavaScript: 1808 return "JavaScript"; 1809 case FormatStyle::LK_Proto: 1810 return "Proto"; 1811 case FormatStyle::LK_TextProto: 1812 return "TextProto"; 1813 default: 1814 return "Unknown"; 1815 } 1816} 1817 1818} // end namespace format 1819} // end namespace clang 1820 1821namespace std { 1822template <> 1823struct is_error_code_enum<clang::format::ParseError> : std::true_type {}; 1824} 1825 1826#endif // LLVM_CLANG_FORMAT_FORMAT_H 1827