Home | History | Annotate | Download | only in Format
      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 
     23 namespace clang {
     24 
     25 class Lexer;
     26 class SourceManager;
     27 class DiagnosticConsumer;
     28 
     29 namespace vfs {
     30 class FileSystem;
     31 }
     32 
     33 namespace format {
     34 
     35 enum class ParseError { Success = 0, Error, Unsuitable };
     36 class ParseErrorCategory final : public std::error_category {
     37 public:
     38   const char *name() const LLVM_NOEXCEPT override;
     39   std::string message(int EV) const override;
     40 };
     41 const std::error_category &getParseCategory();
     42 std::error_code make_error_code(ParseError e);
     43 
     44 /// \brief The ``FormatStyle`` is used to configure the formatting to follow
     45 /// specific guidelines.
     46 struct 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 If ``true``, aligns escaped newlines as far left as possible.
    102   /// Otherwise puts them into the right-most column.
    103   bool AlignEscapedNewlinesLeft;
    104 
    105   /// \brief If ``true``, horizontally align operands of binary and ternary
    106   /// expressions.
    107   ///
    108   /// Specifically, this aligns operands of a single expression that needs to be
    109   /// split over multiple lines, e.g.:
    110   /// \code
    111   ///   int aaa = bbbbbbbbbbbbbbb +
    112   ///             ccccccccccccccc;
    113   /// \endcode
    114   bool AlignOperands;
    115 
    116   /// \brief If ``true``, aligns trailing comments.
    117   bool AlignTrailingComments;
    118 
    119   /// \brief Allow putting all parameters of a function declaration onto
    120   /// the next line even if ``BinPackParameters`` is ``false``.
    121   bool AllowAllParametersOfDeclarationOnNextLine;
    122 
    123   /// \brief Allows contracting simple braced statements to a single line.
    124   ///
    125   /// E.g., this allows ``if (a) { return; }`` to be put on a single line.
    126   bool AllowShortBlocksOnASingleLine;
    127 
    128   /// \brief If ``true``, short case labels will be contracted to a single line.
    129   bool AllowShortCaseLabelsOnASingleLine;
    130 
    131   /// \brief Different styles for merging short functions containing at most one
    132   /// statement.
    133   enum ShortFunctionStyle {
    134     /// \brief Never merge functions into a single line.
    135     SFS_None,
    136     /// \brief Only merge empty functions.
    137     SFS_Empty,
    138     /// \brief Only merge functions defined inside a class. Implies "empty".
    139     SFS_Inline,
    140     /// \brief Merge all functions fitting on a single line.
    141     SFS_All,
    142   };
    143 
    144   /// \brief Dependent on the value, ``int f() { return 0; }`` can be put on a
    145   /// single line.
    146   ShortFunctionStyle AllowShortFunctionsOnASingleLine;
    147 
    148   /// \brief If ``true``, ``if (a) return;`` can be put on a single line.
    149   bool AllowShortIfStatementsOnASingleLine;
    150 
    151   /// \brief If ``true``, ``while (true) continue;`` can be put on a single
    152   /// line.
    153   bool AllowShortLoopsOnASingleLine;
    154 
    155   /// \brief Different ways to break after the function definition return type.
    156   enum DefinitionReturnTypeBreakingStyle {
    157     /// Break after return type automatically.
    158     /// ``PenaltyReturnTypeOnItsOwnLine`` is taken into account.
    159     DRTBS_None,
    160     /// Always break after the return type.
    161     DRTBS_All,
    162     /// Always break after the return types of top-level functions.
    163     DRTBS_TopLevel,
    164   };
    165 
    166   /// \brief Different ways to break after the function definition or
    167   /// declaration return type.
    168   enum ReturnTypeBreakingStyle {
    169     /// Break after return type automatically.
    170     /// ``PenaltyReturnTypeOnItsOwnLine`` is taken into account.
    171     RTBS_None,
    172     /// Always break after the return type.
    173     RTBS_All,
    174     /// Always break after the return types of top-level functions.
    175     RTBS_TopLevel,
    176     /// Always break after the return type of function definitions.
    177     RTBS_AllDefinitions,
    178     /// Always break after the return type of top-level definitions.
    179     RTBS_TopLevelDefinitions,
    180   };
    181 
    182   /// \brief The function definition return type breaking style to use.  This
    183   /// option is deprecated and is retained for backwards compatibility.
    184   DefinitionReturnTypeBreakingStyle AlwaysBreakAfterDefinitionReturnType;
    185 
    186   /// \brief The function declaration return type breaking style to use.
    187   ReturnTypeBreakingStyle AlwaysBreakAfterReturnType;
    188 
    189   /// \brief If ``true``, always break before multiline string literals.
    190   ///
    191   /// This flag is mean to make cases where there are multiple multiline strings
    192   /// in a file look more consistent. Thus, it will only take effect if wrapping
    193   /// the string at that point leads to it being indented
    194   /// ``ContinuationIndentWidth`` spaces from the start of the line.
    195   bool AlwaysBreakBeforeMultilineStrings;
    196 
    197   /// \brief If ``true``, always break after the ``template<...>`` of a template
    198   /// declaration.
    199   bool AlwaysBreakTemplateDeclarations;
    200 
    201   /// \brief If ``false``, a function call's arguments will either be all on the
    202   /// same line or will have one line each.
    203   bool BinPackArguments;
    204 
    205   /// \brief If ``false``, a function declaration's or function definition's
    206   /// parameters will either all be on the same line or will have one line each.
    207   bool BinPackParameters;
    208 
    209   /// \brief The style of breaking before or after binary operators.
    210   enum BinaryOperatorStyle {
    211     /// Break after operators.
    212     BOS_None,
    213     /// Break before operators that aren't assignments.
    214     BOS_NonAssignment,
    215     /// Break before operators.
    216     BOS_All,
    217   };
    218 
    219   /// \brief The way to wrap binary operators.
    220   BinaryOperatorStyle BreakBeforeBinaryOperators;
    221 
    222   /// \brief Different ways to attach braces to their surrounding context.
    223   enum BraceBreakingStyle {
    224     /// Always attach braces to surrounding context.
    225     BS_Attach,
    226     /// Like ``Attach``, but break before braces on function, namespace and
    227     /// class definitions.
    228     BS_Linux,
    229     /// Like ``Attach``, but break before braces on enum, function, and record
    230     /// definitions.
    231     BS_Mozilla,
    232     /// Like ``Attach``, but break before function definitions, ``catch``, and
    233     /// ``else``.
    234     BS_Stroustrup,
    235     /// Always break before braces.
    236     BS_Allman,
    237     /// Always break before braces and add an extra level of indentation to
    238     /// braces of control statements, not to those of class, function
    239     /// or other definitions.
    240     BS_GNU,
    241     /// Like ``Attach``, but break before functions.
    242     BS_WebKit,
    243     /// Configure each individual brace in `BraceWrapping`.
    244     BS_Custom
    245   };
    246 
    247   /// \brief The brace breaking style to use.
    248   BraceBreakingStyle BreakBeforeBraces;
    249 
    250   /// \brief Precise control over the wrapping of braces.
    251   struct BraceWrappingFlags {
    252     /// \brief Wrap class definitions.
    253     bool AfterClass;
    254     /// \brief Wrap control statements (``if``/``for``/``while``/``switch``/..).
    255     bool AfterControlStatement;
    256     /// \brief Wrap enum definitions.
    257     bool AfterEnum;
    258     /// \brief Wrap function definitions.
    259     bool AfterFunction;
    260     /// \brief Wrap namespace definitions.
    261     bool AfterNamespace;
    262     /// \brief Wrap ObjC definitions (``@autoreleasepool``, interfaces, ..).
    263     bool AfterObjCDeclaration;
    264     /// \brief Wrap struct definitions.
    265     bool AfterStruct;
    266     /// \brief Wrap union definitions.
    267     bool AfterUnion;
    268     /// \brief Wrap before ``catch``.
    269     bool BeforeCatch;
    270     /// \brief Wrap before ``else``.
    271     bool BeforeElse;
    272     /// \brief Indent the wrapped braces themselves.
    273     bool IndentBraces;
    274   };
    275 
    276   /// \brief Control of individual brace wrapping cases.
    277   ///
    278   /// If ``BreakBeforeBraces`` is set to ``BS_Custom``, use this to specify how
    279   /// each individual brace case should be handled. Otherwise, this is ignored.
    280   BraceWrappingFlags BraceWrapping;
    281 
    282   /// \brief If ``true``, ternary operators will be placed after line breaks.
    283   bool BreakBeforeTernaryOperators;
    284 
    285   /// \brief Always break constructor initializers before commas and align
    286   /// the commas with the colon.
    287   bool BreakConstructorInitializersBeforeComma;
    288 
    289   /// \brief Break after each annotation on a field in Java files.
    290   bool BreakAfterJavaFieldAnnotations;
    291 
    292   /// \brief Allow breaking string literals when formatting.
    293   bool BreakStringLiterals;
    294 
    295   /// \brief The column limit.
    296   ///
    297   /// A column limit of ``0`` means that there is no column limit. In this case,
    298   /// clang-format will respect the input's line breaking decisions within
    299   /// statements unless they contradict other rules.
    300   unsigned ColumnLimit;
    301 
    302   /// \brief A regular expression that describes comments with special meaning,
    303   /// which should not be split into lines or otherwise changed.
    304   std::string CommentPragmas;
    305 
    306   /// \brief If the constructor initializers don't fit on a line, put each
    307   /// initializer on its own line.
    308   bool ConstructorInitializerAllOnOneLineOrOnePerLine;
    309 
    310   /// \brief The number of characters to use for indentation of constructor
    311   /// initializer lists.
    312   unsigned ConstructorInitializerIndentWidth;
    313 
    314   /// \brief Indent width for line continuations.
    315   unsigned ContinuationIndentWidth;
    316 
    317   /// \brief If ``true``, format braced lists as best suited for C++11 braced
    318   /// lists.
    319   ///
    320   /// Important differences:
    321   /// - No spaces inside the braced list.
    322   /// - No line break before the closing brace.
    323   /// - Indentation with the continuation indent, not with the block indent.
    324   ///
    325   /// Fundamentally, C++11 braced lists are formatted exactly like function
    326   /// calls would be formatted in their place. If the braced list follows a name
    327   /// (e.g. a type or variable name), clang-format formats as if the ``{}`` were
    328   /// the parentheses of a function call with that name. If there is no name,
    329   /// a zero-length name is assumed.
    330   bool Cpp11BracedListStyle;
    331 
    332   /// \brief If ``true``, analyze the formatted file for the most common
    333   /// alignment of ``&`` and ``*``. ``PointerAlignment`` is then used only as
    334   /// fallback.
    335   bool DerivePointerAlignment;
    336 
    337   /// \brief Disables formatting completely.
    338   bool DisableFormat;
    339 
    340   /// \brief If ``true``, clang-format detects whether function calls and
    341   /// definitions are formatted with one parameter per line.
    342   ///
    343   /// Each call can be bin-packed, one-per-line or inconclusive. If it is
    344   /// inconclusive, e.g. completely on one line, but a decision needs to be
    345   /// made, clang-format analyzes whether there are other bin-packed cases in
    346   /// the input file and act accordingly.
    347   ///
    348   /// NOTE: This is an experimental flag, that might go away or be renamed. Do
    349   /// not use this in config files, etc. Use at your own risk.
    350   bool ExperimentalAutoDetectBinPacking;
    351 
    352   /// \brief A vector of macros that should be interpreted as foreach loops
    353   /// instead of as function calls.
    354   ///
    355   /// These are expected to be macros of the form:
    356   /// \code
    357   ///   FOREACH(<variable-declaration>, ...)
    358   ///     <loop-body>
    359   /// \endcode
    360   ///
    361   /// In the .clang-format configuration file, this can be configured like:
    362   /// \code{.yaml}
    363   ///   ForEachMacros: ['RANGES_FOR', 'FOREACH']
    364   /// \endcode
    365   ///
    366   /// For example: BOOST_FOREACH.
    367   std::vector<std::string> ForEachMacros;
    368 
    369   /// \brief See documentation of ``IncludeCategories``.
    370   struct IncludeCategory {
    371     /// \brief The regular expression that this category matches.
    372     std::string Regex;
    373     /// \brief The priority to assign to this category.
    374     int Priority;
    375     bool operator==(const IncludeCategory &Other) const {
    376       return Regex == Other.Regex && Priority == Other.Priority;
    377     }
    378   };
    379 
    380   /// \brief Regular expressions denoting the different ``#include`` categories
    381   /// used for ordering ``#includes``.
    382   ///
    383   /// These regular expressions are matched against the filename of an include
    384   /// (including the <> or "") in order. The value belonging to the first
    385   /// matching regular expression is assigned and ``#includes`` are sorted first
    386   /// according to increasing category number and then alphabetically within
    387   /// each category.
    388   ///
    389   /// If none of the regular expressions match, INT_MAX is assigned as
    390   /// category. The main header for a source file automatically gets category 0.
    391   /// so that it is generally kept at the beginning of the ``#includes``
    392   /// (http://llvm.org/docs/CodingStandards.html#include-style). However, you
    393   /// can also assign negative priorities if you have certain headers that
    394   /// always need to be first.
    395   ///
    396   /// To configure this in the .clang-format file, use:
    397   /// \code{.yaml}
    398   ///   IncludeCategories:
    399   ///     - Regex:           '^"(llvm|llvm-c|clang|clang-c)/'
    400   ///       Priority:        2
    401   ///     - Regex:           '^(<|"(gtest|isl|json)/)'
    402   ///       Priority:        3
    403   ///     - Regex:           '.*'
    404   ///       Priority:        1
    405   /// \endcode
    406   std::vector<IncludeCategory> IncludeCategories;
    407 
    408   /// \brief Specify a regular expression of suffixes that are allowed in the
    409   /// file-to-main-include mapping.
    410   ///
    411   /// When guessing whether a #include is the "main" include (to assign
    412   /// category 0, see above), use this regex of allowed suffixes to the header
    413   /// stem. A partial match is done, so that:
    414   /// - "" means "arbitrary suffix"
    415   /// - "$" means "no suffix"
    416   ///
    417   /// For example, if configured to "(_test)?$", then a header a.h would be seen
    418   /// as the "main" include in both a.cc and a_test.cc.
    419   std::string IncludeIsMainRegex;
    420 
    421   /// \brief Indent case labels one level from the switch statement.
    422   ///
    423   /// When ``false``, use the same indentation level as for the switch statement.
    424   /// Switch statement body is always indented one level more than case labels.
    425   bool IndentCaseLabels;
    426 
    427   /// \brief The number of columns to use for indentation.
    428   unsigned IndentWidth;
    429 
    430   /// \brief Indent if a function definition or declaration is wrapped after the
    431   /// type.
    432   bool IndentWrappedFunctionNames;
    433 
    434   /// \brief Quotation styles for JavaScript strings. Does not affect template
    435   /// strings.
    436   enum JavaScriptQuoteStyle {
    437     /// Leave string quotes as they are.
    438     JSQS_Leave,
    439     /// Always use single quotes.
    440     JSQS_Single,
    441     /// Always use double quotes.
    442     JSQS_Double
    443   };
    444 
    445   /// \brief The JavaScriptQuoteStyle to use for JavaScript strings.
    446   JavaScriptQuoteStyle JavaScriptQuotes;
    447 
    448   /// \brief Whether to wrap JavaScript import/export statements.
    449   bool JavaScriptWrapImports;
    450 
    451   /// \brief If true, empty lines at the start of blocks are kept.
    452   bool KeepEmptyLinesAtTheStartOfBlocks;
    453 
    454   /// \brief Supported languages.
    455   ///
    456   /// When stored in a configuration file, specifies the language, that the
    457   /// configuration targets. When passed to the ``reformat()`` function, enables
    458   /// syntax features specific to the language.
    459   enum LanguageKind {
    460     /// Do not use.
    461     LK_None,
    462     /// Should be used for C, C++, ObjectiveC, ObjectiveC++.
    463     LK_Cpp,
    464     /// Should be used for Java.
    465     LK_Java,
    466     /// Should be used for JavaScript.
    467     LK_JavaScript,
    468     /// Should be used for Protocol Buffers
    469     /// (https://developers.google.com/protocol-buffers/).
    470     LK_Proto,
    471     /// Should be used for TableGen code.
    472     LK_TableGen
    473   };
    474 
    475   /// \brief Language, this format style is targeted at.
    476   LanguageKind Language;
    477 
    478   /// \brief A regular expression matching macros that start a block.
    479   std::string MacroBlockBegin;
    480 
    481   /// \brief A regular expression matching macros that end a block.
    482   std::string MacroBlockEnd;
    483 
    484   /// \brief The maximum number of consecutive empty lines to keep.
    485   unsigned MaxEmptyLinesToKeep;
    486 
    487   /// \brief Different ways to indent namespace contents.
    488   enum NamespaceIndentationKind {
    489     /// Don't indent in namespaces.
    490     NI_None,
    491     /// Indent only in inner namespaces (nested in other namespaces).
    492     NI_Inner,
    493     /// Indent in all namespaces.
    494     NI_All
    495   };
    496 
    497   /// \brief The indentation used for namespaces.
    498   NamespaceIndentationKind NamespaceIndentation;
    499 
    500   /// \brief The number of characters to use for indentation of ObjC blocks.
    501   unsigned ObjCBlockIndentWidth;
    502 
    503   /// \brief Add a space after ``@property`` in Objective-C, i.e. use
    504   /// ``@property (readonly)`` instead of ``@property(readonly)``.
    505   bool ObjCSpaceAfterProperty;
    506 
    507   /// \brief Add a space in front of an Objective-C protocol list, i.e. use
    508   /// ``Foo <Protocol>`` instead of ``Foo<Protocol>``.
    509   bool ObjCSpaceBeforeProtocolList;
    510 
    511   /// \brief The penalty for breaking a function call after ``call(``.
    512   unsigned PenaltyBreakBeforeFirstCallParameter;
    513 
    514   /// \brief The penalty for each line break introduced inside a comment.
    515   unsigned PenaltyBreakComment;
    516 
    517   /// \brief The penalty for breaking before the first ``<<``.
    518   unsigned PenaltyBreakFirstLessLess;
    519 
    520   /// \brief The penalty for each line break introduced inside a string literal.
    521   unsigned PenaltyBreakString;
    522 
    523   /// \brief The penalty for each character outside of the column limit.
    524   unsigned PenaltyExcessCharacter;
    525 
    526   /// \brief Penalty for putting the return type of a function onto its own
    527   /// line.
    528   unsigned PenaltyReturnTypeOnItsOwnLine;
    529 
    530   /// \brief The ``&`` and ``*`` alignment style.
    531   enum PointerAlignmentStyle {
    532     /// Align pointer to the left.
    533     PAS_Left,
    534     /// Align pointer to the right.
    535     PAS_Right,
    536     /// Align pointer in the middle.
    537     PAS_Middle
    538   };
    539 
    540   /// \brief Pointer and reference alignment style.
    541   PointerAlignmentStyle PointerAlignment;
    542 
    543   /// \brief If ``true``, clang-format will attempt to re-flow comments.
    544   bool ReflowComments;
    545 
    546   /// \brief If ``true``, clang-format will sort ``#includes``.
    547   bool SortIncludes;
    548 
    549   /// \brief If ``true``, a space may be inserted after C style casts.
    550   bool SpaceAfterCStyleCast;
    551 
    552   /// \brief If ``false``, spaces will be removed before assignment operators.
    553   bool SpaceBeforeAssignmentOperators;
    554 
    555   /// \brief Different ways to put a space before opening parentheses.
    556   enum SpaceBeforeParensOptions {
    557     /// Never put a space before opening parentheses.
    558     SBPO_Never,
    559     /// Put a space before opening parentheses only after control statement
    560     /// keywords (``for/if/while...``).
    561     SBPO_ControlStatements,
    562     /// Always put a space before opening parentheses, except when it's
    563     /// prohibited by the syntax rules (in function-like macro definitions) or
    564     /// when determined by other style rules (after unary operators, opening
    565     /// parentheses, etc.)
    566     SBPO_Always
    567   };
    568 
    569   /// \brief Defines in which cases to put a space before opening parentheses.
    570   SpaceBeforeParensOptions SpaceBeforeParens;
    571 
    572   /// \brief If ``true``, spaces may be inserted into ``()``.
    573   bool SpaceInEmptyParentheses;
    574 
    575   /// \brief The number of spaces before trailing line comments
    576   /// (``//`` - comments).
    577   ///
    578   /// This does not affect trailing block comments (``/*`` - comments) as
    579   /// those commonly have different usage patterns and a number of special
    580   /// cases.
    581   unsigned SpacesBeforeTrailingComments;
    582 
    583   /// \brief If ``true``, spaces will be inserted after ``<`` and before ``>``
    584   /// in template argument lists.
    585   bool SpacesInAngles;
    586 
    587   /// \brief If ``true``, spaces are inserted inside container literals (e.g.
    588   /// ObjC and Javascript array and dict literals).
    589   bool SpacesInContainerLiterals;
    590 
    591   /// \brief If ``true``, spaces may be inserted into C style casts.
    592   bool SpacesInCStyleCastParentheses;
    593 
    594   /// \brief If ``true``, spaces will be inserted after ``(`` and before ``)``.
    595   bool SpacesInParentheses;
    596 
    597   /// \brief If ``true``, spaces will be inserted after ``[`` and before ``]``.
    598   bool SpacesInSquareBrackets;
    599 
    600   /// \brief Supported language standards.
    601   enum LanguageStandard {
    602     /// Use C++03-compatible syntax.
    603     LS_Cpp03,
    604     /// Use features of C++11 (e.g. ``A<A<int>>`` instead of ``A<A<int> >``).
    605     LS_Cpp11,
    606     /// Automatic detection based on the input.
    607     LS_Auto
    608   };
    609 
    610   /// \brief Format compatible with this standard, e.g. use ``A<A<int> >``
    611   /// instead of ``A<A<int>>`` for ``LS_Cpp03``.
    612   LanguageStandard Standard;
    613 
    614   /// \brief The number of columns used for tab stops.
    615   unsigned TabWidth;
    616 
    617   /// \brief Different ways to use tab in formatting.
    618   enum UseTabStyle {
    619     /// Never use tab.
    620     UT_Never,
    621     /// Use tabs only for indentation.
    622     UT_ForIndentation,
    623     /// Use tabs only for line continuation and indentation.
    624     UT_ForContinuationAndIndentation,
    625     /// Use tabs whenever we need to fill whitespace that spans at least from
    626     /// one tab stop to the next one.
    627     UT_Always
    628   };
    629 
    630   /// \brief The way to use tab characters in the resulting file.
    631   UseTabStyle UseTab;
    632 
    633   bool operator==(const FormatStyle &R) const {
    634     return AccessModifierOffset == R.AccessModifierOffset &&
    635            AlignAfterOpenBracket == R.AlignAfterOpenBracket &&
    636            AlignConsecutiveAssignments == R.AlignConsecutiveAssignments &&
    637            AlignConsecutiveDeclarations == R.AlignConsecutiveDeclarations &&
    638            AlignEscapedNewlinesLeft == R.AlignEscapedNewlinesLeft &&
    639            AlignOperands == R.AlignOperands &&
    640            AlignTrailingComments == R.AlignTrailingComments &&
    641            AllowAllParametersOfDeclarationOnNextLine ==
    642                R.AllowAllParametersOfDeclarationOnNextLine &&
    643            AllowShortBlocksOnASingleLine == R.AllowShortBlocksOnASingleLine &&
    644            AllowShortCaseLabelsOnASingleLine ==
    645                R.AllowShortCaseLabelsOnASingleLine &&
    646            AllowShortFunctionsOnASingleLine ==
    647                R.AllowShortFunctionsOnASingleLine &&
    648            AllowShortIfStatementsOnASingleLine ==
    649                R.AllowShortIfStatementsOnASingleLine &&
    650            AllowShortLoopsOnASingleLine == R.AllowShortLoopsOnASingleLine &&
    651            AlwaysBreakAfterReturnType == R.AlwaysBreakAfterReturnType &&
    652            AlwaysBreakBeforeMultilineStrings ==
    653                R.AlwaysBreakBeforeMultilineStrings &&
    654            AlwaysBreakTemplateDeclarations ==
    655                R.AlwaysBreakTemplateDeclarations &&
    656            BinPackArguments == R.BinPackArguments &&
    657            BinPackParameters == R.BinPackParameters &&
    658            BreakBeforeBinaryOperators == R.BreakBeforeBinaryOperators &&
    659            BreakBeforeBraces == R.BreakBeforeBraces &&
    660            BreakBeforeTernaryOperators == R.BreakBeforeTernaryOperators &&
    661            BreakConstructorInitializersBeforeComma ==
    662                R.BreakConstructorInitializersBeforeComma &&
    663            BreakAfterJavaFieldAnnotations == R.BreakAfterJavaFieldAnnotations &&
    664            BreakStringLiterals == R.BreakStringLiterals &&
    665            ColumnLimit == R.ColumnLimit && CommentPragmas == R.CommentPragmas &&
    666            ConstructorInitializerAllOnOneLineOrOnePerLine ==
    667                R.ConstructorInitializerAllOnOneLineOrOnePerLine &&
    668            ConstructorInitializerIndentWidth ==
    669                R.ConstructorInitializerIndentWidth &&
    670            ContinuationIndentWidth == R.ContinuationIndentWidth &&
    671            Cpp11BracedListStyle == R.Cpp11BracedListStyle &&
    672            DerivePointerAlignment == R.DerivePointerAlignment &&
    673            DisableFormat == R.DisableFormat &&
    674            ExperimentalAutoDetectBinPacking ==
    675                R.ExperimentalAutoDetectBinPacking &&
    676            ForEachMacros == R.ForEachMacros &&
    677            IncludeCategories == R.IncludeCategories &&
    678            IndentCaseLabels == R.IndentCaseLabels &&
    679            IndentWidth == R.IndentWidth && Language == R.Language &&
    680            IndentWrappedFunctionNames == R.IndentWrappedFunctionNames &&
    681            JavaScriptQuotes == R.JavaScriptQuotes &&
    682            JavaScriptWrapImports == R.JavaScriptWrapImports &&
    683            KeepEmptyLinesAtTheStartOfBlocks ==
    684                R.KeepEmptyLinesAtTheStartOfBlocks &&
    685            MacroBlockBegin == R.MacroBlockBegin &&
    686            MacroBlockEnd == R.MacroBlockEnd &&
    687            MaxEmptyLinesToKeep == R.MaxEmptyLinesToKeep &&
    688            NamespaceIndentation == R.NamespaceIndentation &&
    689            ObjCBlockIndentWidth == R.ObjCBlockIndentWidth &&
    690            ObjCSpaceAfterProperty == R.ObjCSpaceAfterProperty &&
    691            ObjCSpaceBeforeProtocolList == R.ObjCSpaceBeforeProtocolList &&
    692            PenaltyBreakBeforeFirstCallParameter ==
    693                R.PenaltyBreakBeforeFirstCallParameter &&
    694            PenaltyBreakComment == R.PenaltyBreakComment &&
    695            PenaltyBreakFirstLessLess == R.PenaltyBreakFirstLessLess &&
    696            PenaltyBreakString == R.PenaltyBreakString &&
    697            PenaltyExcessCharacter == R.PenaltyExcessCharacter &&
    698            PenaltyReturnTypeOnItsOwnLine == R.PenaltyReturnTypeOnItsOwnLine &&
    699            PointerAlignment == R.PointerAlignment &&
    700            SpaceAfterCStyleCast == R.SpaceAfterCStyleCast &&
    701            SpaceBeforeAssignmentOperators == R.SpaceBeforeAssignmentOperators &&
    702            SpaceBeforeParens == R.SpaceBeforeParens &&
    703            SpaceInEmptyParentheses == R.SpaceInEmptyParentheses &&
    704            SpacesBeforeTrailingComments == R.SpacesBeforeTrailingComments &&
    705            SpacesInAngles == R.SpacesInAngles &&
    706            SpacesInContainerLiterals == R.SpacesInContainerLiterals &&
    707            SpacesInCStyleCastParentheses == R.SpacesInCStyleCastParentheses &&
    708            SpacesInParentheses == R.SpacesInParentheses &&
    709            SpacesInSquareBrackets == R.SpacesInSquareBrackets &&
    710            Standard == R.Standard && TabWidth == R.TabWidth &&
    711            UseTab == R.UseTab;
    712   }
    713 };
    714 
    715 /// \brief Returns a format style complying with the LLVM coding standards:
    716 /// http://llvm.org/docs/CodingStandards.html.
    717 FormatStyle getLLVMStyle();
    718 
    719 /// \brief Returns a format style complying with one of Google's style guides:
    720 /// http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml.
    721 /// http://google-styleguide.googlecode.com/svn/trunk/javascriptguide.xml.
    722 /// https://developers.google.com/protocol-buffers/docs/style.
    723 FormatStyle getGoogleStyle(FormatStyle::LanguageKind Language);
    724 
    725 /// \brief Returns a format style complying with Chromium's style guide:
    726 /// http://www.chromium.org/developers/coding-style.
    727 FormatStyle getChromiumStyle(FormatStyle::LanguageKind Language);
    728 
    729 /// \brief Returns a format style complying with Mozilla's style guide:
    730 /// https://developer.mozilla.org/en-US/docs/Developer_Guide/Coding_Style.
    731 FormatStyle getMozillaStyle();
    732 
    733 /// \brief Returns a format style complying with Webkit's style guide:
    734 /// http://www.webkit.org/coding/coding-style.html
    735 FormatStyle getWebKitStyle();
    736 
    737 /// \brief Returns a format style complying with GNU Coding Standards:
    738 /// http://www.gnu.org/prep/standards/standards.html
    739 FormatStyle getGNUStyle();
    740 
    741 /// \brief Returns style indicating formatting should be not applied at all.
    742 FormatStyle getNoStyle();
    743 
    744 /// \brief Gets a predefined style for the specified language by name.
    745 ///
    746 /// Currently supported names: LLVM, Google, Chromium, Mozilla. Names are
    747 /// compared case-insensitively.
    748 ///
    749 /// Returns ``true`` if the Style has been set.
    750 bool getPredefinedStyle(StringRef Name, FormatStyle::LanguageKind Language,
    751                         FormatStyle *Style);
    752 
    753 /// \brief Parse configuration from YAML-formatted text.
    754 ///
    755 /// Style->Language is used to get the base style, if the ``BasedOnStyle``
    756 /// option is present.
    757 ///
    758 /// When ``BasedOnStyle`` is not present, options not present in the YAML
    759 /// document, are retained in \p Style.
    760 std::error_code parseConfiguration(StringRef Text, FormatStyle *Style);
    761 
    762 /// \brief Gets configuration in a YAML string.
    763 std::string configurationAsText(const FormatStyle &Style);
    764 
    765 /// \brief Returns the replacements necessary to sort all ``#include`` blocks
    766 /// that are affected by ``Ranges``.
    767 tooling::Replacements sortIncludes(const FormatStyle &Style, StringRef Code,
    768                                    ArrayRef<tooling::Range> Ranges,
    769                                    StringRef FileName,
    770                                    unsigned *Cursor = nullptr);
    771 
    772 /// \brief Returns the replacements corresponding to applying and formatting
    773 /// \p Replaces on success; otheriwse, return an llvm::Error carrying
    774 /// llvm::StringError.
    775 llvm::Expected<tooling::Replacements>
    776 formatReplacements(StringRef Code, const tooling::Replacements &Replaces,
    777                    const FormatStyle &Style);
    778 
    779 /// \brief Returns the replacements corresponding to applying \p Replaces and
    780 /// cleaning up the code after that on success; otherwise, return an llvm::Error
    781 /// carrying llvm::StringError.
    782 /// This also inserts a C++ #include directive into the correct block if the
    783 /// replacement corresponding to the header insertion has offset UINT_MAX.
    784 llvm::Expected<tooling::Replacements>
    785 cleanupAroundReplacements(StringRef Code, const tooling::Replacements &Replaces,
    786                           const FormatStyle &Style);
    787 
    788 /// \brief Reformats the given \p Ranges in the file \p ID.
    789 ///
    790 /// Each range is extended on either end to its next bigger logic unit, i.e.
    791 /// everything that might influence its formatting or might be influenced by its
    792 /// formatting.
    793 ///
    794 /// Returns the ``Replacements`` necessary to make all \p Ranges comply with
    795 /// \p Style.
    796 ///
    797 /// If ``IncompleteFormat`` is non-null, its value will be set to true if any
    798 /// of the affected ranges were not formatted due to a non-recoverable syntax
    799 /// error.
    800 tooling::Replacements reformat(const FormatStyle &Style,
    801                                SourceManager &SourceMgr, FileID ID,
    802                                ArrayRef<CharSourceRange> Ranges,
    803                                bool *IncompleteFormat = nullptr);
    804 
    805 /// \brief Reformats the given \p Ranges in \p Code.
    806 ///
    807 /// Otherwise identical to the reformat() function using a file ID.
    808 tooling::Replacements reformat(const FormatStyle &Style, StringRef Code,
    809                                ArrayRef<tooling::Range> Ranges,
    810                                StringRef FileName = "<stdin>",
    811                                bool *IncompleteFormat = nullptr);
    812 
    813 /// \brief Clean up any erroneous/redundant code in the given \p Ranges in the
    814 /// file \p ID.
    815 ///
    816 /// Returns the ``Replacements`` that clean up all \p Ranges in the file \p ID.
    817 tooling::Replacements cleanup(const FormatStyle &Style,
    818                               SourceManager &SourceMgr, FileID ID,
    819                               ArrayRef<CharSourceRange> Ranges);
    820 
    821 /// \brief Clean up any erroneous/redundant code in the given \p Ranges in \p
    822 /// Code.
    823 ///
    824 /// Otherwise identical to the cleanup() function using a file ID.
    825 tooling::Replacements cleanup(const FormatStyle &Style, StringRef Code,
    826                               ArrayRef<tooling::Range> Ranges,
    827                               StringRef FileName = "<stdin>");
    828 
    829 /// \brief Returns the ``LangOpts`` that the formatter expects you to set.
    830 ///
    831 /// \param Style determines specific settings for lexing mode.
    832 LangOptions getFormattingLangOpts(const FormatStyle &Style = getLLVMStyle());
    833 
    834 /// \brief Description to be used for help text for a ``llvm::cl`` option for
    835 /// specifying format style. The description is closely related to the operation
    836 /// of ``getStyle()``.
    837 extern const char *StyleOptionHelpDescription;
    838 
    839 /// \brief Construct a FormatStyle based on ``StyleName``.
    840 ///
    841 /// ``StyleName`` can take several forms:
    842 /// * "{<key>: <value>, ...}" - Set specic style parameters.
    843 /// * "<style name>" - One of the style names supported by
    844 /// getPredefinedStyle().
    845 /// * "file" - Load style configuration from a file called ``.clang-format``
    846 /// located in one of the parent directories of ``FileName`` or the current
    847 /// directory if ``FileName`` is empty.
    848 ///
    849 /// \param[in] StyleName Style name to interpret according to the description
    850 /// above.
    851 /// \param[in] FileName Path to start search for .clang-format if ``StyleName``
    852 /// == "file".
    853 /// \param[in] FallbackStyle The name of a predefined style used to fallback to
    854 /// in case the style can't be determined from \p StyleName.
    855 /// \param[in] FS The underlying file system, in which the file resides. By
    856 /// default, the file system is the real file system.
    857 ///
    858 /// \returns FormatStyle as specified by ``StyleName``. If no style could be
    859 /// determined, the default is LLVM Style (see ``getLLVMStyle()``).
    860 FormatStyle getStyle(StringRef StyleName, StringRef FileName,
    861                      StringRef FallbackStyle, vfs::FileSystem *FS = nullptr);
    862 
    863 // \brief Returns a string representation of ``Language``.
    864 inline StringRef getLanguageName(FormatStyle::LanguageKind Language) {
    865   switch (Language) {
    866   case FormatStyle::LK_Cpp:
    867     return "C++";
    868   case FormatStyle::LK_Java:
    869     return "Java";
    870   case FormatStyle::LK_JavaScript:
    871     return "JavaScript";
    872   case FormatStyle::LK_Proto:
    873     return "Proto";
    874   default:
    875     return "Unknown";
    876   }
    877 }
    878 
    879 } // end namespace format
    880 } // end namespace clang
    881 
    882 namespace std {
    883 template <>
    884 struct is_error_code_enum<clang::format::ParseError> : std::true_type {};
    885 }
    886 
    887 #endif // LLVM_CLANG_FORMAT_FORMAT_H
    888