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/Frontend/FrontendAction.h"
     19 #include "clang/Tooling/Refactoring.h"
     20 #include "llvm/Support/system_error.h"
     21 
     22 namespace clang {
     23 
     24 class Lexer;
     25 class SourceManager;
     26 class DiagnosticConsumer;
     27 
     28 namespace format {
     29 
     30 /// \brief The \c FormatStyle is used to configure the formatting to follow
     31 /// specific guidelines.
     32 struct FormatStyle {
     33   /// \brief The column limit.
     34   ///
     35   /// A column limit of \c 0 means that there is no column limit. In this case,
     36   /// clang-format will respect the input's line breaking decisions within
     37   /// statements.
     38   unsigned ColumnLimit;
     39 
     40   /// \brief The maximum number of consecutive empty lines to keep.
     41   unsigned MaxEmptyLinesToKeep;
     42 
     43   /// \brief The penalty for each line break introduced inside a comment.
     44   unsigned PenaltyBreakComment;
     45 
     46   /// \brief The penalty for each line break introduced inside a string literal.
     47   unsigned PenaltyBreakString;
     48 
     49   /// \brief The penalty for each character outside of the column limit.
     50   unsigned PenaltyExcessCharacter;
     51 
     52   /// \brief The penalty for breaking before the first "<<".
     53   unsigned PenaltyBreakFirstLessLess;
     54 
     55   /// \brief Set whether & and * bind to the type as opposed to the variable.
     56   bool PointerBindsToType;
     57 
     58   /// \brief If \c true, analyze the formatted file for the most common binding.
     59   bool DerivePointerBinding;
     60 
     61   /// \brief The extra indent or outdent of access modifiers (e.g.: public:).
     62   int AccessModifierOffset;
     63 
     64   enum LanguageStandard {
     65     LS_Cpp03,
     66     LS_Cpp11,
     67     LS_Auto
     68   };
     69 
     70   /// \brief Format compatible with this standard, e.g. use \c A<A<int> >
     71   /// instead of \c A<A<int>> for LS_Cpp03.
     72   LanguageStandard Standard;
     73 
     74   /// \brief Indent case labels one level from the switch statement.
     75   ///
     76   /// When false, use the same indentation level as for the switch statement.
     77   /// Switch statement body is always indented one level more than case labels.
     78   bool IndentCaseLabels;
     79 
     80   enum NamespaceIndentationKind {
     81     NI_None,  // Don't indent in namespaces.
     82     NI_Inner, // Indent only in inner namespaces (nested in other namespaces).
     83     NI_All    // Indent in all namespaces.
     84   };
     85 
     86   /// \brief The indentation used for namespaces.
     87   NamespaceIndentationKind NamespaceIndentation;
     88 
     89   /// \brief The number of spaces to before trailing line comments.
     90   unsigned SpacesBeforeTrailingComments;
     91 
     92   /// \brief If false, a function call's or function definition's parameters
     93   /// will either all be on the same line or will have one line each.
     94   bool BinPackParameters;
     95 
     96   /// \brief If true, clang-format detects whether function calls and
     97   /// definitions are formatted with one parameter per line.
     98   ///
     99   /// Each call can be bin-packed, one-per-line or inconclusive. If it is
    100   /// inconclusive, e.g. completely on one line, but a decision needs to be
    101   /// made, clang-format analyzes whether there are other bin-packed cases in
    102   /// the input file and act accordingly.
    103   ///
    104   /// NOTE: This is an experimental flag, that might go away or be renamed. Do
    105   /// not use this in config files, etc. Use at your own risk.
    106   bool ExperimentalAutoDetectBinPacking;
    107 
    108   /// \brief Allow putting all parameters of a function declaration onto
    109   /// the next line even if \c BinPackParameters is \c false.
    110   bool AllowAllParametersOfDeclarationOnNextLine;
    111 
    112   /// \brief Penalty for putting the return type of a function onto its own
    113   /// line.
    114   unsigned PenaltyReturnTypeOnItsOwnLine;
    115 
    116   /// \brief If the constructor initializers don't fit on a line, put each
    117   /// initializer on its own line.
    118   bool ConstructorInitializerAllOnOneLineOrOnePerLine;
    119 
    120   /// \brief Always break constructor initializers before commas and align
    121   /// the commas with the colon.
    122   bool BreakConstructorInitializersBeforeComma;
    123 
    124   /// \brief If true, "if (a) return;" can be put on a single line.
    125   bool AllowShortIfStatementsOnASingleLine;
    126 
    127   /// \brief If true, "while (true) continue;" can be put on a single line.
    128   bool AllowShortLoopsOnASingleLine;
    129 
    130   /// \brief Add a space in front of an Objective-C protocol list, i.e. use
    131   /// Foo <Protocol> instead of Foo<Protocol>.
    132   bool ObjCSpaceBeforeProtocolList;
    133 
    134   /// \brief If \c true, aligns trailing comments.
    135   bool AlignTrailingComments;
    136 
    137   /// \brief If \c true, aligns escaped newlines as far left as possible.
    138   /// Otherwise puts them into the right-most column.
    139   bool AlignEscapedNewlinesLeft;
    140 
    141   /// \brief The number of characters to use for indentation.
    142   unsigned IndentWidth;
    143 
    144   /// \brief If \c true, always break after the \c template<...> of a template
    145   /// declaration.
    146   bool AlwaysBreakTemplateDeclarations;
    147 
    148   /// \brief If \c true, always break before multiline string literals.
    149   bool AlwaysBreakBeforeMultilineStrings;
    150 
    151   /// \brief If true, \c IndentWidth consecutive spaces will be replaced with
    152   /// tab characters.
    153   bool UseTab;
    154 
    155   /// \brief If \c true, binary operators will be placed after line breaks.
    156   bool BreakBeforeBinaryOperators;
    157 
    158   /// \brief Different ways to attach braces to their surrounding context.
    159   enum BraceBreakingStyle {
    160     /// Always attach braces to surrounding context.
    161     BS_Attach,
    162     /// Like \c Attach, but break before braces on function, namespace and
    163     /// class definitions.
    164     BS_Linux,
    165     /// Like \c Attach, but break before function definitions.
    166     BS_Stroustrup,
    167     /// Always break before braces
    168     BS_Allman
    169   };
    170 
    171   /// \brief The brace breaking style to use.
    172   BraceBreakingStyle BreakBeforeBraces;
    173 
    174   /// \brief If \c true, format braced lists as best suited for C++11 braced
    175   /// lists.
    176   ///
    177   /// Important differences:
    178   /// - No spaces inside the braced list.
    179   /// - No line break before the closing brace.
    180   /// - Indentation with the continuation indent, not with the block indent.
    181   ///
    182   /// Fundamentally, C++11 braced lists are formatted exactly like function
    183   /// calls would be formatted in their place. If the braced list follows a name
    184   /// (e.g. a type or variable name), clang-format formats as if the "{}" were
    185   /// the parentheses of a function call with that name. If there is no name,
    186   /// a zero-length name is assumed.
    187   bool Cpp11BracedListStyle;
    188 
    189   /// \brief If \c true, indent when breaking function declarations which
    190   /// are not also definitions after the type.
    191   bool IndentFunctionDeclarationAfterType;
    192 
    193   bool operator==(const FormatStyle &R) const {
    194     return AccessModifierOffset == R.AccessModifierOffset &&
    195            AlignEscapedNewlinesLeft == R.AlignEscapedNewlinesLeft &&
    196            AlignTrailingComments == R.AlignTrailingComments &&
    197            AllowAllParametersOfDeclarationOnNextLine ==
    198                R.AllowAllParametersOfDeclarationOnNextLine &&
    199            AllowShortIfStatementsOnASingleLine ==
    200                R.AllowShortIfStatementsOnASingleLine &&
    201            AlwaysBreakTemplateDeclarations ==
    202                R.AlwaysBreakTemplateDeclarations &&
    203            AlwaysBreakBeforeMultilineStrings ==
    204                R.AlwaysBreakBeforeMultilineStrings &&
    205            BinPackParameters == R.BinPackParameters &&
    206            BreakBeforeBraces == R.BreakBeforeBraces &&
    207            ColumnLimit == R.ColumnLimit &&
    208            ConstructorInitializerAllOnOneLineOrOnePerLine ==
    209                R.ConstructorInitializerAllOnOneLineOrOnePerLine &&
    210            DerivePointerBinding == R.DerivePointerBinding &&
    211            ExperimentalAutoDetectBinPacking ==
    212                R.ExperimentalAutoDetectBinPacking &&
    213            IndentCaseLabels == R.IndentCaseLabels &&
    214            IndentWidth == R.IndentWidth &&
    215            MaxEmptyLinesToKeep == R.MaxEmptyLinesToKeep &&
    216            NamespaceIndentation == R.NamespaceIndentation &&
    217            ObjCSpaceBeforeProtocolList == R.ObjCSpaceBeforeProtocolList &&
    218            PenaltyBreakComment == R.PenaltyBreakComment &&
    219            PenaltyBreakFirstLessLess == R.PenaltyBreakFirstLessLess &&
    220            PenaltyBreakString == R.PenaltyBreakString &&
    221            PenaltyExcessCharacter == R.PenaltyExcessCharacter &&
    222            PenaltyReturnTypeOnItsOwnLine == R.PenaltyReturnTypeOnItsOwnLine &&
    223            PointerBindsToType == R.PointerBindsToType &&
    224            SpacesBeforeTrailingComments == R.SpacesBeforeTrailingComments &&
    225            Cpp11BracedListStyle == R.Cpp11BracedListStyle &&
    226            Standard == R.Standard && UseTab == R.UseTab &&
    227            IndentFunctionDeclarationAfterType ==
    228                R.IndentFunctionDeclarationAfterType;
    229   }
    230 };
    231 
    232 /// \brief Returns a format style complying with the LLVM coding standards:
    233 /// http://llvm.org/docs/CodingStandards.html.
    234 FormatStyle getLLVMStyle();
    235 
    236 /// \brief Returns a format style complying with Google's C++ style guide:
    237 /// http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml.
    238 FormatStyle getGoogleStyle();
    239 
    240 /// \brief Returns a format style complying with Chromium's style guide:
    241 /// http://www.chromium.org/developers/coding-style.
    242 FormatStyle getChromiumStyle();
    243 
    244 /// \brief Returns a format style complying with Mozilla's style guide:
    245 /// https://developer.mozilla.org/en-US/docs/Developer_Guide/Coding_Style.
    246 FormatStyle getMozillaStyle();
    247 
    248 /// \brief Returns a format style complying with Webkit's style guide:
    249 /// http://www.webkit.org/coding/coding-style.html
    250 FormatStyle getWebKitStyle();
    251 
    252 /// \brief Gets a predefined style by name.
    253 ///
    254 /// Currently supported names: LLVM, Google, Chromium, Mozilla. Names are
    255 /// compared case-insensitively.
    256 ///
    257 /// Returns true if the Style has been set.
    258 bool getPredefinedStyle(StringRef Name, FormatStyle *Style);
    259 
    260 /// \brief Parse configuration from YAML-formatted text.
    261 llvm::error_code parseConfiguration(StringRef Text, FormatStyle *Style);
    262 
    263 /// \brief Gets configuration in a YAML string.
    264 std::string configurationAsText(const FormatStyle &Style);
    265 
    266 /// \brief Reformats the given \p Ranges in the token stream coming out of
    267 /// \c Lex.
    268 ///
    269 /// Each range is extended on either end to its next bigger logic unit, i.e.
    270 /// everything that might influence its formatting or might be influenced by its
    271 /// formatting.
    272 ///
    273 /// Returns the \c Replacements necessary to make all \p Ranges comply with
    274 /// \p Style.
    275 tooling::Replacements reformat(const FormatStyle &Style, Lexer &Lex,
    276                                SourceManager &SourceMgr,
    277                                std::vector<CharSourceRange> Ranges);
    278 
    279 /// \brief Reformats the given \p Ranges in \p Code.
    280 ///
    281 /// Otherwise identical to the reformat() function consuming a \c Lexer.
    282 tooling::Replacements reformat(const FormatStyle &Style, StringRef Code,
    283                                std::vector<tooling::Range> Ranges,
    284                                StringRef FileName = "<stdin>");
    285 
    286 /// \brief Returns the \c LangOpts that the formatter expects you to set.
    287 ///
    288 /// \param Standard determines lexing mode: LC_Cpp11 and LS_Auto turn on C++11
    289 /// lexing mode, LS_Cpp03 - C++03 mode.
    290 LangOptions getFormattingLangOpts(FormatStyle::LanguageStandard Standard =
    291                                       FormatStyle::LS_Cpp11);
    292 
    293 } // end namespace format
    294 } // end namespace clang
    295 
    296 #endif // LLVM_CLANG_FORMAT_FORMAT_H
    297