1 //===--- Format.h - Format C++ code -----------------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
11 /// Various functions to configurably format source code.
13 //===----------------------------------------------------------------------===//
15 #ifndef LLVM_CLANG_FORMAT_FORMAT_H
16 #define LLVM_CLANG_FORMAT_FORMAT_H
18 #include "clang/Basic/LangOptions.h"
19 #include "clang/Tooling/Core/Replacement.h"
20 #include "llvm/ADT/ArrayRef.h"
21 #include <system_error>
27 class DiagnosticConsumer;
31 enum class ParseError { Success = 0, Error, Unsuitable };
32 class ParseErrorCategory final : public std::error_category {
34 const char *name() const LLVM_NOEXCEPT override;
35 std::string message(int EV) const override;
37 const std::error_category &getParseCategory();
38 std::error_code make_error_code(ParseError e);
40 /// \brief The \c FormatStyle is used to configure the formatting to follow
41 /// specific guidelines.
43 /// \brief The extra indent or outdent of access modifiers, e.g. \c public:.
44 int AccessModifierOffset;
46 /// \brief If \c true, horizontally aligns arguments after an open bracket.
48 /// This applies to round brackets (parentheses), angle brackets and square
49 /// brackets. This will result in formattings like
51 /// someLongFunction(argument1,
54 bool AlignAfterOpenBracket;
56 /// \brief If \c true, aligns consecutive assignments.
58 /// This will align the assignment operators of consecutive lines. This
59 /// will result in formattings like
65 bool AlignConsecutiveAssignments;
67 /// \brief If \c true, aligns escaped newlines as far left as possible.
68 /// Otherwise puts them into the right-most column.
69 bool AlignEscapedNewlinesLeft;
71 /// \brief If \c true, horizontally align operands of binary and ternary
75 /// \brief If \c true, aligns trailing comments.
76 bool AlignTrailingComments;
78 /// \brief Allow putting all parameters of a function declaration onto
79 /// the next line even if \c BinPackParameters is \c false.
80 bool AllowAllParametersOfDeclarationOnNextLine;
82 /// \brief Allows contracting simple braced statements to a single line.
84 /// E.g., this allows <tt>if (a) { return; }</tt> to be put on a single line.
85 bool AllowShortBlocksOnASingleLine;
87 /// \brief If \c true, short case labels will be contracted to a single line.
88 bool AllowShortCaseLabelsOnASingleLine;
90 /// \brief Different styles for merging short functions containing at most one
92 enum ShortFunctionStyle {
93 /// \brief Never merge functions into a single line.
95 /// \brief Only merge empty functions.
97 /// \brief Only merge functions defined inside a class. Implies "empty".
99 /// \brief Merge all functions fitting on a single line.
103 /// \brief Dependent on the value, <tt>int f() { return 0; }</tt> can be put
104 /// on a single line.
105 ShortFunctionStyle AllowShortFunctionsOnASingleLine;
107 /// \brief If \c true, <tt>if (a) return;</tt> can be put on a single
109 bool AllowShortIfStatementsOnASingleLine;
111 /// \brief If \c true, <tt>while (true) continue;</tt> can be put on a
113 bool AllowShortLoopsOnASingleLine;
115 /// \brief Different ways to break after the function definition return type.
116 enum DefinitionReturnTypeBreakingStyle {
117 /// Break after return type automatically.
118 /// \c PenaltyReturnTypeOnItsOwnLine is taken into account.
120 /// Always break after the return type.
122 /// Always break after the return types of top level functions.
126 /// \brief The function definition return type breaking style to use.
127 DefinitionReturnTypeBreakingStyle AlwaysBreakAfterDefinitionReturnType;
129 /// \brief If \c true, always break before multiline string literals.
131 /// This flag is mean to make cases where there are multiple multiline strings
132 /// in a file look more consistent. Thus, it will only take effect if wrapping
133 /// the string at that point leads to it being indented
134 /// \c ContinuationIndentWidth spaces from the start of the line.
135 bool AlwaysBreakBeforeMultilineStrings;
137 /// \brief If \c true, always break after the <tt>template<...></tt> of a
138 /// template declaration.
139 bool AlwaysBreakTemplateDeclarations;
141 /// \brief If \c false, a function call's arguments will either be all on the
142 /// same line or will have one line each.
143 bool BinPackArguments;
145 /// \brief If \c false, a function declaration's or function definition's
146 /// parameters will either all be on the same line or will have one line each.
147 bool BinPackParameters;
149 /// \brief The style of breaking before or after binary operators.
150 enum BinaryOperatorStyle {
151 /// Break after operators.
153 /// Break before operators that aren't assignments.
155 /// Break before operators.
159 /// \brief The way to wrap binary operators.
160 BinaryOperatorStyle BreakBeforeBinaryOperators;
162 /// \brief Different ways to attach braces to their surrounding context.
163 enum BraceBreakingStyle {
164 /// Always attach braces to surrounding context.
166 /// Like \c Attach, but break before braces on function, namespace and
167 /// class definitions.
169 /// Like ``Attach``, but break before braces on enum, function, and record
172 /// Like \c Attach, but break before function definitions, and 'else'.
174 /// Always break before braces.
176 /// Always break before braces and add an extra level of indentation to
177 /// braces of control statements, not to those of class, function
178 /// or other definitions.
182 /// \brief The brace breaking style to use.
183 BraceBreakingStyle BreakBeforeBraces;
185 /// \brief If \c true, ternary operators will be placed after line breaks.
186 bool BreakBeforeTernaryOperators;
188 /// \brief Always break constructor initializers before commas and align
189 /// the commas with the colon.
190 bool BreakConstructorInitializersBeforeComma;
192 /// \brief The column limit.
194 /// A column limit of \c 0 means that there is no column limit. In this case,
195 /// clang-format will respect the input's line breaking decisions within
196 /// statements unless they contradict other rules.
197 unsigned ColumnLimit;
199 /// \brief A regular expression that describes comments with special meaning,
200 /// which should not be split into lines or otherwise changed.
201 std::string CommentPragmas;
203 /// \brief If the constructor initializers don't fit on a line, put each
204 /// initializer on its own line.
205 bool ConstructorInitializerAllOnOneLineOrOnePerLine;
207 /// \brief The number of characters to use for indentation of constructor
208 /// initializer lists.
209 unsigned ConstructorInitializerIndentWidth;
211 /// \brief Indent width for line continuations.
212 unsigned ContinuationIndentWidth;
214 /// \brief If \c true, format braced lists as best suited for C++11 braced
217 /// Important differences:
218 /// - No spaces inside the braced list.
219 /// - No line break before the closing brace.
220 /// - Indentation with the continuation indent, not with the block indent.
222 /// Fundamentally, C++11 braced lists are formatted exactly like function
223 /// calls would be formatted in their place. If the braced list follows a name
224 /// (e.g. a type or variable name), clang-format formats as if the \c {} were
225 /// the parentheses of a function call with that name. If there is no name,
226 /// a zero-length name is assumed.
227 bool Cpp11BracedListStyle;
229 /// \brief If \c true, analyze the formatted file for the most common
230 /// alignment of & and *. \c PointerAlignment is then used only as fallback.
231 bool DerivePointerAlignment;
233 /// \brief Disables formatting completely.
236 /// \brief If \c true, clang-format detects whether function calls and
237 /// definitions are formatted with one parameter per line.
239 /// Each call can be bin-packed, one-per-line or inconclusive. If it is
240 /// inconclusive, e.g. completely on one line, but a decision needs to be
241 /// made, clang-format analyzes whether there are other bin-packed cases in
242 /// the input file and act accordingly.
244 /// NOTE: This is an experimental flag, that might go away or be renamed. Do
245 /// not use this in config files, etc. Use at your own risk.
246 bool ExperimentalAutoDetectBinPacking;
248 /// \brief A vector of macros that should be interpreted as foreach loops
249 /// instead of as function calls.
251 /// These are expected to be macros of the form:
253 /// FOREACH(<variable-declaration>, ...)
257 /// For example: BOOST_FOREACH.
258 std::vector<std::string> ForEachMacros;
260 /// \brief Indent case labels one level from the switch statement.
262 /// When \c false, use the same indentation level as for the switch statement.
263 /// Switch statement body is always indented one level more than case labels.
264 bool IndentCaseLabels;
266 /// \brief The number of columns to use for indentation.
267 unsigned IndentWidth;
269 /// \brief Indent if a function definition or declaration is wrapped after the
271 bool IndentWrappedFunctionNames;
273 /// \brief If true, empty lines at the start of blocks are kept.
274 bool KeepEmptyLinesAtTheStartOfBlocks;
276 /// \brief Supported languages. When stored in a configuration file, specifies
277 /// the language, that the configuration targets. When passed to the
278 /// reformat() function, enables syntax features specific to the language.
282 /// Should be used for C, C++, ObjectiveC, ObjectiveC++.
284 /// Should be used for Java.
286 /// Should be used for JavaScript.
288 /// Should be used for Protocol Buffers
289 /// (https://developers.google.com/protocol-buffers/).
293 /// \brief Language, this format style is targeted at.
294 LanguageKind Language;
296 /// \brief A regular expression matching macros that start a block.
297 std::string MacroBlockBegin;
299 /// \brief A regular expression matching macros that end a block.
300 std::string MacroBlockEnd;
302 /// \brief The maximum number of consecutive empty lines to keep.
303 unsigned MaxEmptyLinesToKeep;
305 /// \brief Different ways to indent namespace contents.
306 enum NamespaceIndentationKind {
307 /// Don't indent in namespaces.
309 /// Indent only in inner namespaces (nested in other namespaces).
311 /// Indent in all namespaces.
315 /// \brief The indentation used for namespaces.
316 NamespaceIndentationKind NamespaceIndentation;
318 /// \brief The number of characters to use for indentation of ObjC blocks.
319 unsigned ObjCBlockIndentWidth;
321 /// \brief Add a space after \c @property in Objective-C, i.e. use
322 /// <tt>\@property (readonly)</tt> instead of <tt>\@property(readonly)</tt>.
323 bool ObjCSpaceAfterProperty;
325 /// \brief Add a space in front of an Objective-C protocol list, i.e. use
326 /// <tt>Foo <Protocol></tt> instead of \c Foo<Protocol>.
327 bool ObjCSpaceBeforeProtocolList;
329 /// \brief The penalty for breaking a function call after "call(".
330 unsigned PenaltyBreakBeforeFirstCallParameter;
332 /// \brief The penalty for each line break introduced inside a comment.
333 unsigned PenaltyBreakComment;
335 /// \brief The penalty for breaking before the first \c <<.
336 unsigned PenaltyBreakFirstLessLess;
338 /// \brief The penalty for each line break introduced inside a string literal.
339 unsigned PenaltyBreakString;
341 /// \brief The penalty for each character outside of the column limit.
342 unsigned PenaltyExcessCharacter;
344 /// \brief Penalty for putting the return type of a function onto its own
346 unsigned PenaltyReturnTypeOnItsOwnLine;
348 /// \brief The & and * alignment style.
349 enum PointerAlignmentStyle {
350 /// Align pointer to the left.
352 /// Align pointer to the right.
354 /// Align pointer in the middle.
358 /// Pointer and reference alignment style.
359 PointerAlignmentStyle PointerAlignment;
361 /// \brief If \c true, a space may be inserted after C style casts.
362 bool SpaceAfterCStyleCast;
364 /// \brief If \c false, spaces will be removed before assignment operators.
365 bool SpaceBeforeAssignmentOperators;
367 /// \brief Different ways to put a space before opening parentheses.
368 enum SpaceBeforeParensOptions {
369 /// Never put a space before opening parentheses.
371 /// Put a space before opening parentheses only after control statement
372 /// keywords (<tt>for/if/while...</tt>).
373 SBPO_ControlStatements,
374 /// Always put a space before opening parentheses, except when it's
375 /// prohibited by the syntax rules (in function-like macro definitions) or
376 /// when determined by other style rules (after unary operators, opening
377 /// parentheses, etc.)
381 /// \brief Defines in which cases to put a space before opening parentheses.
382 SpaceBeforeParensOptions SpaceBeforeParens;
384 /// \brief If \c true, spaces may be inserted into '()'.
385 bool SpaceInEmptyParentheses;
387 /// \brief The number of spaces before trailing line comments
388 /// (\c // - comments).
390 /// This does not affect trailing block comments (\c /**/ - comments) as those
391 /// commonly have different usage patterns and a number of special cases.
392 unsigned SpacesBeforeTrailingComments;
394 /// \brief If \c true, spaces will be inserted after '<' and before '>' in
395 /// template argument lists
398 /// \brief If \c true, spaces are inserted inside container literals (e.g.
399 /// ObjC and Javascript array and dict literals).
400 bool SpacesInContainerLiterals;
402 /// \brief If \c true, spaces may be inserted into C style casts.
403 bool SpacesInCStyleCastParentheses;
405 /// \brief If \c true, spaces will be inserted after '(' and before ')'.
406 bool SpacesInParentheses;
408 /// \brief If \c true, spaces will be inserted after '[' and before ']'.
409 bool SpacesInSquareBrackets;
411 /// \brief Supported language standards.
412 enum LanguageStandard {
413 /// Use C++03-compatible syntax.
415 /// Use features of C++11 (e.g. \c A<A<int>> instead of
416 /// <tt>A<A<int> ></tt>).
418 /// Automatic detection based on the input.
422 /// \brief Format compatible with this standard, e.g. use
423 /// <tt>A<A<int> ></tt> instead of \c A<A<int>> for LS_Cpp03.
424 LanguageStandard Standard;
426 /// \brief The number of columns used for tab stops.
429 /// \brief Different ways to use tab in formatting.
433 /// Use tabs only for indentation.
435 /// Use tabs whenever we need to fill whitespace that spans at least from
436 /// one tab stop to the next one.
440 /// \brief The way to use tab characters in the resulting file.
443 bool operator==(const FormatStyle &R) const {
444 return AccessModifierOffset == R.AccessModifierOffset &&
445 AlignAfterOpenBracket == R.AlignAfterOpenBracket &&
446 AlignConsecutiveAssignments == R.AlignConsecutiveAssignments &&
447 AlignEscapedNewlinesLeft == R.AlignEscapedNewlinesLeft &&
448 AlignOperands == R.AlignOperands &&
449 AlignTrailingComments == R.AlignTrailingComments &&
450 AllowAllParametersOfDeclarationOnNextLine ==
451 R.AllowAllParametersOfDeclarationOnNextLine &&
452 AllowShortBlocksOnASingleLine == R.AllowShortBlocksOnASingleLine &&
453 AllowShortCaseLabelsOnASingleLine ==
454 R.AllowShortCaseLabelsOnASingleLine &&
455 AllowShortFunctionsOnASingleLine ==
456 R.AllowShortFunctionsOnASingleLine &&
457 AllowShortIfStatementsOnASingleLine ==
458 R.AllowShortIfStatementsOnASingleLine &&
459 AllowShortLoopsOnASingleLine == R.AllowShortLoopsOnASingleLine &&
460 AlwaysBreakAfterDefinitionReturnType ==
461 R.AlwaysBreakAfterDefinitionReturnType &&
462 AlwaysBreakBeforeMultilineStrings ==
463 R.AlwaysBreakBeforeMultilineStrings &&
464 AlwaysBreakTemplateDeclarations ==
465 R.AlwaysBreakTemplateDeclarations &&
466 BinPackArguments == R.BinPackArguments &&
467 BinPackParameters == R.BinPackParameters &&
468 BreakBeforeBinaryOperators == R.BreakBeforeBinaryOperators &&
469 BreakBeforeBraces == R.BreakBeforeBraces &&
470 BreakBeforeTernaryOperators == R.BreakBeforeTernaryOperators &&
471 BreakConstructorInitializersBeforeComma ==
472 R.BreakConstructorInitializersBeforeComma &&
473 ColumnLimit == R.ColumnLimit &&
474 CommentPragmas == R.CommentPragmas &&
475 ConstructorInitializerAllOnOneLineOrOnePerLine ==
476 R.ConstructorInitializerAllOnOneLineOrOnePerLine &&
477 ConstructorInitializerIndentWidth ==
478 R.ConstructorInitializerIndentWidth &&
479 ContinuationIndentWidth == R.ContinuationIndentWidth &&
480 Cpp11BracedListStyle == R.Cpp11BracedListStyle &&
481 DerivePointerAlignment == R.DerivePointerAlignment &&
482 DisableFormat == R.DisableFormat &&
483 ExperimentalAutoDetectBinPacking ==
484 R.ExperimentalAutoDetectBinPacking &&
485 ForEachMacros == R.ForEachMacros &&
486 IndentCaseLabels == R.IndentCaseLabels &&
487 IndentWidth == R.IndentWidth && Language == R.Language &&
488 IndentWrappedFunctionNames == R.IndentWrappedFunctionNames &&
489 KeepEmptyLinesAtTheStartOfBlocks ==
490 R.KeepEmptyLinesAtTheStartOfBlocks &&
491 MacroBlockBegin == R.MacroBlockBegin &&
492 MacroBlockEnd == R.MacroBlockEnd &&
493 MaxEmptyLinesToKeep == R.MaxEmptyLinesToKeep &&
494 NamespaceIndentation == R.NamespaceIndentation &&
495 ObjCBlockIndentWidth == R.ObjCBlockIndentWidth &&
496 ObjCSpaceAfterProperty == R.ObjCSpaceAfterProperty &&
497 ObjCSpaceBeforeProtocolList == R.ObjCSpaceBeforeProtocolList &&
498 PenaltyBreakBeforeFirstCallParameter ==
499 R.PenaltyBreakBeforeFirstCallParameter &&
500 PenaltyBreakComment == R.PenaltyBreakComment &&
501 PenaltyBreakFirstLessLess == R.PenaltyBreakFirstLessLess &&
502 PenaltyBreakString == R.PenaltyBreakString &&
503 PenaltyExcessCharacter == R.PenaltyExcessCharacter &&
504 PenaltyReturnTypeOnItsOwnLine == R.PenaltyReturnTypeOnItsOwnLine &&
505 PointerAlignment == R.PointerAlignment &&
506 SpaceAfterCStyleCast == R.SpaceAfterCStyleCast &&
507 SpaceBeforeAssignmentOperators == R.SpaceBeforeAssignmentOperators &&
508 SpaceBeforeParens == R.SpaceBeforeParens &&
509 SpaceInEmptyParentheses == R.SpaceInEmptyParentheses &&
510 SpacesBeforeTrailingComments == R.SpacesBeforeTrailingComments &&
511 SpacesInAngles == R.SpacesInAngles &&
512 SpacesInContainerLiterals == R.SpacesInContainerLiterals &&
513 SpacesInCStyleCastParentheses == R.SpacesInCStyleCastParentheses &&
514 SpacesInParentheses == R.SpacesInParentheses &&
515 SpacesInSquareBrackets == R.SpacesInSquareBrackets &&
516 Standard == R.Standard &&
517 TabWidth == R.TabWidth &&
522 /// \brief Returns a format style complying with the LLVM coding standards:
523 /// http://llvm.org/docs/CodingStandards.html.
524 FormatStyle getLLVMStyle();
526 /// \brief Returns a format style complying with one of Google's style guides:
527 /// http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml.
528 /// http://google-styleguide.googlecode.com/svn/trunk/javascriptguide.xml.
529 /// https://developers.google.com/protocol-buffers/docs/style.
530 FormatStyle getGoogleStyle(FormatStyle::LanguageKind Language);
532 /// \brief Returns a format style complying with Chromium's style guide:
533 /// http://www.chromium.org/developers/coding-style.
534 FormatStyle getChromiumStyle(FormatStyle::LanguageKind Language);
536 /// \brief Returns a format style complying with Mozilla's style guide:
537 /// https://developer.mozilla.org/en-US/docs/Developer_Guide/Coding_Style.
538 FormatStyle getMozillaStyle();
540 /// \brief Returns a format style complying with Webkit's style guide:
541 /// http://www.webkit.org/coding/coding-style.html
542 FormatStyle getWebKitStyle();
544 /// \brief Returns a format style complying with GNU Coding Standards:
545 /// http://www.gnu.org/prep/standards/standards.html
546 FormatStyle getGNUStyle();
548 /// \brief Returns style indicating formatting should be not applied at all.
549 FormatStyle getNoStyle();
551 /// \brief Gets a predefined style for the specified language by name.
553 /// Currently supported names: LLVM, Google, Chromium, Mozilla. Names are
554 /// compared case-insensitively.
556 /// Returns \c true if the Style has been set.
557 bool getPredefinedStyle(StringRef Name, FormatStyle::LanguageKind Language,
560 /// \brief Parse configuration from YAML-formatted text.
562 /// Style->Language is used to get the base style, if the \c BasedOnStyle
563 /// option is present.
565 /// When \c BasedOnStyle is not present, options not present in the YAML
566 /// document, are retained in \p Style.
567 std::error_code parseConfiguration(StringRef Text, FormatStyle *Style);
569 /// \brief Gets configuration in a YAML string.
570 std::string configurationAsText(const FormatStyle &Style);
572 /// \brief Reformats the given \p Ranges in the file \p ID.
574 /// Each range is extended on either end to its next bigger logic unit, i.e.
575 /// everything that might influence its formatting or might be influenced by its
578 /// Returns the \c Replacements necessary to make all \p Ranges comply with
581 /// If \c IncompleteFormat is non-null, its value will be set to true if any
582 /// of the affected ranges were not formatted due to a non-recoverable syntax
584 tooling::Replacements reformat(const FormatStyle &Style,
585 SourceManager &SourceMgr, FileID ID,
586 ArrayRef<CharSourceRange> Ranges,
587 bool *IncompleteFormat = nullptr);
589 /// \brief Reformats the given \p Ranges in \p Code.
591 /// Otherwise identical to the reformat() function using a file ID.
592 tooling::Replacements reformat(const FormatStyle &Style, StringRef Code,
593 ArrayRef<tooling::Range> Ranges,
594 StringRef FileName = "<stdin>",
595 bool *IncompleteFormat = nullptr);
597 /// \brief Returns the \c LangOpts that the formatter expects you to set.
599 /// \param Style determines specific settings for lexing mode.
600 LangOptions getFormattingLangOpts(const FormatStyle &Style = getLLVMStyle());
602 /// \brief Description to be used for help text for a llvm::cl option for
603 /// specifying format style. The description is closely related to the operation
605 extern const char *StyleOptionHelpDescription;
607 /// \brief Construct a FormatStyle based on \c StyleName.
609 /// \c StyleName can take several forms:
610 /// \li "{<key>: <value>, ...}" - Set specic style parameters.
611 /// \li "<style name>" - One of the style names supported by
612 /// getPredefinedStyle().
613 /// \li "file" - Load style configuration from a file called '.clang-format'
614 /// located in one of the parent directories of \c FileName or the current
615 /// directory if \c FileName is empty.
617 /// \param[in] StyleName Style name to interpret according to the description
619 /// \param[in] FileName Path to start search for .clang-format if \c StyleName
621 /// \param[in] FallbackStyle The name of a predefined style used to fallback to
622 /// in case the style can't be determined from \p StyleName.
624 /// \returns FormatStyle as specified by \c StyleName. If no style could be
625 /// determined, the default is LLVM Style (see getLLVMStyle()).
626 FormatStyle getStyle(StringRef StyleName, StringRef FileName,
627 StringRef FallbackStyle);
629 } // end namespace format
630 } // end namespace clang
634 struct is_error_code_enum<clang::format::ParseError> : std::true_type {};
637 #endif // LLVM_CLANG_FORMAT_FORMAT_H