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 Different ways to break initializers.
714 enum BreakConstructorInitializersStyle
716 /// Break constructor initializers before the colon and after the commas.
719 /// : initializer1(),
723 /// Break constructor initializers before the colon and commas, and align
724 /// the commas with the colon.
731 /// Break constructor initializers after the colon and commas.
740 /// \brief The constructor initializers style to use..
741 BreakConstructorInitializersStyle BreakConstructorInitializers;
743 /// \brief Break after each annotation on a field in Java files.
746 /// @Partial vs. @Partial @Mock DataLoad loader;
750 bool BreakAfterJavaFieldAnnotations;
752 /// \brief Allow breaking string literals when formatting.
753 bool BreakStringLiterals;
755 /// \brief The column limit.
757 /// A column limit of ``0`` means that there is no column limit. In this case,
758 /// clang-format will respect the input's line breaking decisions within
759 /// statements unless they contradict other rules.
760 unsigned ColumnLimit;
762 /// \brief A regular expression that describes comments with special meaning,
763 /// which should not be split into lines or otherwise changed.
765 /// // CommentPragmas: '^ FOOBAR pragma:'
766 /// // Will leave the following line unaffected
767 /// #include <vector> // FOOBAR pragma: keep
769 std::string CommentPragmas;
771 /// \brief If ``true``, in the class inheritance expression clang-format will
772 /// break before ``:`` and ``,`` if there is multiple inheritance.
775 /// class MyClass vs. class MyClass : public X, public Y {
780 bool BreakBeforeInheritanceComma;
782 /// \brief If the constructor initializers don't fit on a line, put each
783 /// initializer on its own line.
786 /// SomeClass::Constructor()
787 /// : aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa) {
792 /// SomeClass::Constructor()
793 /// : aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaa),
794 /// aaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa) {
798 bool ConstructorInitializerAllOnOneLineOrOnePerLine;
800 /// \brief The number of characters to use for indentation of constructor
801 /// initializer lists.
802 unsigned ConstructorInitializerIndentWidth;
804 /// \brief Indent width for line continuations.
806 /// ContinuationIndentWidth: 2
808 /// int i = // VeryVeryVeryVeryVeryLongComment
809 /// longFunction( // Again a long comment
812 unsigned ContinuationIndentWidth;
814 /// \brief If ``true``, format braced lists as best suited for C++11 braced
817 /// Important differences:
818 /// - No spaces inside the braced list.
819 /// - No line break before the closing brace.
820 /// - Indentation with the continuation indent, not with the block indent.
822 /// Fundamentally, C++11 braced lists are formatted exactly like function
823 /// calls would be formatted in their place. If the braced list follows a name
824 /// (e.g. a type or variable name), clang-format formats as if the ``{}`` were
825 /// the parentheses of a function call with that name. If there is no name,
826 /// a zero-length name is assumed.
829 /// vector<int> x{1, 2, 3, 4}; vs. vector<int> x{ 1, 2, 3, 4 };
830 /// vector<T> x{{}, {}, {}, {}}; vector<T> x{ {}, {}, {}, {} };
831 /// f(MyMap[{composite, key}]); f(MyMap[{ composite, key }]);
832 /// new int[3]{1, 2, 3}; new int[3]{ 1, 2, 3 };
834 bool Cpp11BracedListStyle;
836 /// \brief If ``true``, analyze the formatted file for the most common
837 /// alignment of ``&`` and ``*``.
838 /// Pointer and reference alignment styles are going to be updated according
839 /// to the preferences found in the file.
840 /// ``PointerAlignment`` is then used only as fallback.
841 bool DerivePointerAlignment;
843 /// \brief Disables formatting completely.
846 /// \brief If ``true``, clang-format detects whether function calls and
847 /// definitions are formatted with one parameter per line.
849 /// Each call can be bin-packed, one-per-line or inconclusive. If it is
850 /// inconclusive, e.g. completely on one line, but a decision needs to be
851 /// made, clang-format analyzes whether there are other bin-packed cases in
852 /// the input file and act accordingly.
854 /// NOTE: This is an experimental flag, that might go away or be renamed. Do
855 /// not use this in config files, etc. Use at your own risk.
856 bool ExperimentalAutoDetectBinPacking;
858 /// \brief If ``true``, clang-format adds missing namespace end comments and
859 /// fixes invalid existing ones.
862 /// namespace a { vs. namespace a {
864 /// } // namespace a; }
866 bool FixNamespaceComments;
868 /// \brief A vector of macros that should be interpreted as foreach loops
869 /// instead of as function calls.
871 /// These are expected to be macros of the form:
873 /// FOREACH(<variable-declaration>, ...)
877 /// In the .clang-format configuration file, this can be configured like:
879 /// ForEachMacros: ['RANGES_FOR', 'FOREACH']
882 /// For example: BOOST_FOREACH.
883 std::vector<std::string> ForEachMacros;
885 /// \brief See documentation of ``IncludeCategories``.
886 struct IncludeCategory {
887 /// \brief The regular expression that this category matches.
889 /// \brief The priority to assign to this category.
891 bool operator==(const IncludeCategory &Other) const {
892 return Regex == Other.Regex && Priority == Other.Priority;
896 /// \brief Regular expressions denoting the different ``#include`` categories
897 /// used for ordering ``#includes``.
899 /// These regular expressions are matched against the filename of an include
900 /// (including the <> or "") in order. The value belonging to the first
901 /// matching regular expression is assigned and ``#includes`` are sorted first
902 /// according to increasing category number and then alphabetically within
905 /// If none of the regular expressions match, INT_MAX is assigned as
906 /// category. The main header for a source file automatically gets category 0.
907 /// so that it is generally kept at the beginning of the ``#includes``
908 /// (http://llvm.org/docs/CodingStandards.html#include-style). However, you
909 /// can also assign negative priorities if you have certain headers that
910 /// always need to be first.
912 /// To configure this in the .clang-format file, use:
914 /// IncludeCategories:
915 /// - Regex: '^"(llvm|llvm-c|clang|clang-c)/'
917 /// - Regex: '^(<|"(gtest|isl|json)/)'
922 std::vector<IncludeCategory> IncludeCategories;
924 /// \brief Specify a regular expression of suffixes that are allowed in the
925 /// file-to-main-include mapping.
927 /// When guessing whether a #include is the "main" include (to assign
928 /// category 0, see above), use this regex of allowed suffixes to the header
929 /// stem. A partial match is done, so that:
930 /// - "" means "arbitrary suffix"
931 /// - "$" means "no suffix"
933 /// For example, if configured to "(_test)?$", then a header a.h would be seen
934 /// as the "main" include in both a.cc and a_test.cc.
935 std::string IncludeIsMainRegex;
937 /// \brief Indent case labels one level from the switch statement.
939 /// When ``false``, use the same indentation level as for the switch statement.
940 /// Switch statement body is always indented one level more than case labels.
943 /// switch (fool) { vs. switch (fool) {
947 /// default: default:
951 bool IndentCaseLabels;
953 /// \brief The number of columns to use for indentation.
959 /// if (true, false) {
964 unsigned IndentWidth;
966 /// \brief Indent if a function definition or declaration is wrapped after the
970 /// LoooooooooooooooooooooooooooooooooooooooongReturnType
971 /// LoooooooooooooooooooooooooooooooongFunctionDeclaration();
974 /// LoooooooooooooooooooooooooooooooooooooooongReturnType
975 /// LoooooooooooooooooooooooooooooooongFunctionDeclaration();
977 bool IndentWrappedFunctionNames;
979 /// \brief Quotation styles for JavaScript strings. Does not affect template
981 enum JavaScriptQuoteStyle {
982 /// Leave string quotes as they are.
988 /// Always use single quotes.
994 /// Always use double quotes.
1002 /// \brief The JavaScriptQuoteStyle to use for JavaScript strings.
1003 JavaScriptQuoteStyle JavaScriptQuotes;
1005 /// \brief Whether to wrap JavaScript import/export statements.
1009 /// VeryLongImportsAreAnnoying,
1010 /// VeryLongImportsAreAnnoying,
1011 /// VeryLongImportsAreAnnoying,
1012 /// } from 'some/module.js'
1015 /// import {VeryLongImportsAreAnnoying, VeryLongImportsAreAnnoying, VeryLongImportsAreAnnoying,} from "some/module.js"
1017 bool JavaScriptWrapImports;
1019 /// \brief If true, the empty line at the start of blocks is kept.
1022 /// if (foo) { vs. if (foo) {
1027 bool KeepEmptyLinesAtTheStartOfBlocks;
1029 /// \brief Supported languages.
1031 /// When stored in a configuration file, specifies the language, that the
1032 /// configuration targets. When passed to the ``reformat()`` function, enables
1033 /// syntax features specific to the language.
1037 /// Should be used for C, C++.
1039 /// Should be used for Java.
1041 /// Should be used for JavaScript.
1043 /// Should be used for Objective-C, Objective-C++.
1045 /// Should be used for Protocol Buffers
1046 /// (https://developers.google.com/protocol-buffers/).
1048 /// Should be used for TableGen code.
1051 bool isCpp() const { return Language == LK_Cpp || Language == LK_ObjC; }
1053 /// \brief Language, this format style is targeted at.
1054 LanguageKind Language;
1056 /// \brief A regular expression matching macros that start a block.
1059 /// MacroBlockBegin: "^NS_MAP_BEGIN|\
1061 /// MacroBlockEnd: "^\
1063 /// NS_TABLE_.*_END$"
1071 /// NS_TABLE_FOO_END
1080 /// NS_TABLE_FOO_END
1082 std::string MacroBlockBegin;
1084 /// \brief A regular expression matching macros that end a block.
1085 std::string MacroBlockEnd;
1087 /// \brief The maximum number of consecutive empty lines to keep.
1089 /// MaxEmptyLinesToKeep: 1 vs. MaxEmptyLinesToKeep: 0
1090 /// int f() { int f() {
1091 /// int = 1; int i = 1;
1093 /// i = foo(); return i;
1098 unsigned MaxEmptyLinesToKeep;
1100 /// \brief Different ways to indent namespace contents.
1101 enum NamespaceIndentationKind {
1102 /// Don't indent in namespaces.
1112 /// Indent only in inner namespaces (nested in other namespaces).
1122 /// Indent in all namespaces.
1134 /// \brief The indentation used for namespaces.
1135 NamespaceIndentationKind NamespaceIndentation;
1137 /// \brief The number of characters to use for indentation of ObjC blocks.
1139 /// ObjCBlockIndentWidth: 4
1141 /// [operation setCompletionBlock:^{
1142 /// [self onOperationDone];
1145 unsigned ObjCBlockIndentWidth;
1147 /// \brief Add a space after ``@property`` in Objective-C, i.e. use
1148 /// ``@property (readonly)`` instead of ``@property(readonly)``.
1149 bool ObjCSpaceAfterProperty;
1151 /// \brief Add a space in front of an Objective-C protocol list, i.e. use
1152 /// ``Foo <Protocol>`` instead of ``Foo<Protocol>``.
1153 bool ObjCSpaceBeforeProtocolList;
1155 /// \brief The penalty for breaking around an assignment operator.
1156 unsigned PenaltyBreakAssignment;
1158 /// \brief The penalty for breaking a function call after ``call(``.
1159 unsigned PenaltyBreakBeforeFirstCallParameter;
1161 /// \brief The penalty for each line break introduced inside a comment.
1162 unsigned PenaltyBreakComment;
1164 /// \brief The penalty for breaking before the first ``<<``.
1165 unsigned PenaltyBreakFirstLessLess;
1167 /// \brief The penalty for each line break introduced inside a string literal.
1168 unsigned PenaltyBreakString;
1170 /// \brief The penalty for each character outside of the column limit.
1171 unsigned PenaltyExcessCharacter;
1173 /// \brief Penalty for putting the return type of a function onto its own
1175 unsigned PenaltyReturnTypeOnItsOwnLine;
1177 /// \brief The ``&`` and ``*`` alignment style.
1178 enum PointerAlignmentStyle {
1179 /// Align pointer to the left.
1184 /// Align pointer to the right.
1189 /// Align pointer in the middle.
1196 /// \brief Pointer and reference alignment style.
1197 PointerAlignmentStyle PointerAlignment;
1199 /// \brief If ``true``, clang-format will attempt to re-flow comments.
1202 /// // veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongComment with plenty of information
1203 /// /* second veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongComment with plenty of information */
1206 /// // veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongComment with plenty of
1208 /// /* second veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongComment with plenty of
1209 /// * information */
1211 bool ReflowComments;
1213 /// \brief If ``true``, clang-format will sort ``#includes``.
1216 /// #include "b.h" vs. #include "a.h"
1217 /// #include "a.h" #include "b.h"
1221 /// \brief If ``true``, a space is inserted after C style casts.
1224 /// (int)i; vs. (int) i;
1226 bool SpaceAfterCStyleCast;
1228 /// \brief If \c true, a space will be inserted after the 'template' keyword.
1231 /// template <int> void foo(); vs. template<int> void foo();
1233 bool SpaceAfterTemplateKeyword;
1235 /// \brief If ``false``, spaces will be removed before assignment operators.
1238 /// int a = 5; vs. int a=5;
1241 bool SpaceBeforeAssignmentOperators;
1243 /// \brief Different ways to put a space before opening parentheses.
1244 enum SpaceBeforeParensOptions {
1245 /// Never put a space before opening parentheses.
1254 /// Put a space before opening parentheses only after control statement
1255 /// keywords (``for/if/while...``).
1263 SBPO_ControlStatements,
1264 /// Always put a space before opening parentheses, except when it's
1265 /// prohibited by the syntax rules (in function-like macro definitions) or
1266 /// when determined by other style rules (after unary operators, opening
1267 /// parentheses, etc.)
1278 /// \brief Defines in which cases to put a space before opening parentheses.
1279 SpaceBeforeParensOptions SpaceBeforeParens;
1281 /// \brief If ``true``, spaces may be inserted into ``()``.
1284 /// void f( ) { vs. void f() {
1285 /// int x[] = {foo( ), bar( )}; int x[] = {foo(), bar()};
1286 /// if (true) { if (true) {
1291 bool SpaceInEmptyParentheses;
1293 /// \brief The number of spaces before trailing line comments
1294 /// (``//`` - comments).
1296 /// This does not affect trailing block comments (``/*`` - comments) as
1297 /// those commonly have different usage patterns and a number of special
1300 /// SpacesBeforeTrailingComments: 3
1302 /// if (true) { // foo1
1307 unsigned SpacesBeforeTrailingComments;
1309 /// \brief If ``true``, spaces will be inserted after ``<`` and before ``>``
1310 /// in template argument lists.
1313 /// static_cast< int >(arg); vs. static_cast<int>(arg);
1314 /// std::function< void(int) > fct; std::function<void(int)> fct;
1316 bool SpacesInAngles;
1318 /// \brief If ``true``, spaces are inserted inside container literals (e.g.
1319 /// ObjC and Javascript array and dict literals).
1322 /// var arr = [ 1, 2, 3 ]; vs. var arr = [1, 2, 3];
1323 /// f({a : 1, b : 2, c : 3}); f({a: 1, b: 2, c: 3});
1325 bool SpacesInContainerLiterals;
1327 /// \brief If ``true``, spaces may be inserted into C style casts.
1330 /// x = ( int32 )y vs. x = (int32)y
1332 bool SpacesInCStyleCastParentheses;
1334 /// \brief If ``true``, spaces will be inserted after ``(`` and before ``)``.
1337 /// t f( Deleted & ) & = delete; vs. t f(Deleted &) & = delete;
1339 bool SpacesInParentheses;
1341 /// \brief If ``true``, spaces will be inserted after ``[`` and before ``]``.
1342 /// Lambdas or unspecified size array declarations will not be affected.
1345 /// int a[ 5 ]; vs. int a[5];
1346 /// std::unique_ptr<int[]> foo() {} // Won't be affected
1348 bool SpacesInSquareBrackets;
1350 /// \brief Supported language standards.
1351 enum LanguageStandard {
1352 /// Use C++03-compatible syntax.
1354 /// Use features of C++11, C++14 and C++1z (e.g. ``A<A<int>>`` instead of
1355 /// ``A<A<int> >``).
1357 /// Automatic detection based on the input.
1361 /// \brief Format compatible with this standard, e.g. use ``A<A<int> >``
1362 /// instead of ``A<A<int>>`` for ``LS_Cpp03``.
1363 LanguageStandard Standard;
1365 /// \brief The number of columns used for tab stops.
1368 /// \brief Different ways to use tab in formatting.
1372 /// Use tabs only for indentation.
1374 /// Use tabs only for line continuation and indentation.
1375 UT_ForContinuationAndIndentation,
1376 /// Use tabs whenever we need to fill whitespace that spans at least from
1377 /// one tab stop to the next one.
1381 /// \brief The way to use tab characters in the resulting file.
1384 bool operator==(const FormatStyle &R) const {
1385 return AccessModifierOffset == R.AccessModifierOffset &&
1386 AlignAfterOpenBracket == R.AlignAfterOpenBracket &&
1387 AlignConsecutiveAssignments == R.AlignConsecutiveAssignments &&
1388 AlignConsecutiveDeclarations == R.AlignConsecutiveDeclarations &&
1389 AlignEscapedNewlines == R.AlignEscapedNewlines &&
1390 AlignOperands == R.AlignOperands &&
1391 AlignTrailingComments == R.AlignTrailingComments &&
1392 AllowAllParametersOfDeclarationOnNextLine ==
1393 R.AllowAllParametersOfDeclarationOnNextLine &&
1394 AllowShortBlocksOnASingleLine == R.AllowShortBlocksOnASingleLine &&
1395 AllowShortCaseLabelsOnASingleLine ==
1396 R.AllowShortCaseLabelsOnASingleLine &&
1397 AllowShortFunctionsOnASingleLine ==
1398 R.AllowShortFunctionsOnASingleLine &&
1399 AllowShortIfStatementsOnASingleLine ==
1400 R.AllowShortIfStatementsOnASingleLine &&
1401 AllowShortLoopsOnASingleLine == R.AllowShortLoopsOnASingleLine &&
1402 AlwaysBreakAfterReturnType == R.AlwaysBreakAfterReturnType &&
1403 AlwaysBreakBeforeMultilineStrings ==
1404 R.AlwaysBreakBeforeMultilineStrings &&
1405 AlwaysBreakTemplateDeclarations ==
1406 R.AlwaysBreakTemplateDeclarations &&
1407 BinPackArguments == R.BinPackArguments &&
1408 BinPackParameters == R.BinPackParameters &&
1409 BreakBeforeBinaryOperators == R.BreakBeforeBinaryOperators &&
1410 BreakBeforeBraces == R.BreakBeforeBraces &&
1411 BreakBeforeTernaryOperators == R.BreakBeforeTernaryOperators &&
1412 BreakConstructorInitializers == R.BreakConstructorInitializers &&
1413 BreakAfterJavaFieldAnnotations == R.BreakAfterJavaFieldAnnotations &&
1414 BreakStringLiterals == R.BreakStringLiterals &&
1415 ColumnLimit == R.ColumnLimit && CommentPragmas == R.CommentPragmas &&
1416 BreakBeforeInheritanceComma == R.BreakBeforeInheritanceComma &&
1417 ConstructorInitializerAllOnOneLineOrOnePerLine ==
1418 R.ConstructorInitializerAllOnOneLineOrOnePerLine &&
1419 ConstructorInitializerIndentWidth ==
1420 R.ConstructorInitializerIndentWidth &&
1421 ContinuationIndentWidth == R.ContinuationIndentWidth &&
1422 Cpp11BracedListStyle == R.Cpp11BracedListStyle &&
1423 DerivePointerAlignment == R.DerivePointerAlignment &&
1424 DisableFormat == R.DisableFormat &&
1425 ExperimentalAutoDetectBinPacking ==
1426 R.ExperimentalAutoDetectBinPacking &&
1427 FixNamespaceComments == R.FixNamespaceComments &&
1428 ForEachMacros == R.ForEachMacros &&
1429 IncludeCategories == R.IncludeCategories &&
1430 IndentCaseLabels == R.IndentCaseLabels &&
1431 IndentWidth == R.IndentWidth && Language == R.Language &&
1432 IndentWrappedFunctionNames == R.IndentWrappedFunctionNames &&
1433 JavaScriptQuotes == R.JavaScriptQuotes &&
1434 JavaScriptWrapImports == R.JavaScriptWrapImports &&
1435 KeepEmptyLinesAtTheStartOfBlocks ==
1436 R.KeepEmptyLinesAtTheStartOfBlocks &&
1437 MacroBlockBegin == R.MacroBlockBegin &&
1438 MacroBlockEnd == R.MacroBlockEnd &&
1439 MaxEmptyLinesToKeep == R.MaxEmptyLinesToKeep &&
1440 NamespaceIndentation == R.NamespaceIndentation &&
1441 ObjCBlockIndentWidth == R.ObjCBlockIndentWidth &&
1442 ObjCSpaceAfterProperty == R.ObjCSpaceAfterProperty &&
1443 ObjCSpaceBeforeProtocolList == R.ObjCSpaceBeforeProtocolList &&
1444 PenaltyBreakAssignment ==
1445 R.PenaltyBreakAssignment &&
1446 PenaltyBreakBeforeFirstCallParameter ==
1447 R.PenaltyBreakBeforeFirstCallParameter &&
1448 PenaltyBreakComment == R.PenaltyBreakComment &&
1449 PenaltyBreakFirstLessLess == R.PenaltyBreakFirstLessLess &&
1450 PenaltyBreakString == R.PenaltyBreakString &&
1451 PenaltyExcessCharacter == R.PenaltyExcessCharacter &&
1452 PenaltyReturnTypeOnItsOwnLine == R.PenaltyReturnTypeOnItsOwnLine &&
1453 PointerAlignment == R.PointerAlignment &&
1454 SpaceAfterCStyleCast == R.SpaceAfterCStyleCast &&
1455 SpaceAfterTemplateKeyword == R.SpaceAfterTemplateKeyword &&
1456 SpaceBeforeAssignmentOperators == R.SpaceBeforeAssignmentOperators &&
1457 SpaceBeforeParens == R.SpaceBeforeParens &&
1458 SpaceInEmptyParentheses == R.SpaceInEmptyParentheses &&
1459 SpacesBeforeTrailingComments == R.SpacesBeforeTrailingComments &&
1460 SpacesInAngles == R.SpacesInAngles &&
1461 SpacesInContainerLiterals == R.SpacesInContainerLiterals &&
1462 SpacesInCStyleCastParentheses == R.SpacesInCStyleCastParentheses &&
1463 SpacesInParentheses == R.SpacesInParentheses &&
1464 SpacesInSquareBrackets == R.SpacesInSquareBrackets &&
1465 Standard == R.Standard && TabWidth == R.TabWidth &&
1470 /// \brief Returns a format style complying with the LLVM coding standards:
1471 /// http://llvm.org/docs/CodingStandards.html.
1472 FormatStyle getLLVMStyle();
1474 /// \brief Returns a format style complying with one of Google's style guides:
1475 /// http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml.
1476 /// http://google-styleguide.googlecode.com/svn/trunk/javascriptguide.xml.
1477 /// https://developers.google.com/protocol-buffers/docs/style.
1478 FormatStyle getGoogleStyle(FormatStyle::LanguageKind Language);
1480 /// \brief Returns a format style complying with Chromium's style guide:
1481 /// http://www.chromium.org/developers/coding-style.
1482 FormatStyle getChromiumStyle(FormatStyle::LanguageKind Language);
1484 /// \brief Returns a format style complying with Mozilla's style guide:
1485 /// https://developer.mozilla.org/en-US/docs/Developer_Guide/Coding_Style.
1486 FormatStyle getMozillaStyle();
1488 /// \brief Returns a format style complying with Webkit's style guide:
1489 /// http://www.webkit.org/coding/coding-style.html
1490 FormatStyle getWebKitStyle();
1492 /// \brief Returns a format style complying with GNU Coding Standards:
1493 /// http://www.gnu.org/prep/standards/standards.html
1494 FormatStyle getGNUStyle();
1496 /// \brief Returns style indicating formatting should be not applied at all.
1497 FormatStyle getNoStyle();
1499 /// \brief Gets a predefined style for the specified language by name.
1501 /// Currently supported names: LLVM, Google, Chromium, Mozilla. Names are
1502 /// compared case-insensitively.
1504 /// Returns ``true`` if the Style has been set.
1505 bool getPredefinedStyle(StringRef Name, FormatStyle::LanguageKind Language,
1506 FormatStyle *Style);
1508 /// \brief Parse configuration from YAML-formatted text.
1510 /// Style->Language is used to get the base style, if the ``BasedOnStyle``
1511 /// option is present.
1513 /// When ``BasedOnStyle`` is not present, options not present in the YAML
1514 /// document, are retained in \p Style.
1515 std::error_code parseConfiguration(StringRef Text, FormatStyle *Style);
1517 /// \brief Gets configuration in a YAML string.
1518 std::string configurationAsText(const FormatStyle &Style);
1520 /// \brief Returns the replacements necessary to sort all ``#include`` blocks
1521 /// that are affected by ``Ranges``.
1522 tooling::Replacements sortIncludes(const FormatStyle &Style, StringRef Code,
1523 ArrayRef<tooling::Range> Ranges,
1525 unsigned *Cursor = nullptr);
1527 /// \brief Returns the replacements corresponding to applying and formatting
1528 /// \p Replaces on success; otheriwse, return an llvm::Error carrying
1529 /// llvm::StringError.
1530 llvm::Expected<tooling::Replacements>
1531 formatReplacements(StringRef Code, const tooling::Replacements &Replaces,
1532 const FormatStyle &Style);
1534 /// \brief Returns the replacements corresponding to applying \p Replaces and
1535 /// cleaning up the code after that on success; otherwise, return an llvm::Error
1536 /// carrying llvm::StringError.
1537 /// This also supports inserting/deleting C++ #include directives:
1538 /// - If a replacement has offset UINT_MAX, length 0, and a replacement text
1539 /// that is an #include directive, this will insert the #include into the
1540 /// correct block in the \p Code. When searching for points to insert new
1541 /// header, this ignores #include's after the #include block(s) in the
1542 /// beginning of a file to avoid inserting headers into code sections where
1543 /// new #include's should not be added by default. These code sections
1545 /// - raw string literals (containing #include).
1547 /// - Special #include's among declarations (e.g. functions).
1548 /// - If a replacement has offset UINT_MAX, length 1, and a replacement text
1549 /// that is the name of the header to be removed, the header will be removed
1550 /// from \p Code if it exists.
1551 llvm::Expected<tooling::Replacements>
1552 cleanupAroundReplacements(StringRef Code, const tooling::Replacements &Replaces,
1553 const FormatStyle &Style);
1555 /// \brief Represents the status of a formatting attempt.
1556 struct FormattingAttemptStatus {
1557 /// \brief A value of ``false`` means that any of the affected ranges were not
1558 /// formatted due to a non-recoverable syntax error.
1559 bool FormatComplete = true;
1561 /// \brief If ``FormatComplete`` is false, ``Line`` records a one-based
1562 /// original line number at which a syntax error might have occurred. This is
1563 /// based on a best-effort analysis and could be imprecise.
1567 /// \brief Reformats the given \p Ranges in \p Code.
1569 /// Each range is extended on either end to its next bigger logic unit, i.e.
1570 /// everything that might influence its formatting or might be influenced by its
1573 /// Returns the ``Replacements`` necessary to make all \p Ranges comply with
1576 /// If ``Status`` is non-null, its value will be populated with the status of
1577 /// this formatting attempt. See \c FormattingAttemptStatus.
1578 tooling::Replacements reformat(const FormatStyle &Style, StringRef Code,
1579 ArrayRef<tooling::Range> Ranges,
1580 StringRef FileName = "<stdin>",
1581 FormattingAttemptStatus *Status = nullptr);
1583 /// \brief Same as above, except if ``IncompleteFormat`` is non-null, its value
1584 /// will be set to true if any of the affected ranges were not formatted due to
1585 /// a non-recoverable syntax error.
1586 tooling::Replacements reformat(const FormatStyle &Style, StringRef Code,
1587 ArrayRef<tooling::Range> Ranges,
1589 bool *IncompleteFormat);
1591 /// \brief Clean up any erroneous/redundant code in the given \p Ranges in \p
1594 /// Returns the ``Replacements`` that clean up all \p Ranges in \p Code.
1595 tooling::Replacements cleanup(const FormatStyle &Style, StringRef Code,
1596 ArrayRef<tooling::Range> Ranges,
1597 StringRef FileName = "<stdin>");
1599 /// \brief Fix namespace end comments in the given \p Ranges in \p Code.
1601 /// Returns the ``Replacements`` that fix the namespace comments in all
1602 /// \p Ranges in \p Code.
1603 tooling::Replacements fixNamespaceEndComments(const FormatStyle &Style,
1605 ArrayRef<tooling::Range> Ranges,
1606 StringRef FileName = "<stdin>");
1608 /// \brief Returns the ``LangOpts`` that the formatter expects you to set.
1610 /// \param Style determines specific settings for lexing mode.
1611 LangOptions getFormattingLangOpts(const FormatStyle &Style = getLLVMStyle());
1613 /// \brief Description to be used for help text for a ``llvm::cl`` option for
1614 /// specifying format style. The description is closely related to the operation
1615 /// of ``getStyle()``.
1616 extern const char *StyleOptionHelpDescription;
1618 /// \brief Construct a FormatStyle based on ``StyleName``.
1620 /// ``StyleName`` can take several forms:
1621 /// * "{<key>: <value>, ...}" - Set specic style parameters.
1622 /// * "<style name>" - One of the style names supported by
1623 /// getPredefinedStyle().
1624 /// * "file" - Load style configuration from a file called ``.clang-format``
1625 /// located in one of the parent directories of ``FileName`` or the current
1626 /// directory if ``FileName`` is empty.
1628 /// \param[in] StyleName Style name to interpret according to the description
1630 /// \param[in] FileName Path to start search for .clang-format if ``StyleName``
1632 /// \param[in] FallbackStyle The name of a predefined style used to fallback to
1633 /// in case \p StyleName is "file" and no file can be found.
1634 /// \param[in] Code The actual code to be formatted. Used to determine the
1635 /// language if the filename isn't sufficient.
1636 /// \param[in] FS The underlying file system, in which the file resides. By
1637 /// default, the file system is the real file system.
1639 /// \returns FormatStyle as specified by ``StyleName``. If ``StyleName`` is
1640 /// "file" and no file is found, returns ``FallbackStyle``. If no style could be
1641 /// determined, returns an Error.
1642 llvm::Expected<FormatStyle> getStyle(StringRef StyleName, StringRef FileName,
1643 StringRef FallbackStyle,
1644 StringRef Code = "",
1645 vfs::FileSystem *FS = nullptr);
1647 // \brief Returns a string representation of ``Language``.
1648 inline StringRef getLanguageName(FormatStyle::LanguageKind Language) {
1650 case FormatStyle::LK_Cpp:
1652 case FormatStyle::LK_ObjC:
1653 return "Objective-C";
1654 case FormatStyle::LK_Java:
1656 case FormatStyle::LK_JavaScript:
1657 return "JavaScript";
1658 case FormatStyle::LK_Proto:
1665 } // end namespace format
1666 } // end namespace clang
1670 struct is_error_code_enum<clang::format::ParseError> : std::true_type {};
1673 #endif // LLVM_CLANG_FORMAT_FORMAT_H