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 Different styles for aligning escaped newlines.
102 enum EscapedNewlineAlignmentStyle {
103 /// \brief Don't align escaped newlines.
111 /// \brief Align escaped newlines as far left as possible.
122 /// \brief Align escaped newlines in the right-most column.
132 /// \brief Options for aligning backslashes in escaped newlines.
133 EscapedNewlineAlignmentStyle AlignEscapedNewlines;
135 /// \brief If ``true``, horizontally align operands of binary and ternary
138 /// Specifically, this aligns operands of a single expression that needs to be
139 /// split over multiple lines, e.g.:
141 /// int aaa = bbbbbbbbbbbbbbb +
146 /// \brief If ``true``, aligns trailing comments.
149 /// int a; // My comment a vs. int a; // My comment a
150 /// int b = 2; // comment b int b = 2; // comment about b
152 bool AlignTrailingComments;
154 /// \brief Allow putting all parameters of a function declaration onto
155 /// the next line even if ``BinPackParameters`` is ``false``.
158 /// myFunction(foo, vs. myFunction(foo, bar, plop);
162 bool AllowAllParametersOfDeclarationOnNextLine;
164 /// \brief Allows contracting simple braced statements to a single line.
166 /// E.g., this allows ``if (a) { return; }`` to be put on a single line.
167 bool AllowShortBlocksOnASingleLine;
169 /// \brief If ``true``, short case labels will be contracted to a single line.
172 /// switch (a) { vs. switch (a) {
173 /// case 1: x = 1; break; case 1:
174 /// case 2: return; x = 1;
180 bool AllowShortCaseLabelsOnASingleLine;
182 /// \brief Different styles for merging short functions containing at most one
184 enum ShortFunctionStyle {
185 /// \brief Never merge functions into a single line.
187 /// \brief Only merge empty functions.
189 /// void f() { bar(); }
195 /// \brief Only merge functions defined inside a class. Implies "empty".
198 /// void f() { foo(); }
202 /// \brief Merge all functions fitting on a single line.
205 /// void f() { foo(); }
207 /// void f() { bar(); }
212 /// \brief Dependent on the value, ``int f() { return 0; }`` can be put on a
214 ShortFunctionStyle AllowShortFunctionsOnASingleLine;
216 /// \brief If ``true``, ``if (a) return;`` can be put on a single line.
217 bool AllowShortIfStatementsOnASingleLine;
219 /// \brief If ``true``, ``while (true) continue;`` can be put on a single
221 bool AllowShortLoopsOnASingleLine;
223 /// \brief Different ways to break after the function definition return type.
224 /// This option is **deprecated** and is retained for backwards compatibility.
225 enum DefinitionReturnTypeBreakingStyle {
226 /// Break after return type automatically.
227 /// ``PenaltyReturnTypeOnItsOwnLine`` is taken into account.
229 /// Always break after the return type.
231 /// Always break after the return types of top-level functions.
235 /// \brief Different ways to break after the function definition or
236 /// declaration return type.
237 enum ReturnTypeBreakingStyle {
238 /// Break after return type automatically.
239 /// ``PenaltyReturnTypeOnItsOwnLine`` is taken into account.
242 /// int f() { return 0; };
245 /// int f() { return 1; }
248 /// Always break after the return type.
264 /// Always break after the return types of top-level functions.
267 /// int f() { return 0; };
277 /// Always break after the return type of function definitions.
292 /// Always break after the return type of top-level definitions.
295 /// int f() { return 0; };
303 RTBS_TopLevelDefinitions,
306 /// \brief The function definition return type breaking style to use. This
307 /// option is **deprecated** and is retained for backwards compatibility.
308 DefinitionReturnTypeBreakingStyle AlwaysBreakAfterDefinitionReturnType;
310 /// \brief The function declaration return type breaking style to use.
311 ReturnTypeBreakingStyle AlwaysBreakAfterReturnType;
313 /// \brief If ``true``, always break before multiline string literals.
315 /// This flag is mean to make cases where there are multiple multiline strings
316 /// in a file look more consistent. Thus, it will only take effect if wrapping
317 /// the string at that point leads to it being indented
318 /// ``ContinuationIndentWidth`` spaces from the start of the line.
321 /// aaaa = vs. aaaa = "bbbb"
325 bool AlwaysBreakBeforeMultilineStrings;
327 /// \brief If ``true``, always break after the ``template<...>`` of a template
331 /// template <typename T> vs. template <typename T> class C {};
334 bool AlwaysBreakTemplateDeclarations;
336 /// \brief If ``false``, a function call's arguments will either be all on the
337 /// same line or will have one line each.
341 /// f(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaa,
342 /// aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);
347 /// f(aaaaaaaaaaaaaaaaaaaa,
348 /// aaaaaaaaaaaaaaaaaaaa,
349 /// aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);
352 bool BinPackArguments;
354 /// \brief If ``false``, a function declaration's or function definition's
355 /// parameters will either all be on the same line or will have one line each.
358 /// void f(int aaaaaaaaaaaaaaaaaaaa, int aaaaaaaaaaaaaaaaaaaa,
359 /// int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}
362 /// void f(int aaaaaaaaaaaaaaaaaaaa,
363 /// int aaaaaaaaaaaaaaaaaaaa,
364 /// int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}
366 bool BinPackParameters;
368 /// \brief The style of breaking before or after binary operators.
369 enum BinaryOperatorStyle {
370 /// Break after operators.
372 /// LooooooooooongType loooooooooooooooooooooongVariable =
373 /// someLooooooooooooooooongFunction();
375 /// bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +
376 /// aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==
377 /// aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa &&
378 /// aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >
379 /// ccccccccccccccccccccccccccccccccccccccccc;
382 /// Break before operators that aren't assignments.
384 /// LooooooooooongType loooooooooooooooooooooongVariable =
385 /// someLooooooooooooooooongFunction();
387 /// bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
388 /// + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
389 /// == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
390 /// && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
391 /// > ccccccccccccccccccccccccccccccccccccccccc;
394 /// Break before operators.
396 /// LooooooooooongType loooooooooooooooooooooongVariable
397 /// = someLooooooooooooooooongFunction();
399 /// bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
400 /// + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
401 /// == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
402 /// && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
403 /// > ccccccccccccccccccccccccccccccccccccccccc;
408 /// \brief The way to wrap binary operators.
409 BinaryOperatorStyle BreakBeforeBinaryOperators;
411 /// \brief Different ways to attach braces to their surrounding context.
412 enum BraceBreakingStyle {
413 /// Always attach braces to surrounding context.
419 /// void foo() { bar(); }
424 /// enum X : int { A, B };
427 /// Like ``Attach``, but break before braces on function, namespace and
428 /// class definitions.
434 /// void foo() { bar(); }
441 /// enum X : int { A, B };
444 /// Like ``Attach``, but break before braces on enum, function, and record
451 /// void foo() { bar(); }
458 /// enum X : int { A, B };
461 /// Like ``Attach``, but break before function definitions, ``catch``, and
468 /// void foo() { bar(); }
482 /// Always break before braces.
489 /// void foo() { bar(); }
496 /// enum X : int { A, B };
499 /// Always break before braces and add an extra level of indentation to
500 /// braces of control statements, not to those of class, function
501 /// or other definitions.
510 /// void foo() { bar(); }
527 /// Like ``Attach``, but break before functions.
533 /// void foo() { bar(); }
539 /// enum X : int { A, B };
542 /// Configure each individual brace in `BraceWrapping`.
546 /// \brief The brace breaking style to use.
547 BraceBreakingStyle BreakBeforeBraces;
549 /// \brief Precise control over the wrapping of braces.
551 /// # Should be declared this way:
552 /// BreakBeforeBraces: Custom
556 struct BraceWrappingFlags {
557 /// \brief Wrap class definitions.
567 /// \brief Wrap control statements (``if``/``for``/``while``/``switch``/..).
574 /// for (int i = 0; i < 10; ++i)
581 /// for (int i = 0; i < 10; ++i) {
584 bool AfterControlStatement;
585 /// \brief Wrap enum definitions.
594 /// enum X : int { B };
597 /// \brief Wrap function definitions.
613 /// \brief Wrap namespace definitions.
629 /// \brief Wrap ObjC definitions (``@autoreleasepool``, interfaces, ..).
630 bool AfterObjCDeclaration;
631 /// \brief Wrap struct definitions.
645 /// \brief Wrap union definitions.
659 /// \brief Wrap before ``catch``.
675 /// \brief Wrap before ``else``.
689 /// \brief Indent the wrapped braces themselves.
693 /// \brief Control of individual brace wrapping cases.
695 /// If ``BreakBeforeBraces`` is set to ``BS_Custom``, use this to specify how
696 /// each individual brace case should be handled. Otherwise, this is ignored.
697 BraceWrappingFlags BraceWrapping;
699 /// \brief If ``true``, ternary operators will be placed after line breaks.
702 /// veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongDescription
704 /// : SecondValueVeryVeryVeryVeryLong;
707 /// veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongDescription ?
709 /// SecondValueVeryVeryVeryVeryLong;
711 bool BreakBeforeTernaryOperators;
713 /// \brief Always break constructor initializers before commas and align
714 /// the commas with the colon.
717 /// SomeClass::Constructor() vs. SomeClass::Constructor() : a(a),
722 bool BreakConstructorInitializersBeforeComma;
724 /// \brief Break after each annotation on a field in Java files.
727 /// @Partial vs. @Partial @Mock DataLoad loader;
731 bool BreakAfterJavaFieldAnnotations;
733 /// \brief Allow breaking string literals when formatting.
734 bool BreakStringLiterals;
736 /// \brief The column limit.
738 /// A column limit of ``0`` means that there is no column limit. In this case,
739 /// clang-format will respect the input's line breaking decisions within
740 /// statements unless they contradict other rules.
741 unsigned ColumnLimit;
743 /// \brief A regular expression that describes comments with special meaning,
744 /// which should not be split into lines or otherwise changed.
746 /// // CommentPragmas: '^ FOOBAR pragma:'
747 /// // Will leave the following line unaffected
748 /// #include <vector> // FOOBAR pragma: keep
750 std::string CommentPragmas;
752 /// \brief If ``true``, in the class inheritance expression clang-format will
753 /// break before ``:`` and ``,`` if there is multiple inheritance.
756 /// class MyClass vs. class MyClass : public X, public Y {
761 bool BreakBeforeInheritanceComma;
763 /// \brief If the constructor initializers don't fit on a line, put each
764 /// initializer on its own line.
767 /// SomeClass::Constructor()
768 /// : aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa) {
773 /// SomeClass::Constructor()
774 /// : aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaa),
775 /// aaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa) {
779 bool ConstructorInitializerAllOnOneLineOrOnePerLine;
781 /// \brief The number of characters to use for indentation of constructor
782 /// initializer lists.
783 unsigned ConstructorInitializerIndentWidth;
785 /// \brief Indent width for line continuations.
787 /// ContinuationIndentWidth: 2
789 /// int i = // VeryVeryVeryVeryVeryLongComment
790 /// longFunction( // Again a long comment
793 unsigned ContinuationIndentWidth;
795 /// \brief If ``true``, format braced lists as best suited for C++11 braced
798 /// Important differences:
799 /// - No spaces inside the braced list.
800 /// - No line break before the closing brace.
801 /// - Indentation with the continuation indent, not with the block indent.
803 /// Fundamentally, C++11 braced lists are formatted exactly like function
804 /// calls would be formatted in their place. If the braced list follows a name
805 /// (e.g. a type or variable name), clang-format formats as if the ``{}`` were
806 /// the parentheses of a function call with that name. If there is no name,
807 /// a zero-length name is assumed.
810 /// vector<int> x{1, 2, 3, 4}; vs. vector<int> x{ 1, 2, 3, 4 };
811 /// vector<T> x{{}, {}, {}, {}}; vector<T> x{ {}, {}, {}, {} };
812 /// f(MyMap[{composite, key}]); f(MyMap[{ composite, key }]);
813 /// new int[3]{1, 2, 3}; new int[3]{ 1, 2, 3 };
815 bool Cpp11BracedListStyle;
817 /// \brief If ``true``, analyze the formatted file for the most common
818 /// alignment of ``&`` and ``*``.
819 /// Pointer and reference alignment styles are going to be updated according
820 /// to the preferences found in the file.
821 /// ``PointerAlignment`` is then used only as fallback.
822 bool DerivePointerAlignment;
824 /// \brief Disables formatting completely.
827 /// \brief If ``true``, clang-format detects whether function calls and
828 /// definitions are formatted with one parameter per line.
830 /// Each call can be bin-packed, one-per-line or inconclusive. If it is
831 /// inconclusive, e.g. completely on one line, but a decision needs to be
832 /// made, clang-format analyzes whether there are other bin-packed cases in
833 /// the input file and act accordingly.
835 /// NOTE: This is an experimental flag, that might go away or be renamed. Do
836 /// not use this in config files, etc. Use at your own risk.
837 bool ExperimentalAutoDetectBinPacking;
839 /// \brief If ``true``, clang-format adds missing namespace end comments and
840 /// fixes invalid existing ones.
843 /// namespace a { vs. namespace a {
845 /// } // namespace a; }
847 bool FixNamespaceComments;
849 /// \brief A vector of macros that should be interpreted as foreach loops
850 /// instead of as function calls.
852 /// These are expected to be macros of the form:
854 /// FOREACH(<variable-declaration>, ...)
858 /// In the .clang-format configuration file, this can be configured like:
860 /// ForEachMacros: ['RANGES_FOR', 'FOREACH']
863 /// For example: BOOST_FOREACH.
864 std::vector<std::string> ForEachMacros;
866 /// \brief See documentation of ``IncludeCategories``.
867 struct IncludeCategory {
868 /// \brief The regular expression that this category matches.
870 /// \brief The priority to assign to this category.
872 bool operator==(const IncludeCategory &Other) const {
873 return Regex == Other.Regex && Priority == Other.Priority;
877 /// \brief Regular expressions denoting the different ``#include`` categories
878 /// used for ordering ``#includes``.
880 /// These regular expressions are matched against the filename of an include
881 /// (including the <> or "") in order. The value belonging to the first
882 /// matching regular expression is assigned and ``#includes`` are sorted first
883 /// according to increasing category number and then alphabetically within
886 /// If none of the regular expressions match, INT_MAX is assigned as
887 /// category. The main header for a source file automatically gets category 0.
888 /// so that it is generally kept at the beginning of the ``#includes``
889 /// (http://llvm.org/docs/CodingStandards.html#include-style). However, you
890 /// can also assign negative priorities if you have certain headers that
891 /// always need to be first.
893 /// To configure this in the .clang-format file, use:
895 /// IncludeCategories:
896 /// - Regex: '^"(llvm|llvm-c|clang|clang-c)/'
898 /// - Regex: '^(<|"(gtest|isl|json)/)'
903 std::vector<IncludeCategory> IncludeCategories;
905 /// \brief Specify a regular expression of suffixes that are allowed in the
906 /// file-to-main-include mapping.
908 /// When guessing whether a #include is the "main" include (to assign
909 /// category 0, see above), use this regex of allowed suffixes to the header
910 /// stem. A partial match is done, so that:
911 /// - "" means "arbitrary suffix"
912 /// - "$" means "no suffix"
914 /// For example, if configured to "(_test)?$", then a header a.h would be seen
915 /// as the "main" include in both a.cc and a_test.cc.
916 std::string IncludeIsMainRegex;
918 /// \brief Indent case labels one level from the switch statement.
920 /// When ``false``, use the same indentation level as for the switch statement.
921 /// Switch statement body is always indented one level more than case labels.
924 /// switch (fool) { vs. switch (fool) {
928 /// default: default:
932 bool IndentCaseLabels;
934 /// \brief The number of columns to use for indentation.
940 /// if (true, false) {
945 unsigned IndentWidth;
947 /// \brief Indent if a function definition or declaration is wrapped after the
951 /// LoooooooooooooooooooooooooooooooooooooooongReturnType
952 /// LoooooooooooooooooooooooooooooooongFunctionDeclaration();
955 /// LoooooooooooooooooooooooooooooooooooooooongReturnType
956 /// LoooooooooooooooooooooooooooooooongFunctionDeclaration();
958 bool IndentWrappedFunctionNames;
960 /// \brief Quotation styles for JavaScript strings. Does not affect template
962 enum JavaScriptQuoteStyle {
963 /// Leave string quotes as they are.
969 /// Always use single quotes.
975 /// Always use double quotes.
983 /// \brief The JavaScriptQuoteStyle to use for JavaScript strings.
984 JavaScriptQuoteStyle JavaScriptQuotes;
986 /// \brief Whether to wrap JavaScript import/export statements.
990 /// VeryLongImportsAreAnnoying,
991 /// VeryLongImportsAreAnnoying,
992 /// VeryLongImportsAreAnnoying,
993 /// } from 'some/module.js'
996 /// import {VeryLongImportsAreAnnoying, VeryLongImportsAreAnnoying, VeryLongImportsAreAnnoying,} from "some/module.js"
998 bool JavaScriptWrapImports;
1000 /// \brief If true, the empty line at the start of blocks is kept.
1003 /// if (foo) { vs. if (foo) {
1008 bool KeepEmptyLinesAtTheStartOfBlocks;
1010 /// \brief Supported languages.
1012 /// When stored in a configuration file, specifies the language, that the
1013 /// configuration targets. When passed to the ``reformat()`` function, enables
1014 /// syntax features specific to the language.
1018 /// Should be used for C, C++.
1020 /// Should be used for Java.
1022 /// Should be used for JavaScript.
1024 /// Should be used for Objective-C, Objective-C++.
1026 /// Should be used for Protocol Buffers
1027 /// (https://developers.google.com/protocol-buffers/).
1029 /// Should be used for TableGen code.
1032 bool isCpp() const { return Language == LK_Cpp || Language == LK_ObjC; }
1034 /// \brief Language, this format style is targeted at.
1035 LanguageKind Language;
1037 /// \brief A regular expression matching macros that start a block.
1040 /// MacroBlockBegin: "^NS_MAP_BEGIN|\
1042 /// MacroBlockEnd: "^\
1044 /// NS_TABLE_.*_END$"
1052 /// NS_TABLE_FOO_END
1061 /// NS_TABLE_FOO_END
1063 std::string MacroBlockBegin;
1065 /// \brief A regular expression matching macros that end a block.
1066 std::string MacroBlockEnd;
1068 /// \brief The maximum number of consecutive empty lines to keep.
1070 /// MaxEmptyLinesToKeep: 1 vs. MaxEmptyLinesToKeep: 0
1071 /// int f() { int f() {
1072 /// int = 1; int i = 1;
1074 /// i = foo(); return i;
1079 unsigned MaxEmptyLinesToKeep;
1081 /// \brief Different ways to indent namespace contents.
1082 enum NamespaceIndentationKind {
1083 /// Don't indent in namespaces.
1093 /// Indent only in inner namespaces (nested in other namespaces).
1103 /// Indent in all namespaces.
1115 /// \brief The indentation used for namespaces.
1116 NamespaceIndentationKind NamespaceIndentation;
1118 /// \brief The number of characters to use for indentation of ObjC blocks.
1120 /// ObjCBlockIndentWidth: 4
1122 /// [operation setCompletionBlock:^{
1123 /// [self onOperationDone];
1126 unsigned ObjCBlockIndentWidth;
1128 /// \brief Add a space after ``@property`` in Objective-C, i.e. use
1129 /// ``@property (readonly)`` instead of ``@property(readonly)``.
1130 bool ObjCSpaceAfterProperty;
1132 /// \brief Add a space in front of an Objective-C protocol list, i.e. use
1133 /// ``Foo <Protocol>`` instead of ``Foo<Protocol>``.
1134 bool ObjCSpaceBeforeProtocolList;
1136 /// \brief The penalty for breaking around an assignment operator.
1137 unsigned PenaltyBreakAssignment;
1139 /// \brief The penalty for breaking a function call after ``call(``.
1140 unsigned PenaltyBreakBeforeFirstCallParameter;
1142 /// \brief The penalty for each line break introduced inside a comment.
1143 unsigned PenaltyBreakComment;
1145 /// \brief The penalty for breaking before the first ``<<``.
1146 unsigned PenaltyBreakFirstLessLess;
1148 /// \brief The penalty for each line break introduced inside a string literal.
1149 unsigned PenaltyBreakString;
1151 /// \brief The penalty for each character outside of the column limit.
1152 unsigned PenaltyExcessCharacter;
1154 /// \brief Penalty for putting the return type of a function onto its own
1156 unsigned PenaltyReturnTypeOnItsOwnLine;
1158 /// \brief The ``&`` and ``*`` alignment style.
1159 enum PointerAlignmentStyle {
1160 /// Align pointer to the left.
1165 /// Align pointer to the right.
1170 /// Align pointer in the middle.
1177 /// \brief Pointer and reference alignment style.
1178 PointerAlignmentStyle PointerAlignment;
1180 /// \brief If ``true``, clang-format will attempt to re-flow comments.
1183 /// // veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongComment with plenty of information
1184 /// /* second veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongComment with plenty of information */
1187 /// // veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongComment with plenty of
1189 /// /* second veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongComment with plenty of
1190 /// * information */
1192 bool ReflowComments;
1194 /// \brief If ``true``, clang-format will sort ``#includes``.
1197 /// #include "b.h" vs. #include "a.h"
1198 /// #include "a.h" #include "b.h"
1202 /// \brief If ``true``, a space is inserted after C style casts.
1205 /// (int)i; vs. (int) i;
1207 bool SpaceAfterCStyleCast;
1209 /// \brief If \c true, a space will be inserted after the 'template' keyword.
1212 /// template <int> void foo(); vs. template<int> void foo();
1214 bool SpaceAfterTemplateKeyword;
1216 /// \brief If ``false``, spaces will be removed before assignment operators.
1219 /// int a = 5; vs. int a=5;
1222 bool SpaceBeforeAssignmentOperators;
1224 /// \brief Different ways to put a space before opening parentheses.
1225 enum SpaceBeforeParensOptions {
1226 /// Never put a space before opening parentheses.
1235 /// Put a space before opening parentheses only after control statement
1236 /// keywords (``for/if/while...``).
1244 SBPO_ControlStatements,
1245 /// Always put a space before opening parentheses, except when it's
1246 /// prohibited by the syntax rules (in function-like macro definitions) or
1247 /// when determined by other style rules (after unary operators, opening
1248 /// parentheses, etc.)
1259 /// \brief Defines in which cases to put a space before opening parentheses.
1260 SpaceBeforeParensOptions SpaceBeforeParens;
1262 /// \brief If ``true``, spaces may be inserted into ``()``.
1265 /// void f( ) { vs. void f() {
1266 /// int x[] = {foo( ), bar( )}; int x[] = {foo(), bar()};
1267 /// if (true) { if (true) {
1272 bool SpaceInEmptyParentheses;
1274 /// \brief The number of spaces before trailing line comments
1275 /// (``//`` - comments).
1277 /// This does not affect trailing block comments (``/*`` - comments) as
1278 /// those commonly have different usage patterns and a number of special
1281 /// SpacesBeforeTrailingComments: 3
1283 /// if (true) { // foo1
1288 unsigned SpacesBeforeTrailingComments;
1290 /// \brief If ``true``, spaces will be inserted after ``<`` and before ``>``
1291 /// in template argument lists.
1294 /// static_cast< int >(arg); vs. static_cast<int>(arg);
1295 /// std::function< void(int) > fct; std::function<void(int)> fct;
1297 bool SpacesInAngles;
1299 /// \brief If ``true``, spaces are inserted inside container literals (e.g.
1300 /// ObjC and Javascript array and dict literals).
1303 /// var arr = [ 1, 2, 3 ]; vs. var arr = [1, 2, 3];
1304 /// f({a : 1, b : 2, c : 3}); f({a: 1, b: 2, c: 3});
1306 bool SpacesInContainerLiterals;
1308 /// \brief If ``true``, spaces may be inserted into C style casts.
1311 /// x = ( int32 )y vs. x = (int32)y
1313 bool SpacesInCStyleCastParentheses;
1315 /// \brief If ``true``, spaces will be inserted after ``(`` and before ``)``.
1318 /// t f( Deleted & ) & = delete; vs. t f(Deleted &) & = delete;
1320 bool SpacesInParentheses;
1322 /// \brief If ``true``, spaces will be inserted after ``[`` and before ``]``.
1323 /// Lambdas or unspecified size array declarations will not be affected.
1326 /// int a[ 5 ]; vs. int a[5];
1327 /// std::unique_ptr<int[]> foo() {} // Won't be affected
1329 bool SpacesInSquareBrackets;
1331 /// \brief Supported language standards.
1332 enum LanguageStandard {
1333 /// Use C++03-compatible syntax.
1335 /// Use features of C++11, C++14 and C++1z (e.g. ``A<A<int>>`` instead of
1336 /// ``A<A<int> >``).
1338 /// Automatic detection based on the input.
1342 /// \brief Format compatible with this standard, e.g. use ``A<A<int> >``
1343 /// instead of ``A<A<int>>`` for ``LS_Cpp03``.
1344 LanguageStandard Standard;
1346 /// \brief The number of columns used for tab stops.
1349 /// \brief Different ways to use tab in formatting.
1353 /// Use tabs only for indentation.
1355 /// Use tabs only for line continuation and indentation.
1356 UT_ForContinuationAndIndentation,
1357 /// Use tabs whenever we need to fill whitespace that spans at least from
1358 /// one tab stop to the next one.
1362 /// \brief The way to use tab characters in the resulting file.
1365 bool operator==(const FormatStyle &R) const {
1366 return AccessModifierOffset == R.AccessModifierOffset &&
1367 AlignAfterOpenBracket == R.AlignAfterOpenBracket &&
1368 AlignConsecutiveAssignments == R.AlignConsecutiveAssignments &&
1369 AlignConsecutiveDeclarations == R.AlignConsecutiveDeclarations &&
1370 AlignEscapedNewlines == R.AlignEscapedNewlines &&
1371 AlignOperands == R.AlignOperands &&
1372 AlignTrailingComments == R.AlignTrailingComments &&
1373 AllowAllParametersOfDeclarationOnNextLine ==
1374 R.AllowAllParametersOfDeclarationOnNextLine &&
1375 AllowShortBlocksOnASingleLine == R.AllowShortBlocksOnASingleLine &&
1376 AllowShortCaseLabelsOnASingleLine ==
1377 R.AllowShortCaseLabelsOnASingleLine &&
1378 AllowShortFunctionsOnASingleLine ==
1379 R.AllowShortFunctionsOnASingleLine &&
1380 AllowShortIfStatementsOnASingleLine ==
1381 R.AllowShortIfStatementsOnASingleLine &&
1382 AllowShortLoopsOnASingleLine == R.AllowShortLoopsOnASingleLine &&
1383 AlwaysBreakAfterReturnType == R.AlwaysBreakAfterReturnType &&
1384 AlwaysBreakBeforeMultilineStrings ==
1385 R.AlwaysBreakBeforeMultilineStrings &&
1386 AlwaysBreakTemplateDeclarations ==
1387 R.AlwaysBreakTemplateDeclarations &&
1388 BinPackArguments == R.BinPackArguments &&
1389 BinPackParameters == R.BinPackParameters &&
1390 BreakBeforeBinaryOperators == R.BreakBeforeBinaryOperators &&
1391 BreakBeforeBraces == R.BreakBeforeBraces &&
1392 BreakBeforeTernaryOperators == R.BreakBeforeTernaryOperators &&
1393 BreakConstructorInitializersBeforeComma ==
1394 R.BreakConstructorInitializersBeforeComma &&
1395 BreakAfterJavaFieldAnnotations == R.BreakAfterJavaFieldAnnotations &&
1396 BreakStringLiterals == R.BreakStringLiterals &&
1397 ColumnLimit == R.ColumnLimit && CommentPragmas == R.CommentPragmas &&
1398 BreakBeforeInheritanceComma == R.BreakBeforeInheritanceComma &&
1399 ConstructorInitializerAllOnOneLineOrOnePerLine ==
1400 R.ConstructorInitializerAllOnOneLineOrOnePerLine &&
1401 ConstructorInitializerIndentWidth ==
1402 R.ConstructorInitializerIndentWidth &&
1403 ContinuationIndentWidth == R.ContinuationIndentWidth &&
1404 Cpp11BracedListStyle == R.Cpp11BracedListStyle &&
1405 DerivePointerAlignment == R.DerivePointerAlignment &&
1406 DisableFormat == R.DisableFormat &&
1407 ExperimentalAutoDetectBinPacking ==
1408 R.ExperimentalAutoDetectBinPacking &&
1409 FixNamespaceComments == R.FixNamespaceComments &&
1410 ForEachMacros == R.ForEachMacros &&
1411 IncludeCategories == R.IncludeCategories &&
1412 IndentCaseLabels == R.IndentCaseLabels &&
1413 IndentWidth == R.IndentWidth && Language == R.Language &&
1414 IndentWrappedFunctionNames == R.IndentWrappedFunctionNames &&
1415 JavaScriptQuotes == R.JavaScriptQuotes &&
1416 JavaScriptWrapImports == R.JavaScriptWrapImports &&
1417 KeepEmptyLinesAtTheStartOfBlocks ==
1418 R.KeepEmptyLinesAtTheStartOfBlocks &&
1419 MacroBlockBegin == R.MacroBlockBegin &&
1420 MacroBlockEnd == R.MacroBlockEnd &&
1421 MaxEmptyLinesToKeep == R.MaxEmptyLinesToKeep &&
1422 NamespaceIndentation == R.NamespaceIndentation &&
1423 ObjCBlockIndentWidth == R.ObjCBlockIndentWidth &&
1424 ObjCSpaceAfterProperty == R.ObjCSpaceAfterProperty &&
1425 ObjCSpaceBeforeProtocolList == R.ObjCSpaceBeforeProtocolList &&
1426 PenaltyBreakAssignment ==
1427 R.PenaltyBreakAssignment &&
1428 PenaltyBreakBeforeFirstCallParameter ==
1429 R.PenaltyBreakBeforeFirstCallParameter &&
1430 PenaltyBreakComment == R.PenaltyBreakComment &&
1431 PenaltyBreakFirstLessLess == R.PenaltyBreakFirstLessLess &&
1432 PenaltyBreakString == R.PenaltyBreakString &&
1433 PenaltyExcessCharacter == R.PenaltyExcessCharacter &&
1434 PenaltyReturnTypeOnItsOwnLine == R.PenaltyReturnTypeOnItsOwnLine &&
1435 PointerAlignment == R.PointerAlignment &&
1436 SpaceAfterCStyleCast == R.SpaceAfterCStyleCast &&
1437 SpaceAfterTemplateKeyword == R.SpaceAfterTemplateKeyword &&
1438 SpaceBeforeAssignmentOperators == R.SpaceBeforeAssignmentOperators &&
1439 SpaceBeforeParens == R.SpaceBeforeParens &&
1440 SpaceInEmptyParentheses == R.SpaceInEmptyParentheses &&
1441 SpacesBeforeTrailingComments == R.SpacesBeforeTrailingComments &&
1442 SpacesInAngles == R.SpacesInAngles &&
1443 SpacesInContainerLiterals == R.SpacesInContainerLiterals &&
1444 SpacesInCStyleCastParentheses == R.SpacesInCStyleCastParentheses &&
1445 SpacesInParentheses == R.SpacesInParentheses &&
1446 SpacesInSquareBrackets == R.SpacesInSquareBrackets &&
1447 Standard == R.Standard && TabWidth == R.TabWidth &&
1452 /// \brief Returns a format style complying with the LLVM coding standards:
1453 /// http://llvm.org/docs/CodingStandards.html.
1454 FormatStyle getLLVMStyle();
1456 /// \brief Returns a format style complying with one of Google's style guides:
1457 /// http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml.
1458 /// http://google-styleguide.googlecode.com/svn/trunk/javascriptguide.xml.
1459 /// https://developers.google.com/protocol-buffers/docs/style.
1460 FormatStyle getGoogleStyle(FormatStyle::LanguageKind Language);
1462 /// \brief Returns a format style complying with Chromium's style guide:
1463 /// http://www.chromium.org/developers/coding-style.
1464 FormatStyle getChromiumStyle(FormatStyle::LanguageKind Language);
1466 /// \brief Returns a format style complying with Mozilla's style guide:
1467 /// https://developer.mozilla.org/en-US/docs/Developer_Guide/Coding_Style.
1468 FormatStyle getMozillaStyle();
1470 /// \brief Returns a format style complying with Webkit's style guide:
1471 /// http://www.webkit.org/coding/coding-style.html
1472 FormatStyle getWebKitStyle();
1474 /// \brief Returns a format style complying with GNU Coding Standards:
1475 /// http://www.gnu.org/prep/standards/standards.html
1476 FormatStyle getGNUStyle();
1478 /// \brief Returns style indicating formatting should be not applied at all.
1479 FormatStyle getNoStyle();
1481 /// \brief Gets a predefined style for the specified language by name.
1483 /// Currently supported names: LLVM, Google, Chromium, Mozilla. Names are
1484 /// compared case-insensitively.
1486 /// Returns ``true`` if the Style has been set.
1487 bool getPredefinedStyle(StringRef Name, FormatStyle::LanguageKind Language,
1488 FormatStyle *Style);
1490 /// \brief Parse configuration from YAML-formatted text.
1492 /// Style->Language is used to get the base style, if the ``BasedOnStyle``
1493 /// option is present.
1495 /// When ``BasedOnStyle`` is not present, options not present in the YAML
1496 /// document, are retained in \p Style.
1497 std::error_code parseConfiguration(StringRef Text, FormatStyle *Style);
1499 /// \brief Gets configuration in a YAML string.
1500 std::string configurationAsText(const FormatStyle &Style);
1502 /// \brief Returns the replacements necessary to sort all ``#include`` blocks
1503 /// that are affected by ``Ranges``.
1504 tooling::Replacements sortIncludes(const FormatStyle &Style, StringRef Code,
1505 ArrayRef<tooling::Range> Ranges,
1507 unsigned *Cursor = nullptr);
1509 /// \brief Returns the replacements corresponding to applying and formatting
1510 /// \p Replaces on success; otheriwse, return an llvm::Error carrying
1511 /// llvm::StringError.
1512 llvm::Expected<tooling::Replacements>
1513 formatReplacements(StringRef Code, const tooling::Replacements &Replaces,
1514 const FormatStyle &Style);
1516 /// \brief Returns the replacements corresponding to applying \p Replaces and
1517 /// cleaning up the code after that on success; otherwise, return an llvm::Error
1518 /// carrying llvm::StringError.
1519 /// This also supports inserting/deleting C++ #include directives:
1520 /// - If a replacement has offset UINT_MAX, length 0, and a replacement text
1521 /// that is an #include directive, this will insert the #include into the
1522 /// correct block in the \p Code. When searching for points to insert new
1523 /// header, this ignores #include's after the #include block(s) in the
1524 /// beginning of a file to avoid inserting headers into code sections where
1525 /// new #include's should not be added by default. These code sections
1527 /// - raw string literals (containing #include).
1529 /// - Special #include's among declarations (e.g. functions).
1530 /// - If a replacement has offset UINT_MAX, length 1, and a replacement text
1531 /// that is the name of the header to be removed, the header will be removed
1532 /// from \p Code if it exists.
1533 llvm::Expected<tooling::Replacements>
1534 cleanupAroundReplacements(StringRef Code, const tooling::Replacements &Replaces,
1535 const FormatStyle &Style);
1537 /// \brief Represents the status of a formatting attempt.
1538 struct FormattingAttemptStatus {
1539 /// \brief A value of ``false`` means that any of the affected ranges were not
1540 /// formatted due to a non-recoverable syntax error.
1541 bool FormatComplete = true;
1543 /// \brief If ``FormatComplete`` is false, ``Line`` records a one-based
1544 /// original line number at which a syntax error might have occurred. This is
1545 /// based on a best-effort analysis and could be imprecise.
1549 /// \brief Reformats the given \p Ranges in \p Code.
1551 /// Each range is extended on either end to its next bigger logic unit, i.e.
1552 /// everything that might influence its formatting or might be influenced by its
1555 /// Returns the ``Replacements`` necessary to make all \p Ranges comply with
1558 /// If ``Status`` is non-null, its value will be populated with the status of
1559 /// this formatting attempt. See \c FormattingAttemptStatus.
1560 tooling::Replacements reformat(const FormatStyle &Style, StringRef Code,
1561 ArrayRef<tooling::Range> Ranges,
1562 StringRef FileName = "<stdin>",
1563 FormattingAttemptStatus *Status = nullptr);
1565 /// \brief Same as above, except if ``IncompleteFormat`` is non-null, its value
1566 /// will be set to true if any of the affected ranges were not formatted due to
1567 /// a non-recoverable syntax error.
1568 tooling::Replacements reformat(const FormatStyle &Style, StringRef Code,
1569 ArrayRef<tooling::Range> Ranges,
1571 bool *IncompleteFormat);
1573 /// \brief Clean up any erroneous/redundant code in the given \p Ranges in \p
1576 /// Returns the ``Replacements`` that clean up all \p Ranges in \p Code.
1577 tooling::Replacements cleanup(const FormatStyle &Style, StringRef Code,
1578 ArrayRef<tooling::Range> Ranges,
1579 StringRef FileName = "<stdin>");
1581 /// \brief Fix namespace end comments in the given \p Ranges in \p Code.
1583 /// Returns the ``Replacements`` that fix the namespace comments in all
1584 /// \p Ranges in \p Code.
1585 tooling::Replacements fixNamespaceEndComments(const FormatStyle &Style,
1587 ArrayRef<tooling::Range> Ranges,
1588 StringRef FileName = "<stdin>");
1590 /// \brief Returns the ``LangOpts`` that the formatter expects you to set.
1592 /// \param Style determines specific settings for lexing mode.
1593 LangOptions getFormattingLangOpts(const FormatStyle &Style = getLLVMStyle());
1595 /// \brief Description to be used for help text for a ``llvm::cl`` option for
1596 /// specifying format style. The description is closely related to the operation
1597 /// of ``getStyle()``.
1598 extern const char *StyleOptionHelpDescription;
1600 /// \brief Construct a FormatStyle based on ``StyleName``.
1602 /// ``StyleName`` can take several forms:
1603 /// * "{<key>: <value>, ...}" - Set specic style parameters.
1604 /// * "<style name>" - One of the style names supported by
1605 /// getPredefinedStyle().
1606 /// * "file" - Load style configuration from a file called ``.clang-format``
1607 /// located in one of the parent directories of ``FileName`` or the current
1608 /// directory if ``FileName`` is empty.
1610 /// \param[in] StyleName Style name to interpret according to the description
1612 /// \param[in] FileName Path to start search for .clang-format if ``StyleName``
1614 /// \param[in] FallbackStyle The name of a predefined style used to fallback to
1615 /// in case \p StyleName is "file" and no file can be found.
1616 /// \param[in] Code The actual code to be formatted. Used to determine the
1617 /// language if the filename isn't sufficient.
1618 /// \param[in] FS The underlying file system, in which the file resides. By
1619 /// default, the file system is the real file system.
1621 /// \returns FormatStyle as specified by ``StyleName``. If ``StyleName`` is
1622 /// "file" and no file is found, returns ``FallbackStyle``. If no style could be
1623 /// determined, returns an Error.
1624 llvm::Expected<FormatStyle> getStyle(StringRef StyleName, StringRef FileName,
1625 StringRef FallbackStyle,
1626 StringRef Code = "",
1627 vfs::FileSystem *FS = nullptr);
1629 // \brief Returns a string representation of ``Language``.
1630 inline StringRef getLanguageName(FormatStyle::LanguageKind Language) {
1632 case FormatStyle::LK_Cpp:
1634 case FormatStyle::LK_ObjC:
1635 return "Objective-C";
1636 case FormatStyle::LK_Java:
1638 case FormatStyle::LK_JavaScript:
1639 return "JavaScript";
1640 case FormatStyle::LK_Proto:
1647 } // end namespace format
1648 } // end namespace clang
1652 struct is_error_code_enum<clang::format::ParseError> : std::true_type {};
1655 #endif // LLVM_CLANG_FORMAT_FORMAT_H