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;
35 enum class ParseError { Success = 0, Error, Unsuitable };
36 class ParseErrorCategory final : public std::error_category {
38 const char *name() const noexcept override;
39 std::string message(int EV) const override;
41 const std::error_category &getParseCategory();
42 std::error_code make_error_code(ParseError e);
44 /// \brief The ``FormatStyle`` is used to configure the formatting to follow
45 /// specific guidelines.
47 /// \brief The extra indent or outdent of access modifiers, e.g. ``public:``.
48 int AccessModifierOffset;
50 /// \brief Different styles for aligning after open brackets.
51 enum BracketAlignmentStyle {
52 /// \brief Align parameters on the open bracket, e.g.:
54 /// someLongFunction(argument1,
58 /// \brief Don't align, instead use ``ContinuationIndentWidth``, e.g.:
60 /// someLongFunction(argument1,
64 /// \brief Always break after an open bracket, if the parameters don't fit
65 /// on a single line, e.g.:
68 /// argument1, argument2);
73 /// \brief If ``true``, horizontally aligns arguments after an open bracket.
75 /// This applies to round brackets (parentheses), angle brackets and square
77 BracketAlignmentStyle AlignAfterOpenBracket;
79 /// \brief If ``true``, aligns consecutive assignments.
81 /// This will align the assignment operators of consecutive lines. This
82 /// will result in formattings like
88 bool AlignConsecutiveAssignments;
90 /// \brief If ``true``, aligns consecutive declarations.
92 /// This will align the declaration names of consecutive lines. This
93 /// will result in formattings like
97 /// std::string ccc = 23;
99 bool AlignConsecutiveDeclarations;
101 /// \brief If ``true``, aligns escaped newlines as far left as possible.
102 /// Otherwise puts them into the right-most column.
103 bool AlignEscapedNewlinesLeft;
105 /// \brief If ``true``, horizontally align operands of binary and ternary
108 /// Specifically, this aligns operands of a single expression that needs to be
109 /// split over multiple lines, e.g.:
111 /// int aaa = bbbbbbbbbbbbbbb +
116 /// \brief If ``true``, aligns trailing comments.
117 bool AlignTrailingComments;
119 /// \brief Allow putting all parameters of a function declaration onto
120 /// the next line even if ``BinPackParameters`` is ``false``.
121 bool AllowAllParametersOfDeclarationOnNextLine;
123 /// \brief Allows contracting simple braced statements to a single line.
125 /// E.g., this allows ``if (a) { return; }`` to be put on a single line.
126 bool AllowShortBlocksOnASingleLine;
128 /// \brief If ``true``, short case labels will be contracted to a single line.
129 bool AllowShortCaseLabelsOnASingleLine;
131 /// \brief Different styles for merging short functions containing at most one
133 enum ShortFunctionStyle {
134 /// \brief Never merge functions into a single line.
136 /// \brief Only merge empty functions.
138 /// \brief Only merge functions defined inside a class. Implies "empty".
140 /// \brief Merge all functions fitting on a single line.
144 /// \brief Dependent on the value, ``int f() { return 0; }`` can be put on a
146 ShortFunctionStyle AllowShortFunctionsOnASingleLine;
148 /// \brief If ``true``, ``if (a) return;`` can be put on a single line.
149 bool AllowShortIfStatementsOnASingleLine;
151 /// \brief If ``true``, ``while (true) continue;`` can be put on a single
153 bool AllowShortLoopsOnASingleLine;
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.
160 /// Always break after the return type.
162 /// Always break after the return types of top-level functions.
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.
172 /// Always break after the return type.
174 /// Always break after the return types of top-level functions.
176 /// Always break after the return type of function definitions.
178 /// Always break after the return type of top-level definitions.
179 RTBS_TopLevelDefinitions,
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;
186 /// \brief The function declaration return type breaking style to use.
187 ReturnTypeBreakingStyle AlwaysBreakAfterReturnType;
189 /// \brief If ``true``, always break before multiline string literals.
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;
197 /// \brief If ``true``, always break after the ``template<...>`` of a template
199 bool AlwaysBreakTemplateDeclarations;
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;
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;
209 /// \brief The style of breaking before or after binary operators.
210 enum BinaryOperatorStyle {
211 /// Break after operators.
213 /// Break before operators that aren't assignments.
215 /// Break before operators.
219 /// \brief The way to wrap binary operators.
220 BinaryOperatorStyle BreakBeforeBinaryOperators;
222 /// \brief Different ways to attach braces to their surrounding context.
223 enum BraceBreakingStyle {
224 /// Always attach braces to surrounding context.
226 /// Like ``Attach``, but break before braces on function, namespace and
227 /// class definitions.
229 /// Like ``Attach``, but break before braces on enum, function, and record
232 /// Like ``Attach``, but break before function definitions, ``catch``, and
235 /// Always break before braces.
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.
241 /// Like ``Attach``, but break before functions.
243 /// Configure each individual brace in `BraceWrapping`.
247 /// \brief The brace breaking style to use.
248 BraceBreakingStyle BreakBeforeBraces;
250 /// \brief Precise control over the wrapping of braces.
251 struct BraceWrappingFlags {
252 /// \brief Wrap class definitions.
254 /// \brief Wrap control statements (``if``/``for``/``while``/``switch``/..).
255 bool AfterControlStatement;
256 /// \brief Wrap enum definitions.
258 /// \brief Wrap function definitions.
260 /// \brief Wrap namespace definitions.
262 /// \brief Wrap ObjC definitions (``@autoreleasepool``, interfaces, ..).
263 bool AfterObjCDeclaration;
264 /// \brief Wrap struct definitions.
266 /// \brief Wrap union definitions.
268 /// \brief Wrap before ``catch``.
270 /// \brief Wrap before ``else``.
272 /// \brief Indent the wrapped braces themselves.
276 /// \brief Control of individual brace wrapping cases.
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;
282 /// \brief If ``true``, ternary operators will be placed after line breaks.
283 bool BreakBeforeTernaryOperators;
285 /// \brief Always break constructor initializers before commas and align
286 /// the commas with the colon.
287 bool BreakConstructorInitializersBeforeComma;
289 /// \brief Break after each annotation on a field in Java files.
290 bool BreakAfterJavaFieldAnnotations;
292 /// \brief Allow breaking string literals when formatting.
293 bool BreakStringLiterals;
295 /// \brief The column limit.
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;
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;
306 /// \brief If the constructor initializers don't fit on a line, put each
307 /// initializer on its own line.
308 bool ConstructorInitializerAllOnOneLineOrOnePerLine;
310 /// \brief The number of characters to use for indentation of constructor
311 /// initializer lists.
312 unsigned ConstructorInitializerIndentWidth;
314 /// \brief Indent width for line continuations.
315 unsigned ContinuationIndentWidth;
317 /// \brief If ``true``, format braced lists as best suited for C++11 braced
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.
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;
332 /// \brief If ``true``, analyze the formatted file for the most common
333 /// alignment of ``&`` and ``*``. ``PointerAlignment`` is then used only as
335 bool DerivePointerAlignment;
337 /// \brief Disables formatting completely.
340 /// \brief If ``true``, clang-format detects whether function calls and
341 /// definitions are formatted with one parameter per line.
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.
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;
352 /// \brief A vector of macros that should be interpreted as foreach loops
353 /// instead of as function calls.
355 /// These are expected to be macros of the form:
357 /// FOREACH(<variable-declaration>, ...)
361 /// In the .clang-format configuration file, this can be configured like:
363 /// ForEachMacros: ['RANGES_FOR', 'FOREACH']
366 /// For example: BOOST_FOREACH.
367 std::vector<std::string> ForEachMacros;
369 /// \brief See documentation of ``IncludeCategories``.
370 struct IncludeCategory {
371 /// \brief The regular expression that this category matches.
373 /// \brief The priority to assign to this category.
375 bool operator==(const IncludeCategory &Other) const {
376 return Regex == Other.Regex && Priority == Other.Priority;
380 /// \brief Regular expressions denoting the different ``#include`` categories
381 /// used for ordering ``#includes``.
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
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.
396 /// To configure this in the .clang-format file, use:
398 /// IncludeCategories:
399 /// - Regex: '^"(llvm|llvm-c|clang|clang-c)/'
401 /// - Regex: '^(<|"(gtest|isl|json)/)'
406 std::vector<IncludeCategory> IncludeCategories;
408 /// \brief Specify a regular expression of suffixes that are allowed in the
409 /// file-to-main-include mapping.
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"
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;
421 /// \brief Indent case labels one level from the switch statement.
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;
427 /// \brief The number of columns to use for indentation.
428 unsigned IndentWidth;
430 /// \brief Indent if a function definition or declaration is wrapped after the
432 bool IndentWrappedFunctionNames;
434 /// \brief Quotation styles for JavaScript strings. Does not affect template
436 enum JavaScriptQuoteStyle {
437 /// Leave string quotes as they are.
439 /// Always use single quotes.
441 /// Always use double quotes.
445 /// \brief The JavaScriptQuoteStyle to use for JavaScript strings.
446 JavaScriptQuoteStyle JavaScriptQuotes;
448 /// \brief Whether to wrap JavaScript import/export statements.
449 bool JavaScriptWrapImports;
451 /// \brief If true, empty lines at the start of blocks are kept.
452 bool KeepEmptyLinesAtTheStartOfBlocks;
454 /// \brief Supported languages.
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.
462 /// Should be used for C, C++, ObjectiveC, ObjectiveC++.
464 /// Should be used for Java.
466 /// Should be used for JavaScript.
468 /// Should be used for ObjC code.
470 /// Should be used for Protocol Buffers
471 /// (https://developers.google.com/protocol-buffers/).
473 /// Should be used for TableGen code.
477 /// \brief Language, this format style is targeted at.
478 LanguageKind Language;
480 /// \brief A regular expression matching macros that start a block.
481 std::string MacroBlockBegin;
483 /// \brief A regular expression matching macros that end a block.
484 std::string MacroBlockEnd;
486 /// \brief The maximum number of consecutive empty lines to keep.
487 unsigned MaxEmptyLinesToKeep;
489 /// \brief Different ways to indent namespace contents.
490 enum NamespaceIndentationKind {
491 /// Don't indent in namespaces.
493 /// Indent only in inner namespaces (nested in other namespaces).
495 /// Indent in all namespaces.
499 /// \brief The indentation used for namespaces.
500 NamespaceIndentationKind NamespaceIndentation;
502 /// \brief The number of characters to use for indentation of ObjC blocks.
503 unsigned ObjCBlockIndentWidth;
505 /// \brief Add a space after ``@property`` in Objective-C, i.e. use
506 /// ``@property (readonly)`` instead of ``@property(readonly)``.
507 bool ObjCSpaceAfterProperty;
509 /// \brief Add a space in front of an Objective-C protocol list, i.e. use
510 /// ``Foo <Protocol>`` instead of ``Foo<Protocol>``.
511 bool ObjCSpaceBeforeProtocolList;
513 /// \brief The penalty for breaking a function call after ``call(``.
514 unsigned PenaltyBreakBeforeFirstCallParameter;
516 /// \brief The penalty for each line break introduced inside a comment.
517 unsigned PenaltyBreakComment;
519 /// \brief The penalty for breaking before the first ``<<``.
520 unsigned PenaltyBreakFirstLessLess;
522 /// \brief The penalty for each line break introduced inside a string literal.
523 unsigned PenaltyBreakString;
525 /// \brief The penalty for each character outside of the column limit.
526 unsigned PenaltyExcessCharacter;
528 /// \brief Penalty for putting the return type of a function onto its own
530 unsigned PenaltyReturnTypeOnItsOwnLine;
532 /// \brief The ``&`` and ``*`` alignment style.
533 enum PointerAlignmentStyle {
534 /// Align pointer to the left.
536 /// Align pointer to the right.
538 /// Align pointer in the middle.
542 /// \brief Pointer and reference alignment style.
543 PointerAlignmentStyle PointerAlignment;
545 /// \brief If ``true``, clang-format will attempt to re-flow comments.
548 /// \brief If ``true``, clang-format will sort ``#includes``.
551 /// \brief If ``true``, a space may be inserted after C style casts.
552 bool SpaceAfterCStyleCast;
554 /// \brief If \c true, a space will be inserted after the 'template' keyword.
555 bool SpaceAfterTemplateKeyword;
557 /// \brief If ``false``, spaces will be removed before assignment operators.
558 bool SpaceBeforeAssignmentOperators;
560 /// \brief Different ways to put a space before opening parentheses.
561 enum SpaceBeforeParensOptions {
562 /// Never put a space before opening parentheses.
564 /// Put a space before opening parentheses only after control statement
565 /// keywords (``for/if/while...``).
566 SBPO_ControlStatements,
567 /// Always put a space before opening parentheses, except when it's
568 /// prohibited by the syntax rules (in function-like macro definitions) or
569 /// when determined by other style rules (after unary operators, opening
570 /// parentheses, etc.)
574 /// \brief Defines in which cases to put a space before opening parentheses.
575 SpaceBeforeParensOptions SpaceBeforeParens;
577 /// \brief If ``true``, spaces may be inserted into ``()``.
578 bool SpaceInEmptyParentheses;
580 /// \brief The number of spaces before trailing line comments
581 /// (``//`` - comments).
583 /// This does not affect trailing block comments (``/*`` - comments) as
584 /// those commonly have different usage patterns and a number of special
586 unsigned SpacesBeforeTrailingComments;
588 /// \brief If ``true``, spaces will be inserted after ``<`` and before ``>``
589 /// in template argument lists.
592 /// \brief If ``true``, spaces are inserted inside container literals (e.g.
593 /// ObjC and Javascript array and dict literals).
594 bool SpacesInContainerLiterals;
596 /// \brief If ``true``, spaces may be inserted into C style casts.
597 bool SpacesInCStyleCastParentheses;
599 /// \brief If ``true``, spaces will be inserted after ``(`` and before ``)``.
600 bool SpacesInParentheses;
602 /// \brief If ``true``, spaces will be inserted after ``[`` and before ``]``.
603 bool SpacesInSquareBrackets;
605 /// \brief Supported language standards.
606 enum LanguageStandard {
607 /// Use C++03-compatible syntax.
609 /// Use features of C++11 (e.g. ``A<A<int>>`` instead of ``A<A<int> >``).
611 /// Automatic detection based on the input.
615 /// \brief Format compatible with this standard, e.g. use ``A<A<int> >``
616 /// instead of ``A<A<int>>`` for ``LS_Cpp03``.
617 LanguageStandard Standard;
619 /// \brief The number of columns used for tab stops.
622 /// \brief Different ways to use tab in formatting.
626 /// Use tabs only for indentation.
628 /// Use tabs only for line continuation and indentation.
629 UT_ForContinuationAndIndentation,
630 /// Use tabs whenever we need to fill whitespace that spans at least from
631 /// one tab stop to the next one.
635 /// \brief The way to use tab characters in the resulting file.
638 bool operator==(const FormatStyle &R) const {
639 return AccessModifierOffset == R.AccessModifierOffset &&
640 AlignAfterOpenBracket == R.AlignAfterOpenBracket &&
641 AlignConsecutiveAssignments == R.AlignConsecutiveAssignments &&
642 AlignConsecutiveDeclarations == R.AlignConsecutiveDeclarations &&
643 AlignEscapedNewlinesLeft == R.AlignEscapedNewlinesLeft &&
644 AlignOperands == R.AlignOperands &&
645 AlignTrailingComments == R.AlignTrailingComments &&
646 AllowAllParametersOfDeclarationOnNextLine ==
647 R.AllowAllParametersOfDeclarationOnNextLine &&
648 AllowShortBlocksOnASingleLine == R.AllowShortBlocksOnASingleLine &&
649 AllowShortCaseLabelsOnASingleLine ==
650 R.AllowShortCaseLabelsOnASingleLine &&
651 AllowShortFunctionsOnASingleLine ==
652 R.AllowShortFunctionsOnASingleLine &&
653 AllowShortIfStatementsOnASingleLine ==
654 R.AllowShortIfStatementsOnASingleLine &&
655 AllowShortLoopsOnASingleLine == R.AllowShortLoopsOnASingleLine &&
656 AlwaysBreakAfterReturnType == R.AlwaysBreakAfterReturnType &&
657 AlwaysBreakBeforeMultilineStrings ==
658 R.AlwaysBreakBeforeMultilineStrings &&
659 AlwaysBreakTemplateDeclarations ==
660 R.AlwaysBreakTemplateDeclarations &&
661 BinPackArguments == R.BinPackArguments &&
662 BinPackParameters == R.BinPackParameters &&
663 BreakBeforeBinaryOperators == R.BreakBeforeBinaryOperators &&
664 BreakBeforeBraces == R.BreakBeforeBraces &&
665 BreakBeforeTernaryOperators == R.BreakBeforeTernaryOperators &&
666 BreakConstructorInitializersBeforeComma ==
667 R.BreakConstructorInitializersBeforeComma &&
668 BreakAfterJavaFieldAnnotations == R.BreakAfterJavaFieldAnnotations &&
669 BreakStringLiterals == R.BreakStringLiterals &&
670 ColumnLimit == R.ColumnLimit && CommentPragmas == R.CommentPragmas &&
671 ConstructorInitializerAllOnOneLineOrOnePerLine ==
672 R.ConstructorInitializerAllOnOneLineOrOnePerLine &&
673 ConstructorInitializerIndentWidth ==
674 R.ConstructorInitializerIndentWidth &&
675 ContinuationIndentWidth == R.ContinuationIndentWidth &&
676 Cpp11BracedListStyle == R.Cpp11BracedListStyle &&
677 DerivePointerAlignment == R.DerivePointerAlignment &&
678 DisableFormat == R.DisableFormat &&
679 ExperimentalAutoDetectBinPacking ==
680 R.ExperimentalAutoDetectBinPacking &&
681 ForEachMacros == R.ForEachMacros &&
682 IncludeCategories == R.IncludeCategories &&
683 IndentCaseLabels == R.IndentCaseLabels &&
684 IndentWidth == R.IndentWidth && Language == R.Language &&
685 IndentWrappedFunctionNames == R.IndentWrappedFunctionNames &&
686 JavaScriptQuotes == R.JavaScriptQuotes &&
687 JavaScriptWrapImports == R.JavaScriptWrapImports &&
688 KeepEmptyLinesAtTheStartOfBlocks ==
689 R.KeepEmptyLinesAtTheStartOfBlocks &&
690 MacroBlockBegin == R.MacroBlockBegin &&
691 MacroBlockEnd == R.MacroBlockEnd &&
692 MaxEmptyLinesToKeep == R.MaxEmptyLinesToKeep &&
693 NamespaceIndentation == R.NamespaceIndentation &&
694 ObjCBlockIndentWidth == R.ObjCBlockIndentWidth &&
695 ObjCSpaceAfterProperty == R.ObjCSpaceAfterProperty &&
696 ObjCSpaceBeforeProtocolList == R.ObjCSpaceBeforeProtocolList &&
697 PenaltyBreakBeforeFirstCallParameter ==
698 R.PenaltyBreakBeforeFirstCallParameter &&
699 PenaltyBreakComment == R.PenaltyBreakComment &&
700 PenaltyBreakFirstLessLess == R.PenaltyBreakFirstLessLess &&
701 PenaltyBreakString == R.PenaltyBreakString &&
702 PenaltyExcessCharacter == R.PenaltyExcessCharacter &&
703 PenaltyReturnTypeOnItsOwnLine == R.PenaltyReturnTypeOnItsOwnLine &&
704 PointerAlignment == R.PointerAlignment &&
705 SpaceAfterCStyleCast == R.SpaceAfterCStyleCast &&
706 SpaceAfterTemplateKeyword == R.SpaceAfterTemplateKeyword &&
707 SpaceBeforeAssignmentOperators == R.SpaceBeforeAssignmentOperators &&
708 SpaceBeforeParens == R.SpaceBeforeParens &&
709 SpaceInEmptyParentheses == R.SpaceInEmptyParentheses &&
710 SpacesBeforeTrailingComments == R.SpacesBeforeTrailingComments &&
711 SpacesInAngles == R.SpacesInAngles &&
712 SpacesInContainerLiterals == R.SpacesInContainerLiterals &&
713 SpacesInCStyleCastParentheses == R.SpacesInCStyleCastParentheses &&
714 SpacesInParentheses == R.SpacesInParentheses &&
715 SpacesInSquareBrackets == R.SpacesInSquareBrackets &&
716 Standard == R.Standard && TabWidth == R.TabWidth &&
721 /// \brief Returns a format style complying with the LLVM coding standards:
722 /// http://llvm.org/docs/CodingStandards.html.
723 FormatStyle getLLVMStyle();
725 /// \brief Returns a format style complying with one of Google's style guides:
726 /// http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml.
727 /// http://google-styleguide.googlecode.com/svn/trunk/javascriptguide.xml.
728 /// https://developers.google.com/protocol-buffers/docs/style.
729 FormatStyle getGoogleStyle(FormatStyle::LanguageKind Language);
731 /// \brief Returns a format style complying with Chromium's style guide:
732 /// http://www.chromium.org/developers/coding-style.
733 FormatStyle getChromiumStyle(FormatStyle::LanguageKind Language);
735 /// \brief Returns a format style complying with Mozilla's style guide:
736 /// https://developer.mozilla.org/en-US/docs/Developer_Guide/Coding_Style.
737 FormatStyle getMozillaStyle();
739 /// \brief Returns a format style complying with Webkit's style guide:
740 /// http://www.webkit.org/coding/coding-style.html
741 FormatStyle getWebKitStyle();
743 /// \brief Returns a format style complying with GNU Coding Standards:
744 /// http://www.gnu.org/prep/standards/standards.html
745 FormatStyle getGNUStyle();
747 /// \brief Returns style indicating formatting should be not applied at all.
748 FormatStyle getNoStyle();
750 /// \brief Gets a predefined style for the specified language by name.
752 /// Currently supported names: LLVM, Google, Chromium, Mozilla. Names are
753 /// compared case-insensitively.
755 /// Returns ``true`` if the Style has been set.
756 bool getPredefinedStyle(StringRef Name, FormatStyle::LanguageKind Language,
759 /// \brief Parse configuration from YAML-formatted text.
761 /// Style->Language is used to get the base style, if the ``BasedOnStyle``
762 /// option is present.
764 /// When ``BasedOnStyle`` is not present, options not present in the YAML
765 /// document, are retained in \p Style.
766 std::error_code parseConfiguration(StringRef Text, FormatStyle *Style);
768 /// \brief Gets configuration in a YAML string.
769 std::string configurationAsText(const FormatStyle &Style);
771 /// \brief Returns the replacements necessary to sort all ``#include`` blocks
772 /// that are affected by ``Ranges``.
773 tooling::Replacements sortIncludes(const FormatStyle &Style, StringRef Code,
774 ArrayRef<tooling::Range> Ranges,
776 unsigned *Cursor = nullptr);
778 /// \brief Returns the replacements corresponding to applying and formatting
779 /// \p Replaces on success; otheriwse, return an llvm::Error carrying
780 /// llvm::StringError.
781 llvm::Expected<tooling::Replacements>
782 formatReplacements(StringRef Code, const tooling::Replacements &Replaces,
783 const FormatStyle &Style);
785 /// \brief Returns the replacements corresponding to applying \p Replaces and
786 /// cleaning up the code after that on success; otherwise, return an llvm::Error
787 /// carrying llvm::StringError.
788 /// This also supports inserting/deleting C++ #include directives:
789 /// - If a replacement has offset UINT_MAX, length 0, and a replacement text
790 /// that is an #include directive, this will insert the #include into the
791 /// correct block in the \p Code. When searching for points to insert new
792 /// header, this ignores #include's after the #include block(s) in the
793 /// beginning of a file to avoid inserting headers into code sections where
794 /// new #include's should not be added by default. These code sections
796 /// - raw string literals (containing #include).
798 /// - Special #include's among declarations (e.g. functions).
799 /// - If a replacement has offset UINT_MAX, length 1, and a replacement text
800 /// that is the name of the header to be removed, the header will be removed
801 /// from \p Code if it exists.
802 llvm::Expected<tooling::Replacements>
803 cleanupAroundReplacements(StringRef Code, const tooling::Replacements &Replaces,
804 const FormatStyle &Style);
806 /// \brief Reformats the given \p Ranges in \p Code.
808 /// Each range is extended on either end to its next bigger logic unit, i.e.
809 /// everything that might influence its formatting or might be influenced by its
812 /// Returns the ``Replacements`` necessary to make all \p Ranges comply with
815 /// If ``IncompleteFormat`` is non-null, its value will be set to true if any
816 /// of the affected ranges were not formatted due to a non-recoverable syntax
818 tooling::Replacements reformat(const FormatStyle &Style, StringRef Code,
819 ArrayRef<tooling::Range> Ranges,
820 StringRef FileName = "<stdin>",
821 bool *IncompleteFormat = nullptr);
823 /// \brief Clean up any erroneous/redundant code in the given \p Ranges in \p
826 /// Returns the ``Replacements`` that clean up all \p Ranges in \p Code.
827 tooling::Replacements cleanup(const FormatStyle &Style, StringRef Code,
828 ArrayRef<tooling::Range> Ranges,
829 StringRef FileName = "<stdin>");
831 /// \brief Returns the ``LangOpts`` that the formatter expects you to set.
833 /// \param Style determines specific settings for lexing mode.
834 LangOptions getFormattingLangOpts(const FormatStyle &Style = getLLVMStyle());
836 /// \brief Description to be used for help text for a ``llvm::cl`` option for
837 /// specifying format style. The description is closely related to the operation
838 /// of ``getStyle()``.
839 extern const char *StyleOptionHelpDescription;
841 /// \brief Construct a FormatStyle based on ``StyleName``.
843 /// ``StyleName`` can take several forms:
844 /// * "{<key>: <value>, ...}" - Set specic style parameters.
845 /// * "<style name>" - One of the style names supported by
846 /// getPredefinedStyle().
847 /// * "file" - Load style configuration from a file called ``.clang-format``
848 /// located in one of the parent directories of ``FileName`` or the current
849 /// directory if ``FileName`` is empty.
851 /// \param[in] StyleName Style name to interpret according to the description
853 /// \param[in] FileName Path to start search for .clang-format if ``StyleName``
855 /// \param[in] FallbackStyle The name of a predefined style used to fallback to
856 /// in case the style can't be determined from \p StyleName.
857 /// \param[in] Code The actual code to be formatted. Used to determine the
858 /// language if the filename isn't sufficient.
859 /// \param[in] FS The underlying file system, in which the file resides. By
860 /// default, the file system is the real file system.
862 /// \returns FormatStyle as specified by ``StyleName``. If no style could be
863 /// determined, the default is LLVM Style (see ``getLLVMStyle()``).
864 FormatStyle getStyle(StringRef StyleName, StringRef FileName,
865 StringRef FallbackStyle, StringRef Code = "",
866 vfs::FileSystem *FS = nullptr);
868 // \brief Returns a string representation of ``Language``.
869 inline StringRef getLanguageName(FormatStyle::LanguageKind Language) {
871 case FormatStyle::LK_Cpp:
873 case FormatStyle::LK_Java:
875 case FormatStyle::LK_JavaScript:
877 case FormatStyle::LK_Proto:
884 } // end namespace format
885 } // end namespace clang
889 struct is_error_code_enum<clang::format::ParseError> : std::true_type {};
892 #endif // LLVM_CLANG_FORMAT_FORMAT_H