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 /// Allows contracting simple braced statements to a single line.
221 /// E.g., this allows ``if (a) { return; }`` to be put on a single line.
222 bool AllowShortBlocksOnASingleLine;
224 /// If ``true``, short case labels will be contracted to a single line.
227 /// switch (a) { vs. switch (a) {
228 /// case 1: x = 1; break; case 1:
229 /// case 2: return; x = 1;
235 bool AllowShortCaseLabelsOnASingleLine;
237 /// Different styles for merging short functions containing at most one
239 enum ShortFunctionStyle {
240 /// Never merge functions into a single line.
242 /// Only merge functions defined inside a class. Same as "inline",
243 /// except it does not implies "empty": i.e. top level empty functions
244 /// are not merged either.
247 /// void f() { foo(); }
256 /// Only merge empty functions.
264 /// Only merge functions defined inside a class. Implies "empty".
267 /// void f() { foo(); }
275 /// Merge all functions fitting on a single line.
278 /// void f() { foo(); }
280 /// void f() { bar(); }
285 /// Dependent on the value, ``int f() { return 0; }`` can be put on a
287 ShortFunctionStyle AllowShortFunctionsOnASingleLine;
289 /// Different styles for handling short if lines
291 /// Never put short ifs on the same line.
300 /// Without else put short ifs on the same line only if
301 /// the else is not a compound statement.
308 /// Always put short ifs on the same line if
309 /// the else is not a compound statement or not.
319 /// If ``true``, ``if (a) return;`` can be put on a single line.
320 ShortIfStyle AllowShortIfStatementsOnASingleLine;
322 /// Different styles for merging short lambdas containing at most one
324 enum ShortLambdaStyle {
325 /// Never merge lambdas into a single line.
327 /// Only merge empty lambdas.
329 /// auto lambda = [](int a) {}
330 /// auto lambda2 = [](int a) {
335 /// Merge lambda into a single line if argument of a function.
337 /// auto lambda = [](int a) {
340 /// sort(a.begin(), a.end(), ()[] { return x < y; })
343 /// Merge all lambdas fitting on a single line.
345 /// auto lambda = [](int a) {}
346 /// auto lambda2 = [](int a) { return a; };
351 /// Dependent on the value, ``auto lambda []() { return 0; }`` can be put on a
353 ShortLambdaStyle AllowShortLambdasOnASingleLine;
355 /// If ``true``, ``while (true) continue;`` can be put on a single
357 bool AllowShortLoopsOnASingleLine;
359 /// Different ways to break after the function definition return type.
360 /// This option is **deprecated** and is retained for backwards compatibility.
361 enum DefinitionReturnTypeBreakingStyle {
362 /// Break after return type automatically.
363 /// ``PenaltyReturnTypeOnItsOwnLine`` is taken into account.
365 /// Always break after the return type.
367 /// Always break after the return types of top-level functions.
371 /// Different ways to break after the function definition or
372 /// declaration return type.
373 enum ReturnTypeBreakingStyle {
374 /// Break after return type automatically.
375 /// ``PenaltyReturnTypeOnItsOwnLine`` is taken into account.
378 /// int f() { return 0; };
381 /// int f() { return 1; }
384 /// Always break after the return type.
400 /// Always break after the return types of top-level functions.
403 /// int f() { return 0; };
413 /// Always break after the return type of function definitions.
428 /// Always break after the return type of top-level definitions.
431 /// int f() { return 0; };
439 RTBS_TopLevelDefinitions,
442 /// The function definition return type breaking style to use. This
443 /// option is **deprecated** and is retained for backwards compatibility.
444 DefinitionReturnTypeBreakingStyle AlwaysBreakAfterDefinitionReturnType;
446 /// The function declaration return type breaking style to use.
447 ReturnTypeBreakingStyle AlwaysBreakAfterReturnType;
449 /// If ``true``, always break before multiline string literals.
451 /// This flag is mean to make cases where there are multiple multiline strings
452 /// in a file look more consistent. Thus, it will only take effect if wrapping
453 /// the string at that point leads to it being indented
454 /// ``ContinuationIndentWidth`` spaces from the start of the line.
457 /// aaaa = vs. aaaa = "bbbb"
461 bool AlwaysBreakBeforeMultilineStrings;
463 /// Different ways to break after the template declaration.
464 enum BreakTemplateDeclarationsStyle {
465 /// Do not force break before declaration.
466 /// ``PenaltyBreakTemplateDeclaration`` is taken into account.
468 /// template <typename T> T foo() {
470 /// template <typename T> T foo(int aaaaaaaaaaaaaaaaaaaaa,
471 /// int bbbbbbbbbbbbbbbbbbbbb) {
475 /// Force break after template declaration only when the following
476 /// declaration spans multiple lines.
478 /// template <typename T> T foo() {
480 /// template <typename T>
481 /// T foo(int aaaaaaaaaaaaaaaaaaaaa,
482 /// int bbbbbbbbbbbbbbbbbbbbb) {
486 /// Always break after template declaration.
488 /// template <typename T>
491 /// template <typename T>
492 /// T foo(int aaaaaaaaaaaaaaaaaaaaa,
493 /// int bbbbbbbbbbbbbbbbbbbbb) {
499 /// The template declaration breaking style to use.
500 BreakTemplateDeclarationsStyle AlwaysBreakTemplateDeclarations;
502 /// If ``false``, a function call's arguments will either be all on the
503 /// same line or will have one line each.
507 /// f(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaa,
508 /// aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);
513 /// f(aaaaaaaaaaaaaaaaaaaa,
514 /// aaaaaaaaaaaaaaaaaaaa,
515 /// aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);
518 bool BinPackArguments;
520 /// If ``false``, a function declaration's or function definition's
521 /// parameters will either all be on the same line or will have one line each.
524 /// void f(int aaaaaaaaaaaaaaaaaaaa, int aaaaaaaaaaaaaaaaaaaa,
525 /// int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}
528 /// void f(int aaaaaaaaaaaaaaaaaaaa,
529 /// int aaaaaaaaaaaaaaaaaaaa,
530 /// int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}
532 bool BinPackParameters;
534 /// The style of wrapping parameters on the same line (bin-packed) or
535 /// on one line each.
537 /// Automatically determine parameter bin-packing behavior.
539 /// Always bin-pack parameters.
541 /// Never bin-pack parameters.
545 /// The style of breaking before or after binary operators.
546 enum BinaryOperatorStyle {
547 /// Break after operators.
549 /// LooooooooooongType loooooooooooooooooooooongVariable =
550 /// someLooooooooooooooooongFunction();
552 /// bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +
553 /// aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==
554 /// aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa &&
555 /// aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >
556 /// ccccccccccccccccccccccccccccccccccccccccc;
559 /// Break before operators that aren't assignments.
561 /// LooooooooooongType loooooooooooooooooooooongVariable =
562 /// someLooooooooooooooooongFunction();
564 /// bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
565 /// + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
566 /// == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
567 /// && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
568 /// > ccccccccccccccccccccccccccccccccccccccccc;
571 /// Break before operators.
573 /// LooooooooooongType loooooooooooooooooooooongVariable
574 /// = someLooooooooooooooooongFunction();
576 /// bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
577 /// + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
578 /// == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
579 /// && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
580 /// > ccccccccccccccccccccccccccccccccccccccccc;
585 /// The way to wrap binary operators.
586 BinaryOperatorStyle BreakBeforeBinaryOperators;
588 /// Different ways to attach braces to their surrounding context.
589 enum BraceBreakingStyle {
590 /// Always attach braces to surrounding context.
596 /// void foo() { bar(); }
601 /// enum X : int { A, B };
604 /// Like ``Attach``, but break before braces on function, namespace and
605 /// class definitions.
611 /// void foo() { bar(); }
618 /// enum X : int { A, B };
621 /// Like ``Attach``, but break before braces on enum, function, and record
628 /// void foo() { bar(); }
635 /// enum X : int { A, B };
638 /// Like ``Attach``, but break before function definitions, ``catch``, and
646 /// void foo() { bar(); }
653 /// enum X : int { A, B };
656 /// Always break before braces.
665 /// void foo() { bar(); }
682 /// Always break before braces and add an extra level of indentation to
683 /// braces of control statements, not to those of class, function
684 /// or other definitions.
693 /// void foo() { bar(); }
710 /// Like ``Attach``, but break before functions.
716 /// void foo() { bar(); }
722 /// enum X : int { A, B };
725 /// Configure each individual brace in `BraceWrapping`.
729 /// The brace breaking style to use.
730 BraceBreakingStyle BreakBeforeBraces;
732 /// Precise control over the wrapping of braces.
734 /// # Should be declared this way:
735 /// BreakBeforeBraces: Custom
739 struct BraceWrappingFlags {
740 /// Wrap case labels.
743 /// switch (foo) { vs. switch (foo) {
744 /// case 1: { case 1:
756 /// Wrap class definitions.
766 /// Wrap control statements (``if``/``for``/``while``/``switch``/..).
773 /// for (int i = 0; i < 10; ++i)
780 /// for (int i = 0; i < 10; ++i) {
783 bool AfterControlStatement;
784 /// Wrap enum definitions.
793 /// enum X : int { B };
796 /// Wrap function definitions.
812 /// Wrap namespace definitions.
828 /// Wrap ObjC definitions (interfaces, implementations...).
829 /// \note @autoreleasepool and @synchronized blocks are wrapped
830 /// according to `AfterControlStatement` flag.
831 bool AfterObjCDeclaration;
832 /// Wrap struct definitions.
846 /// Wrap union definitions.
860 /// Wrap extern blocks.
873 bool AfterExternBlock;
874 /// Wrap before ``catch``.
890 /// Wrap before ``else``.
904 /// Indent the wrapped braces themselves.
906 /// If ``false``, empty function body can be put on a single line.
907 /// This option is used only if the opening brace of the function has
908 /// already been wrapped, i.e. the `AfterFunction` brace wrapping mode is
909 /// set, and the function could/should not be put on a single line (as per
910 /// `AllowShortFunctionsOnASingleLine` and constructor formatting options).
912 /// int f() vs. inf f()
917 bool SplitEmptyFunction;
918 /// If ``false``, empty record (e.g. class, struct or union) body
919 /// can be put on a single line. This option is used only if the opening
920 /// brace of the record has already been wrapped, i.e. the `AfterClass`
921 /// (for classes) brace wrapping mode is set.
923 /// class Foo vs. class Foo
928 bool SplitEmptyRecord;
929 /// If ``false``, empty namespace body can be put on a single line.
930 /// This option is used only if the opening brace of the namespace has
931 /// already been wrapped, i.e. the `AfterNamespace` brace wrapping mode is
934 /// namespace Foo vs. namespace Foo
939 bool SplitEmptyNamespace;
942 /// Control of individual brace wrapping cases.
944 /// If ``BreakBeforeBraces`` is set to ``BS_Custom``, use this to specify how
945 /// each individual brace case should be handled. Otherwise, this is ignored.
947 /// # Example of usage:
948 /// BreakBeforeBraces: Custom
951 /// AfterStruct: false
952 /// SplitEmptyFunction: false
954 BraceWrappingFlags BraceWrapping;
956 /// If ``true``, ternary operators will be placed after line breaks.
959 /// veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongDescription
961 /// : SecondValueVeryVeryVeryVeryLong;
964 /// veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongDescription ?
966 /// SecondValueVeryVeryVeryVeryLong;
968 bool BreakBeforeTernaryOperators;
970 /// Different ways to break initializers.
971 enum BreakConstructorInitializersStyle {
972 /// Break constructor initializers before the colon and after the commas.
975 /// : initializer1(),
979 /// Break constructor initializers before the colon and commas, and align
980 /// the commas with the colon.
987 /// Break constructor initializers after the colon and commas.
996 /// The constructor initializers style to use.
997 BreakConstructorInitializersStyle BreakConstructorInitializers;
999 /// Break after each annotation on a field in Java files.
1002 /// @Partial vs. @Partial @Mock DataLoad loader;
1004 /// DataLoad loader;
1006 bool BreakAfterJavaFieldAnnotations;
1008 /// Allow breaking string literals when formatting.
1009 bool BreakStringLiterals;
1011 /// The column limit.
1013 /// A column limit of ``0`` means that there is no column limit. In this case,
1014 /// clang-format will respect the input's line breaking decisions within
1015 /// statements unless they contradict other rules.
1016 unsigned ColumnLimit;
1018 /// A regular expression that describes comments with special meaning,
1019 /// which should not be split into lines or otherwise changed.
1021 /// // CommentPragmas: '^ FOOBAR pragma:'
1022 /// // Will leave the following line unaffected
1023 /// #include <vector> // FOOBAR pragma: keep
1025 std::string CommentPragmas;
1027 /// Different ways to break inheritance list.
1028 enum BreakInheritanceListStyle {
1029 /// Break inheritance list before the colon and after the commas.
1037 /// Break inheritance list before the colon and commas, and align
1038 /// the commas with the colon.
1046 /// Break inheritance list after the colon and commas.
1056 /// The inheritance list style to use.
1057 BreakInheritanceListStyle BreakInheritanceList;
1059 /// If ``true``, consecutive namespace declarations will be on the same
1060 /// line. If ``false``, each namespace is declared on a new line.
1063 /// namespace Foo { namespace Bar {
1073 /// If it does not fit on a single line, the overflowing namespaces get
1076 /// namespace Foo { namespace Bar {
1077 /// namespace Extra {
1080 bool CompactNamespaces;
1082 /// If the constructor initializers don't fit on a line, put each
1083 /// initializer on its own line.
1086 /// SomeClass::Constructor()
1087 /// : aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa) {
1092 /// SomeClass::Constructor()
1093 /// : aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaa),
1094 /// aaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa) {
1098 bool ConstructorInitializerAllOnOneLineOrOnePerLine;
1100 /// The number of characters to use for indentation of constructor
1101 /// initializer lists as well as inheritance lists.
1102 unsigned ConstructorInitializerIndentWidth;
1104 /// Indent width for line continuations.
1106 /// ContinuationIndentWidth: 2
1108 /// int i = // VeryVeryVeryVeryVeryLongComment
1109 /// longFunction( // Again a long comment
1112 unsigned ContinuationIndentWidth;
1114 /// If ``true``, format braced lists as best suited for C++11 braced
1117 /// Important differences:
1118 /// - No spaces inside the braced list.
1119 /// - No line break before the closing brace.
1120 /// - Indentation with the continuation indent, not with the block indent.
1122 /// Fundamentally, C++11 braced lists are formatted exactly like function
1123 /// calls would be formatted in their place. If the braced list follows a name
1124 /// (e.g. a type or variable name), clang-format formats as if the ``{}`` were
1125 /// the parentheses of a function call with that name. If there is no name,
1126 /// a zero-length name is assumed.
1129 /// vector<int> x{1, 2, 3, 4}; vs. vector<int> x{ 1, 2, 3, 4 };
1130 /// vector<T> x{{}, {}, {}, {}}; vector<T> x{ {}, {}, {}, {} };
1131 /// f(MyMap[{composite, key}]); f(MyMap[{ composite, key }]);
1132 /// new int[3]{1, 2, 3}; new int[3]{ 1, 2, 3 };
1134 bool Cpp11BracedListStyle;
1136 /// If ``true``, analyze the formatted file for the most common
1137 /// alignment of ``&`` and ``*``.
1138 /// Pointer and reference alignment styles are going to be updated according
1139 /// to the preferences found in the file.
1140 /// ``PointerAlignment`` is then used only as fallback.
1141 bool DerivePointerAlignment;
1143 /// Disables formatting completely.
1146 /// If ``true``, clang-format detects whether function calls and
1147 /// definitions are formatted with one parameter per line.
1149 /// Each call can be bin-packed, one-per-line or inconclusive. If it is
1150 /// inconclusive, e.g. completely on one line, but a decision needs to be
1151 /// made, clang-format analyzes whether there are other bin-packed cases in
1152 /// the input file and act accordingly.
1154 /// NOTE: This is an experimental flag, that might go away or be renamed. Do
1155 /// not use this in config files, etc. Use at your own risk.
1156 bool ExperimentalAutoDetectBinPacking;
1158 /// If ``true``, clang-format adds missing namespace end comments and
1159 /// fixes invalid existing ones.
1162 /// namespace a { vs. namespace a {
1164 /// } // namespace a }
1166 bool FixNamespaceComments;
1168 /// A vector of macros that should be interpreted as foreach loops
1169 /// instead of as function calls.
1171 /// These are expected to be macros of the form:
1173 /// FOREACH(<variable-declaration>, ...)
1177 /// In the .clang-format configuration file, this can be configured like:
1179 /// ForEachMacros: ['RANGES_FOR', 'FOREACH']
1182 /// For example: BOOST_FOREACH.
1183 std::vector<std::string> ForEachMacros;
1185 /// \brief A vector of macros that should be interpreted as type declarations
1186 /// instead of as function calls.
1188 /// These are expected to be macros of the form:
1193 /// In the .clang-format configuration file, this can be configured like:
1195 /// TypenameMacros: ['STACK_OF', 'LIST']
1198 /// For example: OpenSSL STACK_OF, BSD LIST_ENTRY.
1199 std::vector<std::string> TypenameMacros;
1201 /// A vector of macros that should be interpreted as complete
1204 /// Typical macros are expressions, and require a semi-colon to be
1205 /// added; sometimes this is not the case, and this allows to make
1206 /// clang-format aware of such cases.
1208 /// For example: Q_UNUSED
1209 std::vector<std::string> StatementMacros;
1211 /// A vector of macros which are used to open namespace blocks.
1213 /// These are expected to be macros of the form:
1215 /// NAMESPACE(<namespace-name>, ...) {
1216 /// <namespace-content>
1220 /// For example: TESTSUITE
1221 std::vector<std::string> NamespaceMacros;
1223 tooling::IncludeStyle IncludeStyle;
1225 /// Indent case labels one level from the switch statement.
1227 /// When ``false``, use the same indentation level as for the switch statement.
1228 /// Switch statement body is always indented one level more than case labels.
1231 /// switch (fool) { vs. switch (fool) {
1235 /// default: default:
1239 bool IndentCaseLabels;
1241 /// Options for indenting preprocessor directives.
1242 enum PPDirectiveIndentStyle {
1243 /// Does not indent any directives.
1252 /// Indents directives after the hash.
1261 /// Indents directives before the hash.
1272 /// The preprocessor directive indenting style to use.
1273 PPDirectiveIndentStyle IndentPPDirectives;
1275 /// The number of columns to use for indentation.
1281 /// if (true, false) {
1286 unsigned IndentWidth;
1288 /// Indent if a function definition or declaration is wrapped after the
1292 /// LoooooooooooooooooooooooooooooooooooooooongReturnType
1293 /// LoooooooooooooooooooooooooooooooongFunctionDeclaration();
1296 /// LoooooooooooooooooooooooooooooooooooooooongReturnType
1297 /// LoooooooooooooooooooooooooooooooongFunctionDeclaration();
1299 bool IndentWrappedFunctionNames;
1301 /// A vector of prefixes ordered by the desired groups for Java imports.
1303 /// Each group is separated by a newline. Static imports will also follow the
1304 /// same grouping convention above all non-static imports. One group's prefix
1305 /// can be a subset of another - the longest prefix is always matched. Within
1306 /// a group, the imports are ordered lexicographically.
1308 /// In the .clang-format configuration file, this can be configured like
1309 /// in the following yaml example. This will result in imports being
1310 /// formatted as in the Java example below.
1312 /// JavaImportGroups: ['com.example', 'com', 'org']
1316 /// import static com.example.function1;
1318 /// import static com.test.function2;
1320 /// import static org.example.function3;
1322 /// import com.example.ClassA;
1323 /// import com.example.Test;
1324 /// import com.example.a.ClassB;
1326 /// import com.test.ClassC;
1328 /// import org.example.ClassD;
1330 std::vector<std::string> JavaImportGroups;
1332 /// Quotation styles for JavaScript strings. Does not affect template
1334 enum JavaScriptQuoteStyle {
1335 /// Leave string quotes as they are.
1337 /// string1 = "foo";
1338 /// string2 = 'bar';
1341 /// Always use single quotes.
1343 /// string1 = 'foo';
1344 /// string2 = 'bar';
1347 /// Always use double quotes.
1349 /// string1 = "foo";
1350 /// string2 = "bar";
1355 /// The JavaScriptQuoteStyle to use for JavaScript strings.
1356 JavaScriptQuoteStyle JavaScriptQuotes;
1358 /// Whether to wrap JavaScript import/export statements.
1362 /// VeryLongImportsAreAnnoying,
1363 /// VeryLongImportsAreAnnoying,
1364 /// VeryLongImportsAreAnnoying,
1365 /// } from 'some/module.js'
1368 /// import {VeryLongImportsAreAnnoying, VeryLongImportsAreAnnoying, VeryLongImportsAreAnnoying,} from "some/module.js"
1370 bool JavaScriptWrapImports;
1372 /// If true, the empty line at the start of blocks is kept.
1375 /// if (foo) { vs. if (foo) {
1380 bool KeepEmptyLinesAtTheStartOfBlocks;
1382 /// Supported languages.
1384 /// When stored in a configuration file, specifies the language, that the
1385 /// configuration targets. When passed to the ``reformat()`` function, enables
1386 /// syntax features specific to the language.
1390 /// Should be used for C, C++.
1392 /// Should be used for C#.
1394 /// Should be used for Java.
1396 /// Should be used for JavaScript.
1398 /// Should be used for Objective-C, Objective-C++.
1400 /// Should be used for Protocol Buffers
1401 /// (https://developers.google.com/protocol-buffers/).
1403 /// Should be used for TableGen code.
1405 /// Should be used for Protocol Buffer messages in text format
1406 /// (https://developers.google.com/protocol-buffers/).
1409 bool isCpp() const { return Language == LK_Cpp || Language == LK_ObjC; }
1410 bool isCSharp() const { return Language == LK_CSharp; }
1412 /// Language, this format style is targeted at.
1413 LanguageKind Language;
1415 /// A regular expression matching macros that start a block.
1418 /// MacroBlockBegin: "^NS_MAP_BEGIN|\
1420 /// MacroBlockEnd: "^\
1422 /// NS_TABLE_.*_END$"
1430 /// NS_TABLE_FOO_END
1439 /// NS_TABLE_FOO_END
1441 std::string MacroBlockBegin;
1443 /// A regular expression matching macros that end a block.
1444 std::string MacroBlockEnd;
1446 /// The maximum number of consecutive empty lines to keep.
1448 /// MaxEmptyLinesToKeep: 1 vs. MaxEmptyLinesToKeep: 0
1449 /// int f() { int f() {
1450 /// int = 1; int i = 1;
1452 /// i = foo(); return i;
1457 unsigned MaxEmptyLinesToKeep;
1459 /// Different ways to indent namespace contents.
1460 enum NamespaceIndentationKind {
1461 /// Don't indent in namespaces.
1471 /// Indent only in inner namespaces (nested in other namespaces).
1481 /// Indent in all namespaces.
1493 /// The indentation used for namespaces.
1494 NamespaceIndentationKind NamespaceIndentation;
1496 /// Controls bin-packing Objective-C protocol conformance list
1497 /// items into as few lines as possible when they go over ``ColumnLimit``.
1499 /// If ``Auto`` (the default), delegates to the value in
1500 /// ``BinPackParameters``. If that is ``true``, bin-packs Objective-C
1501 /// protocol conformance list items into as few lines as possible
1502 /// whenever they go over ``ColumnLimit``.
1504 /// If ``Always``, always bin-packs Objective-C protocol conformance
1505 /// list items into as few lines as possible whenever they go over
1506 /// ``ColumnLimit``.
1508 /// If ``Never``, lays out Objective-C protocol conformance list items
1509 /// onto individual lines whenever they go over ``ColumnLimit``.
1512 /// Always (or Auto, if BinPackParameters=true):
1513 /// @interface ccccccccccccc () <
1514 /// ccccccccccccc, ccccccccccccc,
1515 /// ccccccccccccc, ccccccccccccc> {
1518 /// Never (or Auto, if BinPackParameters=false):
1519 /// @interface ddddddddddddd () <
1523 /// ddddddddddddd> {
1526 BinPackStyle ObjCBinPackProtocolList;
1528 /// The number of characters to use for indentation of ObjC blocks.
1530 /// ObjCBlockIndentWidth: 4
1532 /// [operation setCompletionBlock:^{
1533 /// [self onOperationDone];
1536 unsigned ObjCBlockIndentWidth;
1538 /// Add a space after ``@property`` in Objective-C, i.e. use
1539 /// ``@property (readonly)`` instead of ``@property(readonly)``.
1540 bool ObjCSpaceAfterProperty;
1542 /// Add a space in front of an Objective-C protocol list, i.e. use
1543 /// ``Foo <Protocol>`` instead of ``Foo<Protocol>``.
1544 bool ObjCSpaceBeforeProtocolList;
1546 /// The penalty for breaking around an assignment operator.
1547 unsigned PenaltyBreakAssignment;
1549 /// The penalty for breaking a function call after ``call(``.
1550 unsigned PenaltyBreakBeforeFirstCallParameter;
1552 /// The penalty for each line break introduced inside a comment.
1553 unsigned PenaltyBreakComment;
1555 /// The penalty for breaking before the first ``<<``.
1556 unsigned PenaltyBreakFirstLessLess;
1558 /// The penalty for each line break introduced inside a string literal.
1559 unsigned PenaltyBreakString;
1561 /// The penalty for breaking after template declaration.
1562 unsigned PenaltyBreakTemplateDeclaration;
1564 /// The penalty for each character outside of the column limit.
1565 unsigned PenaltyExcessCharacter;
1567 /// Penalty for putting the return type of a function onto its own
1569 unsigned PenaltyReturnTypeOnItsOwnLine;
1571 /// The ``&`` and ``*`` alignment style.
1572 enum PointerAlignmentStyle {
1573 /// Align pointer to the left.
1578 /// Align pointer to the right.
1583 /// Align pointer in the middle.
1590 /// Pointer and reference alignment style.
1591 PointerAlignmentStyle PointerAlignment;
1593 /// See documentation of ``RawStringFormats``.
1594 struct RawStringFormat {
1595 /// The language of this raw string.
1596 LanguageKind Language;
1597 /// A list of raw string delimiters that match this language.
1598 std::vector<std::string> Delimiters;
1599 /// A list of enclosing function names that match this language.
1600 std::vector<std::string> EnclosingFunctions;
1601 /// The canonical delimiter for this language.
1602 std::string CanonicalDelimiter;
1603 /// The style name on which this raw string format is based on.
1604 /// If not specified, the raw string format is based on the style that this
1605 /// format is based on.
1606 std::string BasedOnStyle;
1607 bool operator==(const RawStringFormat &Other) const {
1608 return Language == Other.Language && Delimiters == Other.Delimiters &&
1609 EnclosingFunctions == Other.EnclosingFunctions &&
1610 CanonicalDelimiter == Other.CanonicalDelimiter &&
1611 BasedOnStyle == Other.BasedOnStyle;
1615 /// Defines hints for detecting supported languages code blocks in raw
1618 /// A raw string with a matching delimiter or a matching enclosing function
1619 /// name will be reformatted assuming the specified language based on the
1620 /// style for that language defined in the .clang-format file. If no style has
1621 /// been defined in the .clang-format file for the specific language, a
1622 /// predefined style given by 'BasedOnStyle' is used. If 'BasedOnStyle' is not
1623 /// found, the formatting is based on llvm style. A matching delimiter takes
1624 /// precedence over a matching enclosing function name for determining the
1625 /// language of the raw string contents.
1627 /// If a canonical delimiter is specified, occurrences of other delimiters for
1628 /// the same language will be updated to the canonical if possible.
1630 /// There should be at most one specification per language and each delimiter
1631 /// and enclosing function should not occur in multiple specifications.
1633 /// To configure this in the .clang-format file, use:
1635 /// RawStringFormats:
1636 /// - Language: TextProto
1640 /// EnclosingFunctions:
1641 /// - 'PARSE_TEXT_PROTO'
1642 /// BasedOnStyle: google
1647 /// BasedOnStyle: llvm
1648 /// CanonicalDelimiter: 'cc'
1650 std::vector<RawStringFormat> RawStringFormats;
1652 /// If ``true``, clang-format will attempt to re-flow comments.
1655 /// // veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongComment with plenty of information
1656 /// /* second veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongComment with plenty of information */
1659 /// // veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongComment with plenty of
1661 /// /* second veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongComment with plenty of
1662 /// * information */
1664 bool ReflowComments;
1666 /// If ``true``, clang-format will sort ``#includes``.
1669 /// #include "b.h" vs. #include "a.h"
1670 /// #include "a.h" #include "b.h"
1674 /// If ``true``, clang-format will sort using declarations.
1676 /// The order of using declarations is defined as follows:
1677 /// Split the strings by "::" and discard any initial empty strings. The last
1678 /// element of each list is a non-namespace name; all others are namespace
1679 /// names. Sort the lists of names lexicographically, where the sort order of
1680 /// individual names is that all non-namespace names come before all namespace
1681 /// names, and within those groups, names are in case-insensitive
1682 /// lexicographic order.
1685 /// using std::cout; vs. using std::cin;
1686 /// using std::cin; using std::cout;
1688 bool SortUsingDeclarations;
1690 /// If ``true``, a space is inserted after C style casts.
1693 /// (int) i; vs. (int)i;
1695 bool SpaceAfterCStyleCast;
1697 /// If ``true``, a space is inserted after the logical not operator (``!``).
1700 /// ! someExpression(); vs. !someExpression();
1702 bool SpaceAfterLogicalNot;
1704 /// If \c true, a space will be inserted after the 'template' keyword.
1707 /// template <int> void foo(); vs. template<int> void foo();
1709 bool SpaceAfterTemplateKeyword;
1711 /// If ``false``, spaces will be removed before assignment operators.
1714 /// int a = 5; vs. int a=5;
1717 bool SpaceBeforeAssignmentOperators;
1719 /// If ``true``, a space will be inserted before a C++11 braced list
1720 /// used to initialize an object (after the preceding identifier or type).
1723 /// Foo foo { bar }; vs. Foo foo{ bar };
1725 /// vector<int> { 1, 2, 3 }; vector<int>{ 1, 2, 3 };
1726 /// new int[3] { 1, 2, 3 }; new int[3]{ 1, 2, 3 };
1728 bool SpaceBeforeCpp11BracedList;
1730 /// If ``false``, spaces will be removed before constructor initializer
1734 /// Foo::Foo() : a(a) {} Foo::Foo(): a(a) {}
1736 bool SpaceBeforeCtorInitializerColon;
1738 /// If ``false``, spaces will be removed before inheritance colon.
1741 /// class Foo : Bar {} vs. class Foo: Bar {}
1743 bool SpaceBeforeInheritanceColon;
1745 /// Different ways to put a space before opening parentheses.
1746 enum SpaceBeforeParensOptions {
1747 /// Never put a space before opening parentheses.
1756 /// Put a space before opening parentheses only after control statement
1757 /// keywords (``for/if/while...``).
1765 SBPO_ControlStatements,
1766 /// Put a space before opening parentheses only if the parentheses are not
1776 SBPO_NonEmptyParentheses,
1777 /// Always put a space before opening parentheses, except when it's
1778 /// prohibited by the syntax rules (in function-like macro definitions) or
1779 /// when determined by other style rules (after unary operators, opening
1780 /// parentheses, etc.)
1791 /// Defines in which cases to put a space before opening parentheses.
1792 SpaceBeforeParensOptions SpaceBeforeParens;
1794 /// If ``false``, spaces will be removed before range-based for loop
1798 /// for (auto v : values) {} vs. for(auto v: values) {}
1800 bool SpaceBeforeRangeBasedForLoopColon;
1802 /// If ``true``, spaces may be inserted into ``()``.
1805 /// void f( ) { vs. void f() {
1806 /// int x[] = {foo( ), bar( )}; int x[] = {foo(), bar()};
1807 /// if (true) { if (true) {
1812 bool SpaceInEmptyParentheses;
1814 /// The number of spaces before trailing line comments
1815 /// (``//`` - comments).
1817 /// This does not affect trailing block comments (``/*`` - comments) as
1818 /// those commonly have different usage patterns and a number of special
1821 /// SpacesBeforeTrailingComments: 3
1823 /// if (true) { // foo1
1828 unsigned SpacesBeforeTrailingComments;
1830 /// If ``true``, spaces will be inserted after ``<`` and before ``>``
1831 /// in template argument lists.
1834 /// static_cast< int >(arg); vs. static_cast<int>(arg);
1835 /// std::function< void(int) > fct; std::function<void(int)> fct;
1837 bool SpacesInAngles;
1839 /// If ``true``, spaces are inserted inside container literals (e.g.
1840 /// ObjC and Javascript array and dict literals).
1843 /// var arr = [ 1, 2, 3 ]; vs. var arr = [1, 2, 3];
1844 /// f({a : 1, b : 2, c : 3}); f({a: 1, b: 2, c: 3});
1846 bool SpacesInContainerLiterals;
1848 /// If ``true``, spaces may be inserted into C style casts.
1851 /// x = ( int32 )y vs. x = (int32)y
1853 bool SpacesInCStyleCastParentheses;
1855 /// If ``true``, spaces will be inserted after ``(`` and before ``)``.
1858 /// t f( Deleted & ) & = delete; vs. t f(Deleted &) & = delete;
1860 bool SpacesInParentheses;
1862 /// If ``true``, spaces will be inserted after ``[`` and before ``]``.
1863 /// Lambdas or unspecified size array declarations will not be affected.
1866 /// int a[ 5 ]; vs. int a[5];
1867 /// std::unique_ptr<int[]> foo() {} // Won't be affected
1869 bool SpacesInSquareBrackets;
1871 /// Supported language standards.
1872 enum LanguageStandard {
1873 /// Use C++03-compatible syntax.
1875 /// Use features of C++11, C++14 and C++1z (e.g. ``A<A<int>>`` instead of
1876 /// ``A<A<int> >``).
1878 /// Automatic detection based on the input.
1882 /// Format compatible with this standard, e.g. use ``A<A<int> >``
1883 /// instead of ``A<A<int>>`` for ``LS_Cpp03``.
1884 LanguageStandard Standard;
1886 /// The number of columns used for tab stops.
1889 /// Different ways to use tab in formatting.
1893 /// Use tabs only for indentation.
1895 /// Use tabs only for line continuation and indentation.
1896 UT_ForContinuationAndIndentation,
1897 /// Use tabs whenever we need to fill whitespace that spans at least from
1898 /// one tab stop to the next one.
1902 /// The way to use tab characters in the resulting file.
1905 bool operator==(const FormatStyle &R) const {
1906 return AccessModifierOffset == R.AccessModifierOffset &&
1907 AlignAfterOpenBracket == R.AlignAfterOpenBracket &&
1908 AlignConsecutiveAssignments == R.AlignConsecutiveAssignments &&
1909 AlignConsecutiveDeclarations == R.AlignConsecutiveDeclarations &&
1910 AlignEscapedNewlines == R.AlignEscapedNewlines &&
1911 AlignOperands == R.AlignOperands &&
1912 AlignTrailingComments == R.AlignTrailingComments &&
1913 AllowAllArgumentsOnNextLine == R.AllowAllArgumentsOnNextLine &&
1914 AllowAllConstructorInitializersOnNextLine ==
1915 R.AllowAllConstructorInitializersOnNextLine &&
1916 AllowAllParametersOfDeclarationOnNextLine ==
1917 R.AllowAllParametersOfDeclarationOnNextLine &&
1918 AllowShortBlocksOnASingleLine == R.AllowShortBlocksOnASingleLine &&
1919 AllowShortCaseLabelsOnASingleLine ==
1920 R.AllowShortCaseLabelsOnASingleLine &&
1921 AllowShortFunctionsOnASingleLine ==
1922 R.AllowShortFunctionsOnASingleLine &&
1923 AllowShortIfStatementsOnASingleLine ==
1924 R.AllowShortIfStatementsOnASingleLine &&
1925 AllowShortLambdasOnASingleLine == R.AllowShortLambdasOnASingleLine &&
1926 AllowShortLoopsOnASingleLine == R.AllowShortLoopsOnASingleLine &&
1927 AlwaysBreakAfterReturnType == R.AlwaysBreakAfterReturnType &&
1928 AlwaysBreakBeforeMultilineStrings ==
1929 R.AlwaysBreakBeforeMultilineStrings &&
1930 AlwaysBreakTemplateDeclarations ==
1931 R.AlwaysBreakTemplateDeclarations &&
1932 BinPackArguments == R.BinPackArguments &&
1933 BinPackParameters == R.BinPackParameters &&
1934 BreakBeforeBinaryOperators == R.BreakBeforeBinaryOperators &&
1935 BreakBeforeBraces == R.BreakBeforeBraces &&
1936 BreakBeforeTernaryOperators == R.BreakBeforeTernaryOperators &&
1937 BreakConstructorInitializers == R.BreakConstructorInitializers &&
1938 CompactNamespaces == R.CompactNamespaces &&
1939 BreakAfterJavaFieldAnnotations == R.BreakAfterJavaFieldAnnotations &&
1940 BreakStringLiterals == R.BreakStringLiterals &&
1941 ColumnLimit == R.ColumnLimit && CommentPragmas == R.CommentPragmas &&
1942 BreakInheritanceList == R.BreakInheritanceList &&
1943 ConstructorInitializerAllOnOneLineOrOnePerLine ==
1944 R.ConstructorInitializerAllOnOneLineOrOnePerLine &&
1945 ConstructorInitializerIndentWidth ==
1946 R.ConstructorInitializerIndentWidth &&
1947 ContinuationIndentWidth == R.ContinuationIndentWidth &&
1948 Cpp11BracedListStyle == R.Cpp11BracedListStyle &&
1949 DerivePointerAlignment == R.DerivePointerAlignment &&
1950 DisableFormat == R.DisableFormat &&
1951 ExperimentalAutoDetectBinPacking ==
1952 R.ExperimentalAutoDetectBinPacking &&
1953 FixNamespaceComments == R.FixNamespaceComments &&
1954 ForEachMacros == R.ForEachMacros &&
1955 IncludeStyle.IncludeBlocks == R.IncludeStyle.IncludeBlocks &&
1956 IncludeStyle.IncludeCategories == R.IncludeStyle.IncludeCategories &&
1957 IndentCaseLabels == R.IndentCaseLabels &&
1958 IndentPPDirectives == R.IndentPPDirectives &&
1959 IndentWidth == R.IndentWidth && Language == R.Language &&
1960 IndentWrappedFunctionNames == R.IndentWrappedFunctionNames &&
1961 JavaImportGroups == R.JavaImportGroups &&
1962 JavaScriptQuotes == R.JavaScriptQuotes &&
1963 JavaScriptWrapImports == R.JavaScriptWrapImports &&
1964 KeepEmptyLinesAtTheStartOfBlocks ==
1965 R.KeepEmptyLinesAtTheStartOfBlocks &&
1966 MacroBlockBegin == R.MacroBlockBegin &&
1967 MacroBlockEnd == R.MacroBlockEnd &&
1968 MaxEmptyLinesToKeep == R.MaxEmptyLinesToKeep &&
1969 NamespaceIndentation == R.NamespaceIndentation &&
1970 NamespaceMacros == R.NamespaceMacros &&
1971 ObjCBinPackProtocolList == R.ObjCBinPackProtocolList &&
1972 ObjCBlockIndentWidth == R.ObjCBlockIndentWidth &&
1973 ObjCSpaceAfterProperty == R.ObjCSpaceAfterProperty &&
1974 ObjCSpaceBeforeProtocolList == R.ObjCSpaceBeforeProtocolList &&
1975 PenaltyBreakAssignment == R.PenaltyBreakAssignment &&
1976 PenaltyBreakBeforeFirstCallParameter ==
1977 R.PenaltyBreakBeforeFirstCallParameter &&
1978 PenaltyBreakComment == R.PenaltyBreakComment &&
1979 PenaltyBreakFirstLessLess == R.PenaltyBreakFirstLessLess &&
1980 PenaltyBreakString == R.PenaltyBreakString &&
1981 PenaltyExcessCharacter == R.PenaltyExcessCharacter &&
1982 PenaltyReturnTypeOnItsOwnLine == R.PenaltyReturnTypeOnItsOwnLine &&
1983 PenaltyBreakTemplateDeclaration ==
1984 R.PenaltyBreakTemplateDeclaration &&
1985 PointerAlignment == R.PointerAlignment &&
1986 RawStringFormats == R.RawStringFormats &&
1987 SpaceAfterCStyleCast == R.SpaceAfterCStyleCast &&
1988 SpaceAfterLogicalNot == R.SpaceAfterLogicalNot &&
1989 SpaceAfterTemplateKeyword == R.SpaceAfterTemplateKeyword &&
1990 SpaceBeforeAssignmentOperators == R.SpaceBeforeAssignmentOperators &&
1991 SpaceBeforeCpp11BracedList == R.SpaceBeforeCpp11BracedList &&
1992 SpaceBeforeCtorInitializerColon ==
1993 R.SpaceBeforeCtorInitializerColon &&
1994 SpaceBeforeInheritanceColon == R.SpaceBeforeInheritanceColon &&
1995 SpaceBeforeParens == R.SpaceBeforeParens &&
1996 SpaceBeforeRangeBasedForLoopColon ==
1997 R.SpaceBeforeRangeBasedForLoopColon &&
1998 SpaceInEmptyParentheses == R.SpaceInEmptyParentheses &&
1999 SpacesBeforeTrailingComments == R.SpacesBeforeTrailingComments &&
2000 SpacesInAngles == R.SpacesInAngles &&
2001 SpacesInContainerLiterals == R.SpacesInContainerLiterals &&
2002 SpacesInCStyleCastParentheses == R.SpacesInCStyleCastParentheses &&
2003 SpacesInParentheses == R.SpacesInParentheses &&
2004 SpacesInSquareBrackets == R.SpacesInSquareBrackets &&
2005 Standard == R.Standard && TabWidth == R.TabWidth &&
2006 StatementMacros == R.StatementMacros && UseTab == R.UseTab &&
2007 TypenameMacros == R.TypenameMacros;
2010 llvm::Optional<FormatStyle> GetLanguageStyle(LanguageKind Language) const;
2012 // Stores per-language styles. A FormatStyle instance inside has an empty
2013 // StyleSet. A FormatStyle instance returned by the Get method has its
2014 // StyleSet set to a copy of the originating StyleSet, effectively keeping the
2015 // internal representation of that StyleSet alive.
2017 // The memory management and ownership reminds of a birds nest: chicks
2018 // leaving the nest take photos of the nest with them.
2019 struct FormatStyleSet {
2020 typedef std::map<FormatStyle::LanguageKind, FormatStyle> MapType;
2022 llvm::Optional<FormatStyle> Get(FormatStyle::LanguageKind Language) const;
2024 // Adds \p Style to this FormatStyleSet. Style must not have an associated
2026 // Style.Language should be different than LK_None. If this FormatStyleSet
2027 // already contains an entry for Style.Language, that gets replaced with the
2029 void Add(FormatStyle Style);
2031 // Clears this FormatStyleSet.
2035 std::shared_ptr<MapType> Styles;
2038 static FormatStyleSet BuildStyleSetFromConfiguration(
2039 const FormatStyle &MainStyle,
2040 const std::vector<FormatStyle> &ConfigurationStyles);
2043 FormatStyleSet StyleSet;
2045 friend std::error_code parseConfiguration(StringRef Text, FormatStyle *Style);
2048 /// Returns a format style complying with the LLVM coding standards:
2049 /// http://llvm.org/docs/CodingStandards.html.
2050 FormatStyle getLLVMStyle(
2051 FormatStyle::LanguageKind Language = FormatStyle::LanguageKind::LK_Cpp);
2053 /// Returns a format style complying with one of Google's style guides:
2054 /// http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml.
2055 /// http://google-styleguide.googlecode.com/svn/trunk/javascriptguide.xml.
2056 /// https://developers.google.com/protocol-buffers/docs/style.
2057 FormatStyle getGoogleStyle(FormatStyle::LanguageKind Language);
2059 /// Returns a format style complying with Chromium's style guide:
2060 /// http://www.chromium.org/developers/coding-style.
2061 FormatStyle getChromiumStyle(FormatStyle::LanguageKind Language);
2063 /// Returns a format style complying with Mozilla's style guide:
2064 /// https://developer.mozilla.org/en-US/docs/Developer_Guide/Coding_Style.
2065 FormatStyle getMozillaStyle();
2067 /// Returns a format style complying with Webkit's style guide:
2068 /// http://www.webkit.org/coding/coding-style.html
2069 FormatStyle getWebKitStyle();
2071 /// Returns a format style complying with GNU Coding Standards:
2072 /// http://www.gnu.org/prep/standards/standards.html
2073 FormatStyle getGNUStyle();
2075 /// Returns style indicating formatting should be not applied at all.
2076 FormatStyle getNoStyle();
2078 /// Gets a predefined style for the specified language by name.
2080 /// Currently supported names: LLVM, Google, Chromium, Mozilla. Names are
2081 /// compared case-insensitively.
2083 /// Returns ``true`` if the Style has been set.
2084 bool getPredefinedStyle(StringRef Name, FormatStyle::LanguageKind Language,
2085 FormatStyle *Style);
2087 /// Parse configuration from YAML-formatted text.
2089 /// Style->Language is used to get the base style, if the ``BasedOnStyle``
2090 /// option is present.
2092 /// The FormatStyleSet of Style is reset.
2094 /// When ``BasedOnStyle`` is not present, options not present in the YAML
2095 /// document, are retained in \p Style.
2096 std::error_code parseConfiguration(StringRef Text, FormatStyle *Style);
2098 /// Gets configuration in a YAML string.
2099 std::string configurationAsText(const FormatStyle &Style);
2101 /// Returns the replacements necessary to sort all ``#include`` blocks
2102 /// that are affected by ``Ranges``.
2103 tooling::Replacements sortIncludes(const FormatStyle &Style, StringRef Code,
2104 ArrayRef<tooling::Range> Ranges,
2106 unsigned *Cursor = nullptr);
2108 /// Returns the replacements corresponding to applying and formatting
2109 /// \p Replaces on success; otheriwse, return an llvm::Error carrying
2110 /// llvm::StringError.
2111 llvm::Expected<tooling::Replacements>
2112 formatReplacements(StringRef Code, const tooling::Replacements &Replaces,
2113 const FormatStyle &Style);
2115 /// Returns the replacements corresponding to applying \p Replaces and
2116 /// cleaning up the code after that on success; otherwise, return an llvm::Error
2117 /// carrying llvm::StringError.
2118 /// This also supports inserting/deleting C++ #include directives:
2119 /// - If a replacement has offset UINT_MAX, length 0, and a replacement text
2120 /// that is an #include directive, this will insert the #include into the
2121 /// correct block in the \p Code.
2122 /// - If a replacement has offset UINT_MAX, length 1, and a replacement text
2123 /// that is the name of the header to be removed, the header will be removed
2124 /// from \p Code if it exists.
2125 /// The include manipulation is done via `tooling::HeaderInclude`, see its
2126 /// documentation for more details on how include insertion points are found and
2127 /// what edits are produced.
2128 llvm::Expected<tooling::Replacements>
2129 cleanupAroundReplacements(StringRef Code, const tooling::Replacements &Replaces,
2130 const FormatStyle &Style);
2132 /// Represents the status of a formatting attempt.
2133 struct FormattingAttemptStatus {
2134 /// A value of ``false`` means that any of the affected ranges were not
2135 /// formatted due to a non-recoverable syntax error.
2136 bool FormatComplete = true;
2138 /// If ``FormatComplete`` is false, ``Line`` records a one-based
2139 /// original line number at which a syntax error might have occurred. This is
2140 /// based on a best-effort analysis and could be imprecise.
2144 /// Reformats the given \p Ranges in \p Code.
2146 /// Each range is extended on either end to its next bigger logic unit, i.e.
2147 /// everything that might influence its formatting or might be influenced by its
2150 /// Returns the ``Replacements`` necessary to make all \p Ranges comply with
2153 /// If ``Status`` is non-null, its value will be populated with the status of
2154 /// this formatting attempt. See \c FormattingAttemptStatus.
2155 tooling::Replacements reformat(const FormatStyle &Style, StringRef Code,
2156 ArrayRef<tooling::Range> Ranges,
2157 StringRef FileName = "<stdin>",
2158 FormattingAttemptStatus *Status = nullptr);
2160 /// Same as above, except if ``IncompleteFormat`` is non-null, its value
2161 /// will be set to true if any of the affected ranges were not formatted due to
2162 /// a non-recoverable syntax error.
2163 tooling::Replacements reformat(const FormatStyle &Style, StringRef Code,
2164 ArrayRef<tooling::Range> Ranges,
2166 bool *IncompleteFormat);
2168 /// Clean up any erroneous/redundant code in the given \p Ranges in \p
2171 /// Returns the ``Replacements`` that clean up all \p Ranges in \p Code.
2172 tooling::Replacements cleanup(const FormatStyle &Style, StringRef Code,
2173 ArrayRef<tooling::Range> Ranges,
2174 StringRef FileName = "<stdin>");
2176 /// Fix namespace end comments in the given \p Ranges in \p Code.
2178 /// Returns the ``Replacements`` that fix the namespace comments in all
2179 /// \p Ranges in \p Code.
2180 tooling::Replacements fixNamespaceEndComments(const FormatStyle &Style,
2182 ArrayRef<tooling::Range> Ranges,
2183 StringRef FileName = "<stdin>");
2185 /// Sort consecutive using declarations in the given \p Ranges in
2188 /// Returns the ``Replacements`` that sort the using declarations in all
2189 /// \p Ranges in \p Code.
2190 tooling::Replacements sortUsingDeclarations(const FormatStyle &Style,
2192 ArrayRef<tooling::Range> Ranges,
2193 StringRef FileName = "<stdin>");
2195 /// Returns the ``LangOpts`` that the formatter expects you to set.
2197 /// \param Style determines specific settings for lexing mode.
2198 LangOptions getFormattingLangOpts(const FormatStyle &Style = getLLVMStyle());
2200 /// Description to be used for help text for a ``llvm::cl`` option for
2201 /// specifying format style. The description is closely related to the operation
2202 /// of ``getStyle()``.
2203 extern const char *StyleOptionHelpDescription;
2205 /// The suggested format style to use by default. This allows tools using
2206 /// `getStyle` to have a consistent default style.
2207 /// Different builds can modify the value to the preferred styles.
2208 extern const char *DefaultFormatStyle;
2210 /// The suggested predefined style to use as the fallback style in `getStyle`.
2211 /// Different builds can modify the value to the preferred styles.
2212 extern const char *DefaultFallbackStyle;
2214 /// Construct a FormatStyle based on ``StyleName``.
2216 /// ``StyleName`` can take several forms:
2217 /// * "{<key>: <value>, ...}" - Set specic style parameters.
2218 /// * "<style name>" - One of the style names supported by
2219 /// getPredefinedStyle().
2220 /// * "file" - Load style configuration from a file called ``.clang-format``
2221 /// located in one of the parent directories of ``FileName`` or the current
2222 /// directory if ``FileName`` is empty.
2224 /// \param[in] StyleName Style name to interpret according to the description
2226 /// \param[in] FileName Path to start search for .clang-format if ``StyleName``
2228 /// \param[in] FallbackStyle The name of a predefined style used to fallback to
2229 /// in case \p StyleName is "file" and no file can be found.
2230 /// \param[in] Code The actual code to be formatted. Used to determine the
2231 /// language if the filename isn't sufficient.
2232 /// \param[in] FS The underlying file system, in which the file resides. By
2233 /// default, the file system is the real file system.
2235 /// \returns FormatStyle as specified by ``StyleName``. If ``StyleName`` is
2236 /// "file" and no file is found, returns ``FallbackStyle``. If no style could be
2237 /// determined, returns an Error.
2238 llvm::Expected<FormatStyle> getStyle(StringRef StyleName, StringRef FileName,
2239 StringRef FallbackStyle,
2240 StringRef Code = "",
2241 llvm::vfs::FileSystem *FS = nullptr);
2243 // Guesses the language from the ``FileName`` and ``Code`` to be formatted.
2244 // Defaults to FormatStyle::LK_Cpp.
2245 FormatStyle::LanguageKind guessLanguage(StringRef FileName, StringRef Code);
2247 // Returns a string representation of ``Language``.
2248 inline StringRef getLanguageName(FormatStyle::LanguageKind Language) {
2250 case FormatStyle::LK_Cpp:
2252 case FormatStyle::LK_CSharp:
2254 case FormatStyle::LK_ObjC:
2255 return "Objective-C";
2256 case FormatStyle::LK_Java:
2258 case FormatStyle::LK_JavaScript:
2259 return "JavaScript";
2260 case FormatStyle::LK_Proto:
2262 case FormatStyle::LK_TableGen:
2264 case FormatStyle::LK_TextProto:
2271 } // end namespace format
2272 } // end namespace clang
2276 struct is_error_code_enum<clang::format::ParseError> : std::true_type {};
2279 #endif // LLVM_CLANG_FORMAT_FORMAT_H