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 Supported languages. When stored in a configuration file, specifies
44 /// the language, that the configuration targets. When passed to the
45 /// reformat() function, enables syntax features specific to the language.
49 /// Should be used for C, C++, ObjectiveC, ObjectiveC++.
51 /// Should be used for Java.
53 /// Should be used for JavaScript.
55 /// Should be used for Protocol Buffers
56 /// (https://developers.google.com/protocol-buffers/).
60 /// \brief Language, this format style is targeted at.
61 LanguageKind Language;
63 /// \brief The column limit.
65 /// A column limit of \c 0 means that there is no column limit. In this case,
66 /// clang-format will respect the input's line breaking decisions within
67 /// statements unless they contradict other rules.
70 /// \brief The maximum number of consecutive empty lines to keep.
71 unsigned MaxEmptyLinesToKeep;
73 /// \brief If true, empty lines at the start of blocks are kept.
74 bool KeepEmptyLinesAtTheStartOfBlocks;
76 /// \brief The penalty for each line break introduced inside a comment.
77 unsigned PenaltyBreakComment;
79 /// \brief The penalty for each line break introduced inside a string literal.
80 unsigned PenaltyBreakString;
82 /// \brief The penalty for each character outside of the column limit.
83 unsigned PenaltyExcessCharacter;
85 /// \brief The penalty for breaking before the first \c <<.
86 unsigned PenaltyBreakFirstLessLess;
88 /// \brief The penalty for breaking a function call after "call(".
89 unsigned PenaltyBreakBeforeFirstCallParameter;
91 /// \brief The & and * alignment style.
92 enum PointerAlignmentStyle {
93 /// Align pointer to the left.
95 /// Align pointer to the right.
97 /// Align pointer in the middle.
101 /// Pointer and reference alignment style.
102 PointerAlignmentStyle PointerAlignment;
104 /// \brief If \c true, analyze the formatted file for the most common
105 /// alignment of & and *. \c PointerAlignment is then used only as fallback.
106 bool DerivePointerAlignment;
108 /// \brief The extra indent or outdent of access modifiers, e.g. \c public:.
109 int AccessModifierOffset;
111 /// \brief Supported language standards.
112 enum LanguageStandard {
113 /// Use C++03-compatible syntax.
115 /// Use features of C++11 (e.g. \c A<A<int>> instead of
116 /// <tt>A<A<int> ></tt>).
118 /// Automatic detection based on the input.
122 /// \brief Format compatible with this standard, e.g. use
123 /// <tt>A<A<int> ></tt> instead of \c A<A<int>> for LS_Cpp03.
124 LanguageStandard Standard;
126 /// \brief Indent case labels one level from the switch statement.
128 /// When \c false, use the same indentation level as for the switch statement.
129 /// Switch statement body is always indented one level more than case labels.
130 bool IndentCaseLabels;
132 /// \brief Indent if a function definition or declaration is wrapped after the
134 bool IndentWrappedFunctionNames;
136 /// \brief Different ways to indent namespace contents.
137 enum NamespaceIndentationKind {
138 /// Don't indent in namespaces.
140 /// Indent only in inner namespaces (nested in other namespaces).
142 /// Indent in all namespaces.
146 /// \brief The indentation used for namespaces.
147 NamespaceIndentationKind NamespaceIndentation;
149 /// \brief The number of spaces before trailing line comments
150 /// (\c // - comments).
152 /// This does not affect trailing block comments (\c /**/ - comments) as those
153 /// commonly have different usage patterns and a number of special cases.
154 unsigned SpacesBeforeTrailingComments;
156 /// \brief If \c false, a function declaration's or function definition's
157 /// parameters will either all be on the same line or will have one line each.
158 bool BinPackParameters;
160 /// \brief If \c false, a function call's arguments will either be all on the
161 /// same line or will have one line each.
162 bool BinPackArguments;
164 /// \brief If \c true, clang-format detects whether function calls and
165 /// definitions are formatted with one parameter per line.
167 /// Each call can be bin-packed, one-per-line or inconclusive. If it is
168 /// inconclusive, e.g. completely on one line, but a decision needs to be
169 /// made, clang-format analyzes whether there are other bin-packed cases in
170 /// the input file and act accordingly.
172 /// NOTE: This is an experimental flag, that might go away or be renamed. Do
173 /// not use this in config files, etc. Use at your own risk.
174 bool ExperimentalAutoDetectBinPacking;
176 /// \brief Allow putting all parameters of a function declaration onto
177 /// the next line even if \c BinPackParameters is \c false.
178 bool AllowAllParametersOfDeclarationOnNextLine;
180 /// \brief Penalty for putting the return type of a function onto its own
182 unsigned PenaltyReturnTypeOnItsOwnLine;
184 /// \brief If the constructor initializers don't fit on a line, put each
185 /// initializer on its own line.
186 bool ConstructorInitializerAllOnOneLineOrOnePerLine;
188 /// \brief Always break constructor initializers before commas and align
189 /// the commas with the colon.
190 bool BreakConstructorInitializersBeforeComma;
192 /// \brief Allows contracting simple braced statements to a single line.
194 /// E.g., this allows <tt>if (a) { return; }</tt> to be put on a single line.
195 bool AllowShortBlocksOnASingleLine;
197 /// \brief If \c true, <tt>if (a) return;</tt> can be put on a single
199 bool AllowShortIfStatementsOnASingleLine;
201 /// \brief If \c true, <tt>while (true) continue;</tt> can be put on a
203 bool AllowShortLoopsOnASingleLine;
205 /// \brief If \c true, short case labels will be contracted to a single line.
206 bool AllowShortCaseLabelsOnASingleLine;
208 /// \brief Different styles for merging short functions containing at most one
210 enum ShortFunctionStyle {
211 /// \brief Never merge functions into a single line.
213 /// \brief Only merge empty functions.
215 /// \brief Only merge functions defined inside a class. Implies "empty".
217 /// \brief Merge all functions fitting on a single line.
221 /// \brief Dependent on the value, <tt>int f() { return 0; }</tt> can be put
222 /// on a single line.
223 ShortFunctionStyle AllowShortFunctionsOnASingleLine;
225 /// \brief Add a space after \c @property in Objective-C, i.e. use
226 /// <tt>\@property (readonly)</tt> instead of <tt>\@property(readonly)</tt>.
227 bool ObjCSpaceAfterProperty;
229 /// \brief Add a space in front of an Objective-C protocol list, i.e. use
230 /// <tt>Foo <Protocol></tt> instead of \c Foo<Protocol>.
231 bool ObjCSpaceBeforeProtocolList;
233 /// \brief If \c true, horizontally aligns arguments after an open bracket.
235 /// This applies to round brackets (parentheses), angle brackets and square
236 /// brackets. This will result in formattings like
238 /// someLongFunction(argument1,
241 bool AlignAfterOpenBracket;
243 /// \brief If \c true, horizontally align operands of binary and ternary
247 /// \brief If \c true, aligns trailing comments.
248 bool AlignTrailingComments;
250 /// \brief If \c true, aligns consecutive assignments.
252 /// This will align the assignment operators of consecutive lines. This
253 /// will result in formattings like
259 bool AlignConsecutiveAssignments;
261 /// \brief If \c true, aligns escaped newlines as far left as possible.
262 /// Otherwise puts them into the right-most column.
263 bool AlignEscapedNewlinesLeft;
265 /// \brief The number of columns to use for indentation.
266 unsigned IndentWidth;
268 /// \brief The number of columns used for tab stops.
271 /// \brief The number of characters to use for indentation of constructor
272 /// initializer lists.
273 unsigned ConstructorInitializerIndentWidth;
275 /// \brief The number of characters to use for indentation of ObjC blocks.
276 unsigned ObjCBlockIndentWidth;
278 /// \brief If \c true, always break after function definition return types.
280 /// More truthfully called 'break before the identifier following the type
281 /// in a function definition'. PenaltyReturnTypeOnItsOwnLine becomes
283 bool AlwaysBreakAfterDefinitionReturnType;
285 /// \brief If \c true, always break after the <tt>template<...></tt> of a
286 /// template declaration.
287 bool AlwaysBreakTemplateDeclarations;
289 /// \brief If \c true, always break before multiline string literals.
291 /// This flag is mean to make cases where there are multiple multiline strings
292 /// in a file look more consistent. Thus, it will only take effect if wrapping
293 /// the string at that point leads to it being indented
294 /// \c ContinuationIndentWidth spaces from the start of the line.
295 bool AlwaysBreakBeforeMultilineStrings;
297 /// \brief Different ways to use tab in formatting.
301 /// Use tabs only for indentation.
303 /// Use tabs whenever we need to fill whitespace that spans at least from
304 /// one tab stop to the next one.
308 /// \brief The way to use tab characters in the resulting file.
311 /// \brief The style of breaking before or after binary operators.
312 enum BinaryOperatorStyle {
313 /// Break after operators.
315 /// Break before operators that aren't assignments.
317 /// Break before operators.
321 /// \brief The way to wrap binary operators.
322 BinaryOperatorStyle BreakBeforeBinaryOperators;
324 /// \brief If \c true, ternary operators will be placed after line breaks.
325 bool BreakBeforeTernaryOperators;
327 /// \brief Different ways to attach braces to their surrounding context.
328 enum BraceBreakingStyle {
329 /// Always attach braces to surrounding context.
331 /// Like \c Attach, but break before braces on function, namespace and
332 /// class definitions.
334 /// Like \c Attach, but break before function definitions, and 'else'.
336 /// Always break before braces.
338 /// Always break before braces and add an extra level of indentation to
339 /// braces of control statements, not to those of class, function
340 /// or other definitions.
344 /// \brief The brace breaking style to use.
345 BraceBreakingStyle BreakBeforeBraces;
347 /// \brief If \c true, format braced lists as best suited for C++11 braced
350 /// Important differences:
351 /// - No spaces inside the braced list.
352 /// - No line break before the closing brace.
353 /// - Indentation with the continuation indent, not with the block indent.
355 /// Fundamentally, C++11 braced lists are formatted exactly like function
356 /// calls would be formatted in their place. If the braced list follows a name
357 /// (e.g. a type or variable name), clang-format formats as if the \c {} were
358 /// the parentheses of a function call with that name. If there is no name,
359 /// a zero-length name is assumed.
360 bool Cpp11BracedListStyle;
362 /// \brief If \c true, spaces will be inserted after '(' and before ')'.
363 bool SpacesInParentheses;
365 /// \brief If \c true, spaces will be inserted after '<' and before '>' in
366 /// template argument lists
369 /// \brief If \c true, spaces will be inserted after '[' and before ']'.
370 bool SpacesInSquareBrackets;
372 /// \brief If \c true, spaces may be inserted into '()'.
373 bool SpaceInEmptyParentheses;
375 /// \brief If \c true, spaces are inserted inside container literals (e.g.
376 /// ObjC and Javascript array and dict literals).
377 bool SpacesInContainerLiterals;
379 /// \brief If \c true, spaces may be inserted into C style casts.
380 bool SpacesInCStyleCastParentheses;
382 /// \brief If \c true, a space may be inserted after C style casts.
383 bool SpaceAfterCStyleCast;
385 /// \brief Different ways to put a space before opening parentheses.
386 enum SpaceBeforeParensOptions {
387 /// Never put a space before opening parentheses.
389 /// Put a space before opening parentheses only after control statement
390 /// keywords (<tt>for/if/while...</tt>).
391 SBPO_ControlStatements,
392 /// Always put a space before opening parentheses, except when it's
393 /// prohibited by the syntax rules (in function-like macro definitions) or
394 /// when determined by other style rules (after unary operators, opening
395 /// parentheses, etc.)
399 /// \brief Defines in which cases to put a space before opening parentheses.
400 SpaceBeforeParensOptions SpaceBeforeParens;
402 /// \brief If \c false, spaces will be removed before assignment operators.
403 bool SpaceBeforeAssignmentOperators;
405 /// \brief Indent width for line continuations.
406 unsigned ContinuationIndentWidth;
408 /// \brief A regular expression that describes comments with special meaning,
409 /// which should not be split into lines or otherwise changed.
410 std::string CommentPragmas;
412 /// \brief Disables formatting at all.
415 /// \brief A vector of macros that should be interpreted as foreach loops
416 /// instead of as function calls.
418 /// These are expected to be macros of the form:
420 /// FOREACH(<variable-declaration>, ...)
424 /// For example: BOOST_FOREACH.
425 std::vector<std::string> ForEachMacros;
427 bool operator==(const FormatStyle &R) const {
428 return AccessModifierOffset == R.AccessModifierOffset &&
429 AlignAfterOpenBracket == R.AlignAfterOpenBracket &&
430 AlignOperands == R.AlignOperands &&
431 AlignEscapedNewlinesLeft == R.AlignEscapedNewlinesLeft &&
432 AlignTrailingComments == R.AlignTrailingComments &&
433 AllowAllParametersOfDeclarationOnNextLine ==
434 R.AllowAllParametersOfDeclarationOnNextLine &&
435 AllowShortFunctionsOnASingleLine ==
436 R.AllowShortFunctionsOnASingleLine &&
437 AllowShortBlocksOnASingleLine == R.AllowShortBlocksOnASingleLine &&
438 AllowShortIfStatementsOnASingleLine ==
439 R.AllowShortIfStatementsOnASingleLine &&
440 AllowShortLoopsOnASingleLine == R.AllowShortLoopsOnASingleLine &&
441 AlwaysBreakAfterDefinitionReturnType ==
442 R.AlwaysBreakAfterDefinitionReturnType &&
443 AlwaysBreakTemplateDeclarations ==
444 R.AlwaysBreakTemplateDeclarations &&
445 AlwaysBreakBeforeMultilineStrings ==
446 R.AlwaysBreakBeforeMultilineStrings &&
447 BinPackParameters == R.BinPackParameters &&
448 BinPackArguments == R.BinPackArguments &&
449 BreakBeforeBinaryOperators == R.BreakBeforeBinaryOperators &&
450 BreakBeforeTernaryOperators == R.BreakBeforeTernaryOperators &&
451 BreakBeforeBraces == R.BreakBeforeBraces &&
452 BreakConstructorInitializersBeforeComma ==
453 R.BreakConstructorInitializersBeforeComma &&
454 ColumnLimit == R.ColumnLimit &&
455 ConstructorInitializerAllOnOneLineOrOnePerLine ==
456 R.ConstructorInitializerAllOnOneLineOrOnePerLine &&
457 ConstructorInitializerIndentWidth ==
458 R.ConstructorInitializerIndentWidth &&
459 DerivePointerAlignment == R.DerivePointerAlignment &&
460 ExperimentalAutoDetectBinPacking ==
461 R.ExperimentalAutoDetectBinPacking &&
462 IndentCaseLabels == R.IndentCaseLabels &&
463 IndentWrappedFunctionNames == R.IndentWrappedFunctionNames &&
464 IndentWidth == R.IndentWidth && Language == R.Language &&
465 MaxEmptyLinesToKeep == R.MaxEmptyLinesToKeep &&
466 KeepEmptyLinesAtTheStartOfBlocks ==
467 R.KeepEmptyLinesAtTheStartOfBlocks &&
468 NamespaceIndentation == R.NamespaceIndentation &&
469 ObjCBlockIndentWidth == R.ObjCBlockIndentWidth &&
470 ObjCSpaceAfterProperty == R.ObjCSpaceAfterProperty &&
471 ObjCSpaceBeforeProtocolList == R.ObjCSpaceBeforeProtocolList &&
472 PenaltyBreakComment == R.PenaltyBreakComment &&
473 PenaltyBreakFirstLessLess == R.PenaltyBreakFirstLessLess &&
474 PenaltyBreakString == R.PenaltyBreakString &&
475 PenaltyExcessCharacter == R.PenaltyExcessCharacter &&
476 PenaltyReturnTypeOnItsOwnLine == R.PenaltyReturnTypeOnItsOwnLine &&
477 PointerAlignment == R.PointerAlignment &&
478 SpacesBeforeTrailingComments == R.SpacesBeforeTrailingComments &&
479 Cpp11BracedListStyle == R.Cpp11BracedListStyle &&
480 Standard == R.Standard && TabWidth == R.TabWidth &&
481 UseTab == R.UseTab && SpacesInParentheses == R.SpacesInParentheses &&
482 SpacesInSquareBrackets == R.SpacesInSquareBrackets &&
483 SpacesInAngles == R.SpacesInAngles &&
484 SpaceInEmptyParentheses == R.SpaceInEmptyParentheses &&
485 SpacesInContainerLiterals == R.SpacesInContainerLiterals &&
486 SpacesInCStyleCastParentheses == R.SpacesInCStyleCastParentheses &&
487 SpaceAfterCStyleCast == R.SpaceAfterCStyleCast &&
488 SpaceBeforeParens == R.SpaceBeforeParens &&
489 SpaceBeforeAssignmentOperators == R.SpaceBeforeAssignmentOperators &&
490 ContinuationIndentWidth == R.ContinuationIndentWidth &&
491 CommentPragmas == R.CommentPragmas &&
492 ForEachMacros == R.ForEachMacros;
496 /// \brief Returns a format style complying with the LLVM coding standards:
497 /// http://llvm.org/docs/CodingStandards.html.
498 FormatStyle getLLVMStyle();
500 /// \brief Returns a format style complying with one of Google's style guides:
501 /// http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml.
502 /// http://google-styleguide.googlecode.com/svn/trunk/javascriptguide.xml.
503 /// https://developers.google.com/protocol-buffers/docs/style.
504 FormatStyle getGoogleStyle(FormatStyle::LanguageKind Language);
506 /// \brief Returns a format style complying with Chromium's style guide:
507 /// http://www.chromium.org/developers/coding-style.
508 FormatStyle getChromiumStyle(FormatStyle::LanguageKind Language);
510 /// \brief Returns a format style complying with Mozilla's style guide:
511 /// https://developer.mozilla.org/en-US/docs/Developer_Guide/Coding_Style.
512 FormatStyle getMozillaStyle();
514 /// \brief Returns a format style complying with Webkit's style guide:
515 /// http://www.webkit.org/coding/coding-style.html
516 FormatStyle getWebKitStyle();
518 /// \brief Returns a format style complying with GNU Coding Standards:
519 /// http://www.gnu.org/prep/standards/standards.html
520 FormatStyle getGNUStyle();
522 /// \brief Returns style indicating formatting should be not applied at all.
523 FormatStyle getNoStyle();
525 /// \brief Gets a predefined style for the specified language by name.
527 /// Currently supported names: LLVM, Google, Chromium, Mozilla. Names are
528 /// compared case-insensitively.
530 /// Returns \c true if the Style has been set.
531 bool getPredefinedStyle(StringRef Name, FormatStyle::LanguageKind Language,
534 /// \brief Parse configuration from YAML-formatted text.
536 /// Style->Language is used to get the base style, if the \c BasedOnStyle
537 /// option is present.
539 /// When \c BasedOnStyle is not present, options not present in the YAML
540 /// document, are retained in \p Style.
541 std::error_code parseConfiguration(StringRef Text, FormatStyle *Style);
543 /// \brief Gets configuration in a YAML string.
544 std::string configurationAsText(const FormatStyle &Style);
546 /// \brief Reformats the given \p Ranges in the file \p ID.
548 /// Each range is extended on either end to its next bigger logic unit, i.e.
549 /// everything that might influence its formatting or might be influenced by its
552 /// Returns the \c Replacements necessary to make all \p Ranges comply with
555 /// If \c IncompleteFormat is non-null, its value will be set to true if any
556 /// of the affected ranges were not formatted due to a non-recoverable syntax
558 tooling::Replacements reformat(const FormatStyle &Style,
559 SourceManager &SourceMgr, FileID ID,
560 ArrayRef<CharSourceRange> Ranges,
561 bool *IncompleteFormat = nullptr);
563 /// \brief Reformats the given \p Ranges in \p Code.
565 /// Otherwise identical to the reformat() function using a file ID.
566 tooling::Replacements reformat(const FormatStyle &Style, StringRef Code,
567 ArrayRef<tooling::Range> Ranges,
568 StringRef FileName = "<stdin>",
569 bool *IncompleteFormat = nullptr);
571 /// \brief Returns the \c LangOpts that the formatter expects you to set.
573 /// \param Style determines specific settings for lexing mode.
574 LangOptions getFormattingLangOpts(const FormatStyle &Style = getLLVMStyle());
576 /// \brief Description to be used for help text for a llvm::cl option for
577 /// specifying format style. The description is closely related to the operation
579 extern const char *StyleOptionHelpDescription;
581 /// \brief Construct a FormatStyle based on \c StyleName.
583 /// \c StyleName can take several forms:
584 /// \li "{<key>: <value>, ...}" - Set specic style parameters.
585 /// \li "<style name>" - One of the style names supported by
586 /// getPredefinedStyle().
587 /// \li "file" - Load style configuration from a file called '.clang-format'
588 /// located in one of the parent directories of \c FileName or the current
589 /// directory if \c FileName is empty.
591 /// \param[in] StyleName Style name to interpret according to the description
593 /// \param[in] FileName Path to start search for .clang-format if \c StyleName
595 /// \param[in] FallbackStyle The name of a predefined style used to fallback to
596 /// in case the style can't be determined from \p StyleName.
598 /// \returns FormatStyle as specified by \c StyleName. If no style could be
599 /// determined, the default is LLVM Style (see getLLVMStyle()).
600 FormatStyle getStyle(StringRef StyleName, StringRef FileName,
601 StringRef FallbackStyle);
603 } // end namespace format
604 } // end namespace clang
608 struct is_error_code_enum<clang::format::ParseError> : std::true_type {};
611 #endif // LLVM_CLANG_FORMAT_FORMAT_H