1 //===--- Format.h - Format C++ code -----------------------------*- C++ -*-===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
10 /// Various functions to configurably format source code.
12 //===----------------------------------------------------------------------===//
14 #ifndef LLVM_CLANG_FORMAT_FORMAT_H
15 #define LLVM_CLANG_FORMAT_FORMAT_H
17 #include "clang/Basic/LangOptions.h"
18 #include "clang/Tooling/Core/Replacement.h"
19 #include "clang/Tooling/Inclusions/IncludeStyle.h"
20 #include "llvm/ADT/ArrayRef.h"
21 #include "llvm/Support/Regex.h"
22 #include <system_error>
34 class DiagnosticConsumer;
38 enum class ParseError { Success = 0, Error, Unsuitable };
39 class ParseErrorCategory final : public std::error_category {
41 const char *name() const noexcept override;
42 std::string message(int EV) const override;
44 const std::error_category &getParseCategory();
45 std::error_code make_error_code(ParseError e);
47 /// The ``FormatStyle`` is used to configure the formatting to follow
48 /// specific guidelines.
50 /// The extra indent or outdent of access modifiers, e.g. ``public:``.
51 int AccessModifierOffset;
53 /// Different styles for aligning after open brackets.
54 enum BracketAlignmentStyle {
55 /// Align parameters on the open bracket, e.g.:
57 /// someLongFunction(argument1,
61 /// Don't align, instead use ``ContinuationIndentWidth``, e.g.:
63 /// someLongFunction(argument1,
67 /// Always break after an open bracket, if the parameters don't fit
68 /// on a single line, e.g.:
71 /// argument1, argument2);
76 /// If ``true``, horizontally aligns arguments after an open bracket.
78 /// This applies to round brackets (parentheses), angle brackets and square
80 BracketAlignmentStyle AlignAfterOpenBracket;
82 /// \brief If ``true``, aligns consecutive C/C++ preprocessor macros.
84 /// This will align C/C++ preprocessor macros of consecutive lines.
85 /// Will result in formattings like
87 /// #define SHORT_NAME 42
88 /// #define LONGER_NAME 0x007f
89 /// #define EVEN_LONGER_NAME (2)
90 /// #define foo(x) (x * x)
91 /// #define bar(y, z) (y + z)
93 bool AlignConsecutiveMacros;
95 /// If ``true``, aligns consecutive assignments.
97 /// This will align the assignment operators of consecutive lines. This
98 /// will result in formattings like
104 bool AlignConsecutiveAssignments;
106 /// If ``true``, aligns consecutive declarations.
108 /// This will align the declaration names of consecutive lines. This
109 /// will result in formattings like
113 /// std::string ccc = 23;
115 bool AlignConsecutiveDeclarations;
117 /// Different styles for aligning escaped newlines.
118 enum EscapedNewlineAlignmentStyle {
119 /// Don't align escaped newlines.
127 /// Align escaped newlines as far left as possible.
138 /// Align escaped newlines in the right-most column.
148 /// Options for aligning backslashes in escaped newlines.
149 EscapedNewlineAlignmentStyle AlignEscapedNewlines;
151 /// If ``true``, horizontally align operands of binary and ternary
154 /// Specifically, this aligns operands of a single expression that needs to be
155 /// split over multiple lines, e.g.:
157 /// int aaa = bbbbbbbbbbbbbbb +
162 /// If ``true``, aligns trailing comments.
165 /// int a; // My comment a vs. int a; // My comment a
166 /// int b = 2; // comment b int b = 2; // comment about b
168 bool AlignTrailingComments;
170 /// \brief If a function call or braced initializer list doesn't fit on a
171 /// line, allow putting all arguments onto the next line, even if
172 /// ``BinPackArguments`` is ``false``.
184 bool AllowAllArgumentsOnNextLine;
186 /// \brief If a constructor definition with a member initializer list doesn't
187 /// fit on a single line, allow putting all member initializers onto the next
188 /// line, if ```ConstructorInitializerAllOnOneLineOrOnePerLine``` is true.
189 /// Note that this parameter has no effect if
190 /// ```ConstructorInitializerAllOnOneLineOrOnePerLine``` is false.
193 /// MyClass::MyClass() :
194 /// member0(0), member1(2) {}
197 /// MyClass::MyClass() :
200 bool AllowAllConstructorInitializersOnNextLine;
202 /// If the function declaration doesn't fit on a line,
203 /// allow putting all parameters of a function declaration onto
204 /// the next line even if ``BinPackParameters`` is ``false``.
208 /// int a, int b, int c, int d, int e);
211 /// void myFunction(int a,
217 bool AllowAllParametersOfDeclarationOnNextLine;
219 /// Different styles for merging short blocks containing at most one
221 enum ShortBlockStyle {
222 /// Never merge blocks into a single line.
231 /// Only merge empty blocks.
239 /// Always merge short blocks into a single line.
242 /// while (true) { continue; }
247 /// Dependent on the value, ``while (true) { continue; }`` can be put on a
249 ShortBlockStyle AllowShortBlocksOnASingleLine;
251 /// If ``true``, short case labels will be contracted to a single line.
254 /// switch (a) { vs. switch (a) {
255 /// case 1: x = 1; break; case 1:
256 /// case 2: return; x = 1;
262 bool AllowShortCaseLabelsOnASingleLine;
264 /// Different styles for merging short functions containing at most one
266 enum ShortFunctionStyle {
267 /// Never merge functions into a single line.
269 /// Only merge functions defined inside a class. Same as "inline",
270 /// except it does not implies "empty": i.e. top level empty functions
271 /// are not merged either.
274 /// void f() { foo(); }
283 /// Only merge empty functions.
291 /// Only merge functions defined inside a class. Implies "empty".
294 /// void f() { foo(); }
302 /// Merge all functions fitting on a single line.
305 /// void f() { foo(); }
307 /// void f() { bar(); }
312 /// Dependent on the value, ``int f() { return 0; }`` can be put on a
314 ShortFunctionStyle AllowShortFunctionsOnASingleLine;
316 /// Different styles for handling short if lines
318 /// Never put short ifs on the same line.
327 /// Without else put short ifs on the same line only if
328 /// the else is not a compound statement.
335 /// Always put short ifs on the same line if
336 /// the else is not a compound statement or not.
346 /// If ``true``, ``if (a) return;`` can be put on a single line.
347 ShortIfStyle AllowShortIfStatementsOnASingleLine;
349 /// Different styles for merging short lambdas containing at most one
351 enum ShortLambdaStyle {
352 /// Never merge lambdas into a single line.
354 /// Only merge empty lambdas.
356 /// auto lambda = [](int a) {}
357 /// auto lambda2 = [](int a) {
362 /// Merge lambda into a single line if argument of a function.
364 /// auto lambda = [](int a) {
367 /// sort(a.begin(), a.end(), ()[] { return x < y; })
370 /// Merge all lambdas fitting on a single line.
372 /// auto lambda = [](int a) {}
373 /// auto lambda2 = [](int a) { return a; };
378 /// Dependent on the value, ``auto lambda []() { return 0; }`` can be put on a
380 ShortLambdaStyle AllowShortLambdasOnASingleLine;
382 /// If ``true``, ``while (true) continue;`` can be put on a single
384 bool AllowShortLoopsOnASingleLine;
386 /// Different ways to break after the function definition return type.
387 /// This option is **deprecated** and is retained for backwards compatibility.
388 enum DefinitionReturnTypeBreakingStyle {
389 /// Break after return type automatically.
390 /// ``PenaltyReturnTypeOnItsOwnLine`` is taken into account.
392 /// Always break after the return type.
394 /// Always break after the return types of top-level functions.
398 /// Different ways to break after the function definition or
399 /// declaration return type.
400 enum ReturnTypeBreakingStyle {
401 /// Break after return type automatically.
402 /// ``PenaltyReturnTypeOnItsOwnLine`` is taken into account.
405 /// int f() { return 0; };
408 /// int f() { return 1; }
411 /// Always break after the return type.
427 /// Always break after the return types of top-level functions.
430 /// int f() { return 0; };
440 /// Always break after the return type of function definitions.
455 /// Always break after the return type of top-level definitions.
458 /// int f() { return 0; };
466 RTBS_TopLevelDefinitions,
469 /// The function definition return type breaking style to use. This
470 /// option is **deprecated** and is retained for backwards compatibility.
471 DefinitionReturnTypeBreakingStyle AlwaysBreakAfterDefinitionReturnType;
473 /// The function declaration return type breaking style to use.
474 ReturnTypeBreakingStyle AlwaysBreakAfterReturnType;
476 /// If ``true``, always break before multiline string literals.
478 /// This flag is mean to make cases where there are multiple multiline strings
479 /// in a file look more consistent. Thus, it will only take effect if wrapping
480 /// the string at that point leads to it being indented
481 /// ``ContinuationIndentWidth`` spaces from the start of the line.
484 /// aaaa = vs. aaaa = "bbbb"
488 bool AlwaysBreakBeforeMultilineStrings;
490 /// Different ways to break after the template declaration.
491 enum BreakTemplateDeclarationsStyle {
492 /// Do not force break before declaration.
493 /// ``PenaltyBreakTemplateDeclaration`` is taken into account.
495 /// template <typename T> T foo() {
497 /// template <typename T> T foo(int aaaaaaaaaaaaaaaaaaaaa,
498 /// int bbbbbbbbbbbbbbbbbbbbb) {
502 /// Force break after template declaration only when the following
503 /// declaration spans multiple lines.
505 /// template <typename T> T foo() {
507 /// template <typename T>
508 /// T foo(int aaaaaaaaaaaaaaaaaaaaa,
509 /// int bbbbbbbbbbbbbbbbbbbbb) {
513 /// Always break after template declaration.
515 /// template <typename T>
518 /// template <typename T>
519 /// T foo(int aaaaaaaaaaaaaaaaaaaaa,
520 /// int bbbbbbbbbbbbbbbbbbbbb) {
526 /// The template declaration breaking style to use.
527 BreakTemplateDeclarationsStyle AlwaysBreakTemplateDeclarations;
529 /// If ``false``, a function call's arguments will either be all on the
530 /// same line or will have one line each.
534 /// f(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaa,
535 /// aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);
540 /// f(aaaaaaaaaaaaaaaaaaaa,
541 /// aaaaaaaaaaaaaaaaaaaa,
542 /// aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);
545 bool BinPackArguments;
547 /// If ``false``, a function declaration's or function definition's
548 /// parameters will either all be on the same line or will have one line each.
551 /// void f(int aaaaaaaaaaaaaaaaaaaa, int aaaaaaaaaaaaaaaaaaaa,
552 /// int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}
555 /// void f(int aaaaaaaaaaaaaaaaaaaa,
556 /// int aaaaaaaaaaaaaaaaaaaa,
557 /// int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}
559 bool BinPackParameters;
561 /// The style of wrapping parameters on the same line (bin-packed) or
562 /// on one line each.
564 /// Automatically determine parameter bin-packing behavior.
566 /// Always bin-pack parameters.
568 /// Never bin-pack parameters.
572 /// The style of breaking before or after binary operators.
573 enum BinaryOperatorStyle {
574 /// Break after operators.
576 /// LooooooooooongType loooooooooooooooooooooongVariable =
577 /// someLooooooooooooooooongFunction();
579 /// bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +
580 /// aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==
581 /// aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa &&
582 /// aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >
583 /// ccccccccccccccccccccccccccccccccccccccccc;
586 /// Break before operators that aren't assignments.
588 /// LooooooooooongType loooooooooooooooooooooongVariable =
589 /// someLooooooooooooooooongFunction();
591 /// bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
592 /// + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
593 /// == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
594 /// && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
595 /// > ccccccccccccccccccccccccccccccccccccccccc;
598 /// Break before operators.
600 /// LooooooooooongType loooooooooooooooooooooongVariable
601 /// = someLooooooooooooooooongFunction();
603 /// bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
604 /// + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
605 /// == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
606 /// && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
607 /// > ccccccccccccccccccccccccccccccccccccccccc;
612 /// The way to wrap binary operators.
613 BinaryOperatorStyle BreakBeforeBinaryOperators;
615 /// Different ways to attach braces to their surrounding context.
616 enum BraceBreakingStyle {
617 /// Always attach braces to surrounding context.
623 /// void foo() { bar(); }
628 /// enum X : int { A, B };
631 /// Like ``Attach``, but break before braces on function, namespace and
632 /// class definitions.
638 /// void foo() { bar(); }
645 /// enum X : int { A, B };
648 /// Like ``Attach``, but break before braces on enum, function, and record
655 /// void foo() { bar(); }
662 /// enum X : int { A, B };
665 /// Like ``Attach``, but break before function definitions, ``catch``, and
673 /// void foo() { bar(); }
680 /// enum X : int { A, B };
683 /// Always break before braces.
692 /// void foo() { bar(); }
709 /// Like ``Allman`` but always indent braces and line up code with braces.
718 /// void foo() { bar(); }
735 /// Always break before braces and add an extra level of indentation to
736 /// braces of control statements, not to those of class, function
737 /// or other definitions.
746 /// void foo() { bar(); }
763 /// Like ``Attach``, but break before functions.
769 /// void foo() { bar(); }
775 /// enum X : int { A, B };
778 /// Configure each individual brace in `BraceWrapping`.
782 /// The brace breaking style to use.
783 BraceBreakingStyle BreakBeforeBraces;
785 /// Different ways to wrap braces after control statements.
786 enum BraceWrappingAfterControlStatementStyle {
787 /// Never wrap braces after a control statement.
792 /// for (int i = 0; i < 10; ++i) {
796 /// Only wrap braces after a multi-line control statement.
798 /// if (foo && bar &&
803 /// while (foo || bar) {
807 /// Always wrap braces after a control statement.
813 /// for (int i = 0; i < 10; ++i)
819 /// Precise control over the wrapping of braces.
821 /// # Should be declared this way:
822 /// BreakBeforeBraces: Custom
826 struct BraceWrappingFlags {
827 /// Wrap case labels.
830 /// switch (foo) { vs. switch (foo) {
831 /// case 1: { case 1:
843 /// Wrap class definitions.
854 /// Wrap control statements (``if``/``for``/``while``/``switch``/..).
855 BraceWrappingAfterControlStatementStyle AfterControlStatement;
856 /// Wrap enum definitions.
865 /// enum X : int { B };
868 /// Wrap function definitions.
884 /// Wrap namespace definitions.
900 /// Wrap ObjC definitions (interfaces, implementations...).
901 /// \note @autoreleasepool and @synchronized blocks are wrapped
902 /// according to `AfterControlStatement` flag.
903 bool AfterObjCDeclaration;
904 /// Wrap struct definitions.
918 /// Wrap union definitions.
932 /// Wrap extern blocks.
945 bool AfterExternBlock;
946 /// Wrap before ``catch``.
962 /// Wrap before ``else``.
976 /// Indent the wrapped braces themselves.
978 /// If ``false``, empty function body can be put on a single line.
979 /// This option is used only if the opening brace of the function has
980 /// already been wrapped, i.e. the `AfterFunction` brace wrapping mode is
981 /// set, and the function could/should not be put on a single line (as per
982 /// `AllowShortFunctionsOnASingleLine` and constructor formatting options).
984 /// int f() vs. int f()
989 bool SplitEmptyFunction;
990 /// If ``false``, empty record (e.g. class, struct or union) body
991 /// can be put on a single line. This option is used only if the opening
992 /// brace of the record has already been wrapped, i.e. the `AfterClass`
993 /// (for classes) brace wrapping mode is set.
995 /// class Foo vs. class Foo
1000 bool SplitEmptyRecord;
1001 /// If ``false``, empty namespace body can be put on a single line.
1002 /// This option is used only if the opening brace of the namespace has
1003 /// already been wrapped, i.e. the `AfterNamespace` brace wrapping mode is
1006 /// namespace Foo vs. namespace Foo
1011 bool SplitEmptyNamespace;
1014 /// Control of individual brace wrapping cases.
1016 /// If ``BreakBeforeBraces`` is set to ``BS_Custom``, use this to specify how
1017 /// each individual brace case should be handled. Otherwise, this is ignored.
1019 /// # Example of usage:
1020 /// BreakBeforeBraces: Custom
1023 /// AfterStruct: false
1024 /// SplitEmptyFunction: false
1026 BraceWrappingFlags BraceWrapping;
1028 /// If ``true``, ternary operators will be placed after line breaks.
1031 /// veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongDescription
1033 /// : SecondValueVeryVeryVeryVeryLong;
1036 /// veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongDescription ?
1038 /// SecondValueVeryVeryVeryVeryLong;
1040 bool BreakBeforeTernaryOperators;
1042 /// Different ways to break initializers.
1043 enum BreakConstructorInitializersStyle {
1044 /// Break constructor initializers before the colon and after the commas.
1047 /// : initializer1(),
1051 /// Break constructor initializers before the colon and commas, and align
1052 /// the commas with the colon.
1055 /// : initializer1()
1056 /// , initializer2()
1059 /// Break constructor initializers after the colon and commas.
1068 /// The constructor initializers style to use.
1069 BreakConstructorInitializersStyle BreakConstructorInitializers;
1071 /// Break after each annotation on a field in Java files.
1074 /// @Partial vs. @Partial @Mock DataLoad loader;
1076 /// DataLoad loader;
1078 bool BreakAfterJavaFieldAnnotations;
1080 /// Allow breaking string literals when formatting.
1083 /// const char* x = "veryVeryVeryVeryVeryVe"
1084 /// "ryVeryVeryVeryVeryVery"
1085 /// "VeryLongString";
1089 /// "veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongString";
1091 bool BreakStringLiterals;
1093 /// The column limit.
1095 /// A column limit of ``0`` means that there is no column limit. In this case,
1096 /// clang-format will respect the input's line breaking decisions within
1097 /// statements unless they contradict other rules.
1098 unsigned ColumnLimit;
1100 /// A regular expression that describes comments with special meaning,
1101 /// which should not be split into lines or otherwise changed.
1103 /// // CommentPragmas: '^ FOOBAR pragma:'
1104 /// // Will leave the following line unaffected
1105 /// #include <vector> // FOOBAR pragma: keep
1107 std::string CommentPragmas;
1109 /// Different ways to break inheritance list.
1110 enum BreakInheritanceListStyle {
1111 /// Break inheritance list before the colon and after the commas.
1119 /// Break inheritance list before the colon and commas, and align
1120 /// the commas with the colon.
1128 /// Break inheritance list after the colon and commas.
1138 /// The inheritance list style to use.
1139 BreakInheritanceListStyle BreakInheritanceList;
1141 /// If ``true``, consecutive namespace declarations will be on the same
1142 /// line. If ``false``, each namespace is declared on a new line.
1145 /// namespace Foo { namespace Bar {
1155 /// If it does not fit on a single line, the overflowing namespaces get
1158 /// namespace Foo { namespace Bar {
1159 /// namespace Extra {
1162 bool CompactNamespaces;
1165 /// If the constructor initializers don't fit on a line, put each
1166 /// initializer on its own line.
1169 /// SomeClass::Constructor()
1170 /// : aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa) {
1175 /// SomeClass::Constructor()
1176 /// : aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaa),
1177 /// aaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa) {
1181 bool ConstructorInitializerAllOnOneLineOrOnePerLine;
1184 /// The number of characters to use for indentation of constructor
1185 /// initializer lists as well as inheritance lists.
1186 unsigned ConstructorInitializerIndentWidth;
1188 /// Indent width for line continuations.
1190 /// ContinuationIndentWidth: 2
1192 /// int i = // VeryVeryVeryVeryVeryLongComment
1193 /// longFunction( // Again a long comment
1196 unsigned ContinuationIndentWidth;
1198 /// If ``true``, format braced lists as best suited for C++11 braced
1201 /// Important differences:
1202 /// - No spaces inside the braced list.
1203 /// - No line break before the closing brace.
1204 /// - Indentation with the continuation indent, not with the block indent.
1206 /// Fundamentally, C++11 braced lists are formatted exactly like function
1207 /// calls would be formatted in their place. If the braced list follows a name
1208 /// (e.g. a type or variable name), clang-format formats as if the ``{}`` were
1209 /// the parentheses of a function call with that name. If there is no name,
1210 /// a zero-length name is assumed.
1213 /// vector<int> x{1, 2, 3, 4}; vs. vector<int> x{ 1, 2, 3, 4 };
1214 /// vector<T> x{{}, {}, {}, {}}; vector<T> x{ {}, {}, {}, {} };
1215 /// f(MyMap[{composite, key}]); f(MyMap[{ composite, key }]);
1216 /// new int[3]{1, 2, 3}; new int[3]{ 1, 2, 3 };
1218 bool Cpp11BracedListStyle;
1220 /// \brief Analyze the formatted file for the most used line ending (``\r\n``
1221 /// or ``\n``). ``UseCRLF`` is only used as a fallback if none can be derived.
1222 bool DeriveLineEnding;
1224 /// If ``true``, analyze the formatted file for the most common
1225 /// alignment of ``&`` and ``*``.
1226 /// Pointer and reference alignment styles are going to be updated according
1227 /// to the preferences found in the file.
1228 /// ``PointerAlignment`` is then used only as fallback.
1229 bool DerivePointerAlignment;
1231 /// Disables formatting completely.
1234 /// If ``true``, clang-format detects whether function calls and
1235 /// definitions are formatted with one parameter per line.
1237 /// Each call can be bin-packed, one-per-line or inconclusive. If it is
1238 /// inconclusive, e.g. completely on one line, but a decision needs to be
1239 /// made, clang-format analyzes whether there are other bin-packed cases in
1240 /// the input file and act accordingly.
1242 /// NOTE: This is an experimental flag, that might go away or be renamed. Do
1243 /// not use this in config files, etc. Use at your own risk.
1244 bool ExperimentalAutoDetectBinPacking;
1246 /// If ``true``, clang-format adds missing namespace end comments and
1247 /// fixes invalid existing ones.
1250 /// namespace a { vs. namespace a {
1252 /// } // namespace a }
1254 bool FixNamespaceComments;
1256 /// A vector of macros that should be interpreted as foreach loops
1257 /// instead of as function calls.
1259 /// These are expected to be macros of the form:
1261 /// FOREACH(<variable-declaration>, ...)
1265 /// In the .clang-format configuration file, this can be configured like:
1267 /// ForEachMacros: ['RANGES_FOR', 'FOREACH']
1270 /// For example: BOOST_FOREACH.
1271 std::vector<std::string> ForEachMacros;
1273 /// \brief A vector of macros that should be interpreted as type declarations
1274 /// instead of as function calls.
1276 /// These are expected to be macros of the form:
1281 /// In the .clang-format configuration file, this can be configured like:
1283 /// TypenameMacros: ['STACK_OF', 'LIST']
1286 /// For example: OpenSSL STACK_OF, BSD LIST_ENTRY.
1287 std::vector<std::string> TypenameMacros;
1289 /// A vector of macros that should be interpreted as complete
1292 /// Typical macros are expressions, and require a semi-colon to be
1293 /// added; sometimes this is not the case, and this allows to make
1294 /// clang-format aware of such cases.
1296 /// For example: Q_UNUSED
1297 std::vector<std::string> StatementMacros;
1299 /// A vector of macros which are used to open namespace blocks.
1301 /// These are expected to be macros of the form:
1303 /// NAMESPACE(<namespace-name>, ...) {
1304 /// <namespace-content>
1308 /// For example: TESTSUITE
1309 std::vector<std::string> NamespaceMacros;
1311 tooling::IncludeStyle IncludeStyle;
1313 /// Indent case labels one level from the switch statement.
1315 /// When ``false``, use the same indentation level as for the switch
1316 /// statement. Switch statement body is always indented one level more than
1320 /// switch (fool) { vs. switch (fool) {
1324 /// default: default:
1328 bool IndentCaseLabels;
1330 /// Indent goto labels.
1332 /// When ``false``, goto labels are flushed left.
1335 /// int f() { vs. int f() {
1336 /// if (foo()) { if (foo()) {
1341 /// return 1; return 1;
1344 bool IndentGotoLabels;
1346 /// Options for indenting preprocessor directives.
1347 enum PPDirectiveIndentStyle {
1348 /// Does not indent any directives.
1357 /// Indents directives after the hash.
1366 /// Indents directives before the hash.
1377 /// The preprocessor directive indenting style to use.
1378 PPDirectiveIndentStyle IndentPPDirectives;
1380 /// The number of columns to use for indentation.
1386 /// if (true, false) {
1391 unsigned IndentWidth;
1393 /// Indent if a function definition or declaration is wrapped after the
1397 /// LoooooooooooooooooooooooooooooooooooooooongReturnType
1398 /// LoooooooooooooooooooooooooooooooongFunctionDeclaration();
1401 /// LoooooooooooooooooooooooooooooooooooooooongReturnType
1402 /// LoooooooooooooooooooooooooooooooongFunctionDeclaration();
1404 bool IndentWrappedFunctionNames;
1406 /// A vector of prefixes ordered by the desired groups for Java imports.
1408 /// Each group is separated by a newline. Static imports will also follow the
1409 /// same grouping convention above all non-static imports. One group's prefix
1410 /// can be a subset of another - the longest prefix is always matched. Within
1411 /// a group, the imports are ordered lexicographically.
1413 /// In the .clang-format configuration file, this can be configured like
1414 /// in the following yaml example. This will result in imports being
1415 /// formatted as in the Java example below.
1417 /// JavaImportGroups: ['com.example', 'com', 'org']
1421 /// import static com.example.function1;
1423 /// import static com.test.function2;
1425 /// import static org.example.function3;
1427 /// import com.example.ClassA;
1428 /// import com.example.Test;
1429 /// import com.example.a.ClassB;
1431 /// import com.test.ClassC;
1433 /// import org.example.ClassD;
1435 std::vector<std::string> JavaImportGroups;
1437 /// Quotation styles for JavaScript strings. Does not affect template
1439 enum JavaScriptQuoteStyle {
1440 /// Leave string quotes as they are.
1442 /// string1 = "foo";
1443 /// string2 = 'bar';
1446 /// Always use single quotes.
1448 /// string1 = 'foo';
1449 /// string2 = 'bar';
1452 /// Always use double quotes.
1454 /// string1 = "foo";
1455 /// string2 = "bar";
1460 /// The JavaScriptQuoteStyle to use for JavaScript strings.
1461 JavaScriptQuoteStyle JavaScriptQuotes;
1464 /// Whether to wrap JavaScript import/export statements.
1468 /// VeryLongImportsAreAnnoying,
1469 /// VeryLongImportsAreAnnoying,
1470 /// VeryLongImportsAreAnnoying,
1471 /// } from 'some/module.js'
1474 /// import {VeryLongImportsAreAnnoying, VeryLongImportsAreAnnoying, VeryLongImportsAreAnnoying,} from "some/module.js"
1476 bool JavaScriptWrapImports;
1479 /// If true, the empty line at the start of blocks is kept.
1482 /// if (foo) { vs. if (foo) {
1487 bool KeepEmptyLinesAtTheStartOfBlocks;
1489 /// Supported languages.
1491 /// When stored in a configuration file, specifies the language, that the
1492 /// configuration targets. When passed to the ``reformat()`` function, enables
1493 /// syntax features specific to the language.
1497 /// Should be used for C, C++.
1499 /// Should be used for C#.
1501 /// Should be used for Java.
1503 /// Should be used for JavaScript.
1505 /// Should be used for Objective-C, Objective-C++.
1507 /// Should be used for Protocol Buffers
1508 /// (https://developers.google.com/protocol-buffers/).
1510 /// Should be used for TableGen code.
1512 /// Should be used for Protocol Buffer messages in text format
1513 /// (https://developers.google.com/protocol-buffers/).
1516 bool isCpp() const { return Language == LK_Cpp || Language == LK_ObjC; }
1517 bool isCSharp() const { return Language == LK_CSharp; }
1519 /// Language, this format style is targeted at.
1520 LanguageKind Language;
1522 /// A regular expression matching macros that start a block.
1525 /// MacroBlockBegin: "^NS_MAP_BEGIN|\
1527 /// MacroBlockEnd: "^\
1529 /// NS_TABLE_.*_END$"
1537 /// NS_TABLE_FOO_END
1546 /// NS_TABLE_FOO_END
1548 std::string MacroBlockBegin;
1550 /// A regular expression matching macros that end a block.
1551 std::string MacroBlockEnd;
1553 /// The maximum number of consecutive empty lines to keep.
1555 /// MaxEmptyLinesToKeep: 1 vs. MaxEmptyLinesToKeep: 0
1556 /// int f() { int f() {
1557 /// int = 1; int i = 1;
1559 /// i = foo(); return i;
1564 unsigned MaxEmptyLinesToKeep;
1566 /// Different ways to indent namespace contents.
1567 enum NamespaceIndentationKind {
1568 /// Don't indent in namespaces.
1578 /// Indent only in inner namespaces (nested in other namespaces).
1588 /// Indent in all namespaces.
1600 /// The indentation used for namespaces.
1601 NamespaceIndentationKind NamespaceIndentation;
1603 /// Controls bin-packing Objective-C protocol conformance list
1604 /// items into as few lines as possible when they go over ``ColumnLimit``.
1606 /// If ``Auto`` (the default), delegates to the value in
1607 /// ``BinPackParameters``. If that is ``true``, bin-packs Objective-C
1608 /// protocol conformance list items into as few lines as possible
1609 /// whenever they go over ``ColumnLimit``.
1611 /// If ``Always``, always bin-packs Objective-C protocol conformance
1612 /// list items into as few lines as possible whenever they go over
1613 /// ``ColumnLimit``.
1615 /// If ``Never``, lays out Objective-C protocol conformance list items
1616 /// onto individual lines whenever they go over ``ColumnLimit``.
1619 /// Always (or Auto, if BinPackParameters=true):
1620 /// @interface ccccccccccccc () <
1621 /// ccccccccccccc, ccccccccccccc,
1622 /// ccccccccccccc, ccccccccccccc> {
1625 /// Never (or Auto, if BinPackParameters=false):
1626 /// @interface ddddddddddddd () <
1630 /// ddddddddddddd> {
1633 BinPackStyle ObjCBinPackProtocolList;
1635 /// The number of characters to use for indentation of ObjC blocks.
1637 /// ObjCBlockIndentWidth: 4
1639 /// [operation setCompletionBlock:^{
1640 /// [self onOperationDone];
1643 unsigned ObjCBlockIndentWidth;
1645 /// Add a space after ``@property`` in Objective-C, i.e. use
1646 /// ``@property (readonly)`` instead of ``@property(readonly)``.
1647 bool ObjCSpaceAfterProperty;
1649 /// Add a space in front of an Objective-C protocol list, i.e. use
1650 /// ``Foo <Protocol>`` instead of ``Foo<Protocol>``.
1651 bool ObjCSpaceBeforeProtocolList;
1653 /// The penalty for breaking around an assignment operator.
1654 unsigned PenaltyBreakAssignment;
1656 /// The penalty for breaking a function call after ``call(``.
1657 unsigned PenaltyBreakBeforeFirstCallParameter;
1659 /// The penalty for each line break introduced inside a comment.
1660 unsigned PenaltyBreakComment;
1662 /// The penalty for breaking before the first ``<<``.
1663 unsigned PenaltyBreakFirstLessLess;
1665 /// The penalty for each line break introduced inside a string literal.
1666 unsigned PenaltyBreakString;
1668 /// The penalty for breaking after template declaration.
1669 unsigned PenaltyBreakTemplateDeclaration;
1671 /// The penalty for each character outside of the column limit.
1672 unsigned PenaltyExcessCharacter;
1674 /// Penalty for putting the return type of a function onto its own
1676 unsigned PenaltyReturnTypeOnItsOwnLine;
1678 /// The ``&`` and ``*`` alignment style.
1679 enum PointerAlignmentStyle {
1680 /// Align pointer to the left.
1685 /// Align pointer to the right.
1690 /// Align pointer in the middle.
1697 /// Pointer and reference alignment style.
1698 PointerAlignmentStyle PointerAlignment;
1700 /// See documentation of ``RawStringFormats``.
1701 struct RawStringFormat {
1702 /// The language of this raw string.
1703 LanguageKind Language;
1704 /// A list of raw string delimiters that match this language.
1705 std::vector<std::string> Delimiters;
1706 /// A list of enclosing function names that match this language.
1707 std::vector<std::string> EnclosingFunctions;
1708 /// The canonical delimiter for this language.
1709 std::string CanonicalDelimiter;
1710 /// The style name on which this raw string format is based on.
1711 /// If not specified, the raw string format is based on the style that this
1712 /// format is based on.
1713 std::string BasedOnStyle;
1714 bool operator==(const RawStringFormat &Other) const {
1715 return Language == Other.Language && Delimiters == Other.Delimiters &&
1716 EnclosingFunctions == Other.EnclosingFunctions &&
1717 CanonicalDelimiter == Other.CanonicalDelimiter &&
1718 BasedOnStyle == Other.BasedOnStyle;
1722 /// Defines hints for detecting supported languages code blocks in raw
1725 /// A raw string with a matching delimiter or a matching enclosing function
1726 /// name will be reformatted assuming the specified language based on the
1727 /// style for that language defined in the .clang-format file. If no style has
1728 /// been defined in the .clang-format file for the specific language, a
1729 /// predefined style given by 'BasedOnStyle' is used. If 'BasedOnStyle' is not
1730 /// found, the formatting is based on llvm style. A matching delimiter takes
1731 /// precedence over a matching enclosing function name for determining the
1732 /// language of the raw string contents.
1734 /// If a canonical delimiter is specified, occurrences of other delimiters for
1735 /// the same language will be updated to the canonical if possible.
1737 /// There should be at most one specification per language and each delimiter
1738 /// and enclosing function should not occur in multiple specifications.
1740 /// To configure this in the .clang-format file, use:
1742 /// RawStringFormats:
1743 /// - Language: TextProto
1747 /// EnclosingFunctions:
1748 /// - 'PARSE_TEXT_PROTO'
1749 /// BasedOnStyle: google
1754 /// BasedOnStyle: llvm
1755 /// CanonicalDelimiter: 'cc'
1757 std::vector<RawStringFormat> RawStringFormats;
1760 /// If ``true``, clang-format will attempt to re-flow comments.
1763 /// // veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongComment with plenty of information
1764 /// /* second veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongComment with plenty of information */
1767 /// // veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongComment with plenty of
1769 /// /* second veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongComment with plenty of
1770 /// * information */
1772 bool ReflowComments;
1775 /// If ``true``, clang-format will sort ``#includes``.
1778 /// #include "b.h" vs. #include "a.h"
1779 /// #include "a.h" #include "b.h"
1783 /// If ``true``, clang-format will sort using declarations.
1785 /// The order of using declarations is defined as follows:
1786 /// Split the strings by "::" and discard any initial empty strings. The last
1787 /// element of each list is a non-namespace name; all others are namespace
1788 /// names. Sort the lists of names lexicographically, where the sort order of
1789 /// individual names is that all non-namespace names come before all namespace
1790 /// names, and within those groups, names are in case-insensitive
1791 /// lexicographic order.
1794 /// using std::cout; vs. using std::cin;
1795 /// using std::cin; using std::cout;
1797 bool SortUsingDeclarations;
1799 /// If ``true``, a space is inserted after C style casts.
1802 /// (int) i; vs. (int)i;
1804 bool SpaceAfterCStyleCast;
1806 /// If ``true``, a space is inserted after the logical not operator (``!``).
1809 /// ! someExpression(); vs. !someExpression();
1811 bool SpaceAfterLogicalNot;
1813 /// If \c true, a space will be inserted after the 'template' keyword.
1816 /// template <int> void foo(); vs. template<int> void foo();
1818 bool SpaceAfterTemplateKeyword;
1820 /// If ``false``, spaces will be removed before assignment operators.
1823 /// int a = 5; vs. int a= 5;
1824 /// a += 42; a+= 42;
1826 bool SpaceBeforeAssignmentOperators;
1828 /// If ``true``, a space will be inserted before a C++11 braced list
1829 /// used to initialize an object (after the preceding identifier or type).
1832 /// Foo foo { bar }; vs. Foo foo{ bar };
1834 /// vector<int> { 1, 2, 3 }; vector<int>{ 1, 2, 3 };
1835 /// new int[3] { 1, 2, 3 }; new int[3]{ 1, 2, 3 };
1837 bool SpaceBeforeCpp11BracedList;
1839 /// If ``false``, spaces will be removed before constructor initializer
1843 /// Foo::Foo() : a(a) {} Foo::Foo(): a(a) {}
1845 bool SpaceBeforeCtorInitializerColon;
1847 /// If ``false``, spaces will be removed before inheritance colon.
1850 /// class Foo : Bar {} vs. class Foo: Bar {}
1852 bool SpaceBeforeInheritanceColon;
1854 /// Different ways to put a space before opening parentheses.
1855 enum SpaceBeforeParensOptions {
1856 /// Never put a space before opening parentheses.
1865 /// Put a space before opening parentheses only after control statement
1866 /// keywords (``for/if/while...``).
1874 SBPO_ControlStatements,
1875 /// Put a space before opening parentheses only if the parentheses are not
1885 SBPO_NonEmptyParentheses,
1886 /// Always put a space before opening parentheses, except when it's
1887 /// prohibited by the syntax rules (in function-like macro definitions) or
1888 /// when determined by other style rules (after unary operators, opening
1889 /// parentheses, etc.)
1900 /// Defines in which cases to put a space before opening parentheses.
1901 SpaceBeforeParensOptions SpaceBeforeParens;
1903 /// If ``false``, spaces will be removed before range-based for loop
1907 /// for (auto v : values) {} vs. for(auto v: values) {}
1909 bool SpaceBeforeRangeBasedForLoopColon;
1911 /// If ``true``, spaces will be inserted into ``{}``.
1914 /// void f() { } vs. void f() {}
1915 /// while (true) { } while (true) {}
1917 bool SpaceInEmptyBlock;
1919 /// If ``true``, spaces may be inserted into ``()``.
1922 /// void f( ) { vs. void f() {
1923 /// int x[] = {foo( ), bar( )}; int x[] = {foo(), bar()};
1924 /// if (true) { if (true) {
1929 bool SpaceInEmptyParentheses;
1931 /// The number of spaces before trailing line comments
1932 /// (``//`` - comments).
1934 /// This does not affect trailing block comments (``/*`` - comments) as
1935 /// those commonly have different usage patterns and a number of special
1938 /// SpacesBeforeTrailingComments: 3
1940 /// if (true) { // foo1
1945 unsigned SpacesBeforeTrailingComments;
1947 /// If ``true``, spaces will be inserted after ``<`` and before ``>``
1948 /// in template argument lists.
1951 /// static_cast< int >(arg); vs. static_cast<int>(arg);
1952 /// std::function< void(int) > fct; std::function<void(int)> fct;
1954 bool SpacesInAngles;
1956 /// If ``true``, spaces will be inserted around if/for/switch/while
1960 /// if ( a ) { ... } vs. if (a) { ... }
1961 /// while ( i < 5 ) { ... } while (i < 5) { ... }
1963 bool SpacesInConditionalStatement;
1965 /// If ``true``, spaces are inserted inside container literals (e.g.
1966 /// ObjC and Javascript array and dict literals).
1969 /// var arr = [ 1, 2, 3 ]; vs. var arr = [1, 2, 3];
1970 /// f({a : 1, b : 2, c : 3}); f({a: 1, b: 2, c: 3});
1972 bool SpacesInContainerLiterals;
1974 /// If ``true``, spaces may be inserted into C style casts.
1977 /// x = ( int32 )y vs. x = (int32)y
1979 bool SpacesInCStyleCastParentheses;
1981 /// If ``true``, spaces will be inserted after ``(`` and before ``)``.
1984 /// t f( Deleted & ) & = delete; vs. t f(Deleted &) & = delete;
1986 bool SpacesInParentheses;
1988 /// If ``true``, spaces will be inserted after ``[`` and before ``]``.
1989 /// Lambdas without arguments or unspecified size array declarations will not
1993 /// int a[ 5 ]; vs. int a[5];
1994 /// std::unique_ptr<int[]> foo() {} // Won't be affected
1996 bool SpacesInSquareBrackets;
1998 /// If ``true``, spaces will be before ``[``.
1999 /// Lambdas will not be affected. Only the first ``[`` will get a space added.
2002 /// int a [5]; vs. int a[5];
2003 /// int a [5][5]; vs. int a[5][5];
2005 bool SpaceBeforeSquareBrackets;
2007 /// Supported language standards for parsing and formatting C++ constructs.
2009 /// Latest: vector<set<int>>
2010 /// c++03 vs. vector<set<int> >
2013 /// The correct way to spell a specific language version is e.g. ``c++11``.
2014 /// The historical aliases ``Cpp03`` and ``Cpp11`` are deprecated.
2015 enum LanguageStandard {
2016 /// Parse and format as C++03.
2017 /// ``Cpp03`` is a deprecated alias for ``c++03``
2019 /// Parse and format as C++11.
2021 /// Parse and format as C++14.
2023 /// Parse and format as C++17.
2025 /// Parse and format as C++20.
2027 /// Parse and format using the latest supported language version.
2028 /// ``Cpp11`` is a deprecated alias for ``Latest``
2030 /// Automatic detection based on the input.
2034 /// Parse and format C++ constructs compatible with this standard.
2037 /// vector<set<int> > x; vs. vector<set<int>> x;
2039 LanguageStandard Standard;
2041 /// The number of columns used for tab stops.
2044 /// Different ways to use tab in formatting.
2048 /// Use tabs only for indentation.
2050 /// Use tabs only for line continuation and indentation.
2051 UT_ForContinuationAndIndentation,
2052 /// Use tabs whenever we need to fill whitespace that spans at least from
2053 /// one tab stop to the next one.
2057 /// \brief Use ``\r\n`` instead of ``\n`` for line breaks.
2058 /// Also used as fallback if ``DeriveLineEnding`` is true.
2061 /// The way to use tab characters in the resulting file.
2064 bool operator==(const FormatStyle &R) const {
2065 return AccessModifierOffset == R.AccessModifierOffset &&
2066 AlignAfterOpenBracket == R.AlignAfterOpenBracket &&
2067 AlignConsecutiveAssignments == R.AlignConsecutiveAssignments &&
2068 AlignConsecutiveDeclarations == R.AlignConsecutiveDeclarations &&
2069 AlignEscapedNewlines == R.AlignEscapedNewlines &&
2070 AlignOperands == R.AlignOperands &&
2071 AlignTrailingComments == R.AlignTrailingComments &&
2072 AllowAllArgumentsOnNextLine == R.AllowAllArgumentsOnNextLine &&
2073 AllowAllConstructorInitializersOnNextLine ==
2074 R.AllowAllConstructorInitializersOnNextLine &&
2075 AllowAllParametersOfDeclarationOnNextLine ==
2076 R.AllowAllParametersOfDeclarationOnNextLine &&
2077 AllowShortBlocksOnASingleLine == R.AllowShortBlocksOnASingleLine &&
2078 AllowShortCaseLabelsOnASingleLine ==
2079 R.AllowShortCaseLabelsOnASingleLine &&
2080 AllowShortFunctionsOnASingleLine ==
2081 R.AllowShortFunctionsOnASingleLine &&
2082 AllowShortIfStatementsOnASingleLine ==
2083 R.AllowShortIfStatementsOnASingleLine &&
2084 AllowShortLambdasOnASingleLine == R.AllowShortLambdasOnASingleLine &&
2085 AllowShortLoopsOnASingleLine == R.AllowShortLoopsOnASingleLine &&
2086 AlwaysBreakAfterReturnType == R.AlwaysBreakAfterReturnType &&
2087 AlwaysBreakBeforeMultilineStrings ==
2088 R.AlwaysBreakBeforeMultilineStrings &&
2089 AlwaysBreakTemplateDeclarations ==
2090 R.AlwaysBreakTemplateDeclarations &&
2091 BinPackArguments == R.BinPackArguments &&
2092 BinPackParameters == R.BinPackParameters &&
2093 BreakBeforeBinaryOperators == R.BreakBeforeBinaryOperators &&
2094 BreakBeforeBraces == R.BreakBeforeBraces &&
2095 BreakBeforeTernaryOperators == R.BreakBeforeTernaryOperators &&
2096 BreakConstructorInitializers == R.BreakConstructorInitializers &&
2097 CompactNamespaces == R.CompactNamespaces &&
2098 BreakAfterJavaFieldAnnotations == R.BreakAfterJavaFieldAnnotations &&
2099 BreakStringLiterals == R.BreakStringLiterals &&
2100 ColumnLimit == R.ColumnLimit && CommentPragmas == R.CommentPragmas &&
2101 BreakInheritanceList == R.BreakInheritanceList &&
2102 ConstructorInitializerAllOnOneLineOrOnePerLine ==
2103 R.ConstructorInitializerAllOnOneLineOrOnePerLine &&
2104 ConstructorInitializerIndentWidth ==
2105 R.ConstructorInitializerIndentWidth &&
2106 ContinuationIndentWidth == R.ContinuationIndentWidth &&
2107 Cpp11BracedListStyle == R.Cpp11BracedListStyle &&
2108 DeriveLineEnding == R.DeriveLineEnding &&
2109 DerivePointerAlignment == R.DerivePointerAlignment &&
2110 DisableFormat == R.DisableFormat &&
2111 ExperimentalAutoDetectBinPacking ==
2112 R.ExperimentalAutoDetectBinPacking &&
2113 FixNamespaceComments == R.FixNamespaceComments &&
2114 ForEachMacros == R.ForEachMacros &&
2115 IncludeStyle.IncludeBlocks == R.IncludeStyle.IncludeBlocks &&
2116 IncludeStyle.IncludeCategories == R.IncludeStyle.IncludeCategories &&
2117 IncludeStyle.IncludeIsMainRegex ==
2118 R.IncludeStyle.IncludeIsMainRegex &&
2119 IncludeStyle.IncludeIsMainSourceRegex ==
2120 R.IncludeStyle.IncludeIsMainSourceRegex &&
2121 IndentCaseLabels == R.IndentCaseLabels &&
2122 IndentGotoLabels == R.IndentGotoLabels &&
2123 IndentPPDirectives == R.IndentPPDirectives &&
2124 IndentWidth == R.IndentWidth && Language == R.Language &&
2125 IndentWrappedFunctionNames == R.IndentWrappedFunctionNames &&
2126 JavaImportGroups == R.JavaImportGroups &&
2127 JavaScriptQuotes == R.JavaScriptQuotes &&
2128 JavaScriptWrapImports == R.JavaScriptWrapImports &&
2129 KeepEmptyLinesAtTheStartOfBlocks ==
2130 R.KeepEmptyLinesAtTheStartOfBlocks &&
2131 MacroBlockBegin == R.MacroBlockBegin &&
2132 MacroBlockEnd == R.MacroBlockEnd &&
2133 MaxEmptyLinesToKeep == R.MaxEmptyLinesToKeep &&
2134 NamespaceIndentation == R.NamespaceIndentation &&
2135 NamespaceMacros == R.NamespaceMacros &&
2136 ObjCBinPackProtocolList == R.ObjCBinPackProtocolList &&
2137 ObjCBlockIndentWidth == R.ObjCBlockIndentWidth &&
2138 ObjCSpaceAfterProperty == R.ObjCSpaceAfterProperty &&
2139 ObjCSpaceBeforeProtocolList == R.ObjCSpaceBeforeProtocolList &&
2140 PenaltyBreakAssignment == R.PenaltyBreakAssignment &&
2141 PenaltyBreakBeforeFirstCallParameter ==
2142 R.PenaltyBreakBeforeFirstCallParameter &&
2143 PenaltyBreakComment == R.PenaltyBreakComment &&
2144 PenaltyBreakFirstLessLess == R.PenaltyBreakFirstLessLess &&
2145 PenaltyBreakString == R.PenaltyBreakString &&
2146 PenaltyExcessCharacter == R.PenaltyExcessCharacter &&
2147 PenaltyReturnTypeOnItsOwnLine == R.PenaltyReturnTypeOnItsOwnLine &&
2148 PenaltyBreakTemplateDeclaration ==
2149 R.PenaltyBreakTemplateDeclaration &&
2150 PointerAlignment == R.PointerAlignment &&
2151 RawStringFormats == R.RawStringFormats &&
2152 SpaceAfterCStyleCast == R.SpaceAfterCStyleCast &&
2153 SpaceAfterLogicalNot == R.SpaceAfterLogicalNot &&
2154 SpaceAfterTemplateKeyword == R.SpaceAfterTemplateKeyword &&
2155 SpaceBeforeAssignmentOperators == R.SpaceBeforeAssignmentOperators &&
2156 SpaceBeforeCpp11BracedList == R.SpaceBeforeCpp11BracedList &&
2157 SpaceBeforeCtorInitializerColon ==
2158 R.SpaceBeforeCtorInitializerColon &&
2159 SpaceBeforeInheritanceColon == R.SpaceBeforeInheritanceColon &&
2160 SpaceBeforeParens == R.SpaceBeforeParens &&
2161 SpaceBeforeRangeBasedForLoopColon ==
2162 R.SpaceBeforeRangeBasedForLoopColon &&
2163 SpaceInEmptyBlock == R.SpaceInEmptyBlock &&
2164 SpaceInEmptyParentheses == R.SpaceInEmptyParentheses &&
2165 SpacesBeforeTrailingComments == R.SpacesBeforeTrailingComments &&
2166 SpacesInAngles == R.SpacesInAngles &&
2167 SpacesInConditionalStatement == R.SpacesInConditionalStatement &&
2168 SpacesInContainerLiterals == R.SpacesInContainerLiterals &&
2169 SpacesInCStyleCastParentheses == R.SpacesInCStyleCastParentheses &&
2170 SpacesInParentheses == R.SpacesInParentheses &&
2171 SpacesInSquareBrackets == R.SpacesInSquareBrackets &&
2172 SpaceBeforeSquareBrackets == R.SpaceBeforeSquareBrackets &&
2173 Standard == R.Standard && TabWidth == R.TabWidth &&
2174 StatementMacros == R.StatementMacros && UseTab == R.UseTab &&
2175 UseCRLF == R.UseCRLF && TypenameMacros == R.TypenameMacros;
2178 llvm::Optional<FormatStyle> GetLanguageStyle(LanguageKind Language) const;
2180 // Stores per-language styles. A FormatStyle instance inside has an empty
2181 // StyleSet. A FormatStyle instance returned by the Get method has its
2182 // StyleSet set to a copy of the originating StyleSet, effectively keeping the
2183 // internal representation of that StyleSet alive.
2185 // The memory management and ownership reminds of a birds nest: chicks
2186 // leaving the nest take photos of the nest with them.
2187 struct FormatStyleSet {
2188 typedef std::map<FormatStyle::LanguageKind, FormatStyle> MapType;
2190 llvm::Optional<FormatStyle> Get(FormatStyle::LanguageKind Language) const;
2192 // Adds \p Style to this FormatStyleSet. Style must not have an associated
2194 // Style.Language should be different than LK_None. If this FormatStyleSet
2195 // already contains an entry for Style.Language, that gets replaced with the
2197 void Add(FormatStyle Style);
2199 // Clears this FormatStyleSet.
2203 std::shared_ptr<MapType> Styles;
2206 static FormatStyleSet BuildStyleSetFromConfiguration(
2207 const FormatStyle &MainStyle,
2208 const std::vector<FormatStyle> &ConfigurationStyles);
2211 FormatStyleSet StyleSet;
2213 friend std::error_code parseConfiguration(StringRef Text, FormatStyle *Style);
2216 /// Returns a format style complying with the LLVM coding standards:
2217 /// http://llvm.org/docs/CodingStandards.html.
2218 FormatStyle getLLVMStyle(
2219 FormatStyle::LanguageKind Language = FormatStyle::LanguageKind::LK_Cpp);
2221 /// Returns a format style complying with one of Google's style guides:
2222 /// http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml.
2223 /// http://google-styleguide.googlecode.com/svn/trunk/javascriptguide.xml.
2224 /// https://developers.google.com/protocol-buffers/docs/style.
2225 FormatStyle getGoogleStyle(FormatStyle::LanguageKind Language);
2227 /// Returns a format style complying with Chromium's style guide:
2228 /// http://www.chromium.org/developers/coding-style.
2229 FormatStyle getChromiumStyle(FormatStyle::LanguageKind Language);
2231 /// Returns a format style complying with Mozilla's style guide:
2232 /// https://developer.mozilla.org/en-US/docs/Developer_Guide/Coding_Style.
2233 FormatStyle getMozillaStyle();
2235 /// Returns a format style complying with Webkit's style guide:
2236 /// http://www.webkit.org/coding/coding-style.html
2237 FormatStyle getWebKitStyle();
2239 /// Returns a format style complying with GNU Coding Standards:
2240 /// http://www.gnu.org/prep/standards/standards.html
2241 FormatStyle getGNUStyle();
2243 /// Returns a format style complying with Microsoft style guide:
2244 /// https://docs.microsoft.com/en-us/visualstudio/ide/editorconfig-code-style-settings-reference?view=vs-2017
2245 FormatStyle getMicrosoftStyle(FormatStyle::LanguageKind Language);
2247 /// Returns style indicating formatting should be not applied at all.
2248 FormatStyle getNoStyle();
2250 /// Gets a predefined style for the specified language by name.
2252 /// Currently supported names: LLVM, Google, Chromium, Mozilla. Names are
2253 /// compared case-insensitively.
2255 /// Returns ``true`` if the Style has been set.
2256 bool getPredefinedStyle(StringRef Name, FormatStyle::LanguageKind Language,
2257 FormatStyle *Style);
2259 /// Parse configuration from YAML-formatted text.
2261 /// Style->Language is used to get the base style, if the ``BasedOnStyle``
2262 /// option is present.
2264 /// The FormatStyleSet of Style is reset.
2266 /// When ``BasedOnStyle`` is not present, options not present in the YAML
2267 /// document, are retained in \p Style.
2268 std::error_code parseConfiguration(StringRef Text, FormatStyle *Style);
2270 /// Gets configuration in a YAML string.
2271 std::string configurationAsText(const FormatStyle &Style);
2273 /// Returns the replacements necessary to sort all ``#include`` blocks
2274 /// that are affected by ``Ranges``.
2275 tooling::Replacements sortIncludes(const FormatStyle &Style, StringRef Code,
2276 ArrayRef<tooling::Range> Ranges,
2278 unsigned *Cursor = nullptr);
2280 /// Returns the replacements corresponding to applying and formatting
2281 /// \p Replaces on success; otheriwse, return an llvm::Error carrying
2282 /// llvm::StringError.
2283 llvm::Expected<tooling::Replacements>
2284 formatReplacements(StringRef Code, const tooling::Replacements &Replaces,
2285 const FormatStyle &Style);
2287 /// Returns the replacements corresponding to applying \p Replaces and
2288 /// cleaning up the code after that on success; otherwise, return an llvm::Error
2289 /// carrying llvm::StringError.
2290 /// This also supports inserting/deleting C++ #include directives:
2291 /// - If a replacement has offset UINT_MAX, length 0, and a replacement text
2292 /// that is an #include directive, this will insert the #include into the
2293 /// correct block in the \p Code.
2294 /// - If a replacement has offset UINT_MAX, length 1, and a replacement text
2295 /// that is the name of the header to be removed, the header will be removed
2296 /// from \p Code if it exists.
2297 /// The include manipulation is done via `tooling::HeaderInclude`, see its
2298 /// documentation for more details on how include insertion points are found and
2299 /// what edits are produced.
2300 llvm::Expected<tooling::Replacements>
2301 cleanupAroundReplacements(StringRef Code, const tooling::Replacements &Replaces,
2302 const FormatStyle &Style);
2304 /// Represents the status of a formatting attempt.
2305 struct FormattingAttemptStatus {
2306 /// A value of ``false`` means that any of the affected ranges were not
2307 /// formatted due to a non-recoverable syntax error.
2308 bool FormatComplete = true;
2310 /// If ``FormatComplete`` is false, ``Line`` records a one-based
2311 /// original line number at which a syntax error might have occurred. This is
2312 /// based on a best-effort analysis and could be imprecise.
2316 /// Reformats the given \p Ranges in \p Code.
2318 /// Each range is extended on either end to its next bigger logic unit, i.e.
2319 /// everything that might influence its formatting or might be influenced by its
2322 /// Returns the ``Replacements`` necessary to make all \p Ranges comply with
2325 /// If ``Status`` is non-null, its value will be populated with the status of
2326 /// this formatting attempt. See \c FormattingAttemptStatus.
2327 tooling::Replacements reformat(const FormatStyle &Style, StringRef Code,
2328 ArrayRef<tooling::Range> Ranges,
2329 StringRef FileName = "<stdin>",
2330 FormattingAttemptStatus *Status = nullptr);
2332 /// Same as above, except if ``IncompleteFormat`` is non-null, its value
2333 /// will be set to true if any of the affected ranges were not formatted due to
2334 /// a non-recoverable syntax error.
2335 tooling::Replacements reformat(const FormatStyle &Style, StringRef Code,
2336 ArrayRef<tooling::Range> Ranges,
2337 StringRef FileName, bool *IncompleteFormat);
2339 /// Clean up any erroneous/redundant code in the given \p Ranges in \p
2342 /// Returns the ``Replacements`` that clean up all \p Ranges in \p Code.
2343 tooling::Replacements cleanup(const FormatStyle &Style, StringRef Code,
2344 ArrayRef<tooling::Range> Ranges,
2345 StringRef FileName = "<stdin>");
2347 /// Fix namespace end comments in the given \p Ranges in \p Code.
2349 /// Returns the ``Replacements`` that fix the namespace comments in all
2350 /// \p Ranges in \p Code.
2351 tooling::Replacements fixNamespaceEndComments(const FormatStyle &Style,
2353 ArrayRef<tooling::Range> Ranges,
2354 StringRef FileName = "<stdin>");
2356 /// Sort consecutive using declarations in the given \p Ranges in
2359 /// Returns the ``Replacements`` that sort the using declarations in all
2360 /// \p Ranges in \p Code.
2361 tooling::Replacements sortUsingDeclarations(const FormatStyle &Style,
2363 ArrayRef<tooling::Range> Ranges,
2364 StringRef FileName = "<stdin>");
2366 /// Returns the ``LangOpts`` that the formatter expects you to set.
2368 /// \param Style determines specific settings for lexing mode.
2369 LangOptions getFormattingLangOpts(const FormatStyle &Style = getLLVMStyle());
2371 /// Description to be used for help text for a ``llvm::cl`` option for
2372 /// specifying format style. The description is closely related to the operation
2373 /// of ``getStyle()``.
2374 extern const char *StyleOptionHelpDescription;
2376 /// The suggested format style to use by default. This allows tools using
2377 /// `getStyle` to have a consistent default style.
2378 /// Different builds can modify the value to the preferred styles.
2379 extern const char *DefaultFormatStyle;
2381 /// The suggested predefined style to use as the fallback style in `getStyle`.
2382 /// Different builds can modify the value to the preferred styles.
2383 extern const char *DefaultFallbackStyle;
2385 /// Construct a FormatStyle based on ``StyleName``.
2387 /// ``StyleName`` can take several forms:
2388 /// * "{<key>: <value>, ...}" - Set specic style parameters.
2389 /// * "<style name>" - One of the style names supported by
2390 /// getPredefinedStyle().
2391 /// * "file" - Load style configuration from a file called ``.clang-format``
2392 /// located in one of the parent directories of ``FileName`` or the current
2393 /// directory if ``FileName`` is empty.
2395 /// \param[in] StyleName Style name to interpret according to the description
2397 /// \param[in] FileName Path to start search for .clang-format if ``StyleName``
2399 /// \param[in] FallbackStyle The name of a predefined style used to fallback to
2400 /// in case \p StyleName is "file" and no file can be found.
2401 /// \param[in] Code The actual code to be formatted. Used to determine the
2402 /// language if the filename isn't sufficient.
2403 /// \param[in] FS The underlying file system, in which the file resides. By
2404 /// default, the file system is the real file system.
2406 /// \returns FormatStyle as specified by ``StyleName``. If ``StyleName`` is
2407 /// "file" and no file is found, returns ``FallbackStyle``. If no style could be
2408 /// determined, returns an Error.
2409 llvm::Expected<FormatStyle> getStyle(StringRef StyleName, StringRef FileName,
2410 StringRef FallbackStyle,
2411 StringRef Code = "",
2412 llvm::vfs::FileSystem *FS = nullptr);
2414 // Guesses the language from the ``FileName`` and ``Code`` to be formatted.
2415 // Defaults to FormatStyle::LK_Cpp.
2416 FormatStyle::LanguageKind guessLanguage(StringRef FileName, StringRef Code);
2418 // Returns a string representation of ``Language``.
2419 inline StringRef getLanguageName(FormatStyle::LanguageKind Language) {
2421 case FormatStyle::LK_Cpp:
2423 case FormatStyle::LK_CSharp:
2425 case FormatStyle::LK_ObjC:
2426 return "Objective-C";
2427 case FormatStyle::LK_Java:
2429 case FormatStyle::LK_JavaScript:
2430 return "JavaScript";
2431 case FormatStyle::LK_Proto:
2433 case FormatStyle::LK_TableGen:
2435 case FormatStyle::LK_TextProto:
2442 } // end namespace format
2443 } // end namespace clang
2447 struct is_error_code_enum<clang::format::ParseError> : std::true_type {};
2450 #endif // LLVM_CLANG_FORMAT_FORMAT_H