1 //===--- Format.h - Format C++ code -----------------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
11 /// Various functions to configurably format source code.
13 //===----------------------------------------------------------------------===//
15 #ifndef LLVM_CLANG_FORMAT_FORMAT_H
16 #define LLVM_CLANG_FORMAT_FORMAT_H
18 #include "clang/Basic/LangOptions.h"
19 #include "clang/Tooling/Core/Replacement.h"
20 #include "llvm/ADT/ArrayRef.h"
21 #include <system_error>
27 class DiagnosticConsumer;
35 enum class ParseError { Success = 0, Error, Unsuitable };
36 class ParseErrorCategory final : public std::error_category {
38 const char *name() const noexcept override;
39 std::string message(int EV) const override;
41 const std::error_category &getParseCategory();
42 std::error_code make_error_code(ParseError e);
44 /// \brief The ``FormatStyle`` is used to configure the formatting to follow
45 /// specific guidelines.
47 /// \brief The extra indent or outdent of access modifiers, e.g. ``public:``.
48 int AccessModifierOffset;
50 /// \brief Different styles for aligning after open brackets.
51 enum BracketAlignmentStyle {
52 /// \brief Align parameters on the open bracket, e.g.:
54 /// someLongFunction(argument1,
58 /// \brief Don't align, instead use ``ContinuationIndentWidth``, e.g.:
60 /// someLongFunction(argument1,
64 /// \brief Always break after an open bracket, if the parameters don't fit
65 /// on a single line, e.g.:
68 /// argument1, argument2);
73 /// \brief If ``true``, horizontally aligns arguments after an open bracket.
75 /// This applies to round brackets (parentheses), angle brackets and square
77 BracketAlignmentStyle AlignAfterOpenBracket;
79 /// \brief If ``true``, aligns consecutive assignments.
81 /// This will align the assignment operators of consecutive lines. This
82 /// will result in formattings like
88 bool AlignConsecutiveAssignments;
90 /// \brief If ``true``, aligns consecutive declarations.
92 /// This will align the declaration names of consecutive lines. This
93 /// will result in formattings like
97 /// std::string ccc = 23;
99 bool AlignConsecutiveDeclarations;
101 /// \brief Different styles for aligning escaped newlines.
102 enum EscapedNewlineAlignmentStyle {
103 /// \brief Don't align escaped newlines.
111 /// \brief Align escaped newlines as far left as possible.
122 /// \brief Align escaped newlines in the right-most column.
132 /// \brief Options for aligning backslashes in escaped newlines.
133 EscapedNewlineAlignmentStyle AlignEscapedNewlines;
135 /// \brief If ``true``, horizontally align operands of binary and ternary
138 /// Specifically, this aligns operands of a single expression that needs to be
139 /// split over multiple lines, e.g.:
141 /// int aaa = bbbbbbbbbbbbbbb +
146 /// \brief If ``true``, aligns trailing comments.
149 /// int a; // My comment a vs. int a; // My comment a
150 /// int b = 2; // comment b int b = 2; // comment about b
152 bool AlignTrailingComments;
154 /// \brief Allow putting all parameters of a function declaration onto
155 /// the next line even if ``BinPackParameters`` is ``false``.
158 /// myFunction(foo, vs. myFunction(foo, bar, plop);
162 bool AllowAllParametersOfDeclarationOnNextLine;
164 /// \brief Allows contracting simple braced statements to a single line.
166 /// E.g., this allows ``if (a) { return; }`` to be put on a single line.
167 bool AllowShortBlocksOnASingleLine;
169 /// \brief If ``true``, short case labels will be contracted to a single line.
172 /// switch (a) { vs. switch (a) {
173 /// case 1: x = 1; break; case 1:
174 /// case 2: return; x = 1;
180 bool AllowShortCaseLabelsOnASingleLine;
182 /// \brief Different styles for merging short functions containing at most one
184 enum ShortFunctionStyle {
185 /// \brief Never merge functions into a single line.
187 /// \brief Only merge functions defined inside a class. Same as "inline",
188 /// except it does not implies "empty": i.e. top level empty functions
189 /// are not merged either.
192 /// void f() { foo(); }
201 /// \brief Only merge empty functions.
209 /// \brief Only merge functions defined inside a class. Implies "empty".
212 /// void f() { foo(); }
220 /// \brief Merge all functions fitting on a single line.
223 /// void f() { foo(); }
225 /// void f() { bar(); }
230 /// \brief Dependent on the value, ``int f() { return 0; }`` can be put on a
232 ShortFunctionStyle AllowShortFunctionsOnASingleLine;
234 /// \brief If ``true``, ``if (a) return;`` can be put on a single line.
235 bool AllowShortIfStatementsOnASingleLine;
237 /// \brief If ``true``, ``while (true) continue;`` can be put on a single
239 bool AllowShortLoopsOnASingleLine;
241 /// \brief Different ways to break after the function definition return type.
242 /// This option is **deprecated** and is retained for backwards compatibility.
243 enum DefinitionReturnTypeBreakingStyle {
244 /// Break after return type automatically.
245 /// ``PenaltyReturnTypeOnItsOwnLine`` is taken into account.
247 /// Always break after the return type.
249 /// Always break after the return types of top-level functions.
253 /// \brief Different ways to break after the function definition or
254 /// declaration return type.
255 enum ReturnTypeBreakingStyle {
256 /// Break after return type automatically.
257 /// ``PenaltyReturnTypeOnItsOwnLine`` is taken into account.
260 /// int f() { return 0; };
263 /// int f() { return 1; }
266 /// Always break after the return type.
282 /// Always break after the return types of top-level functions.
285 /// int f() { return 0; };
295 /// Always break after the return type of function definitions.
310 /// Always break after the return type of top-level definitions.
313 /// int f() { return 0; };
321 RTBS_TopLevelDefinitions,
324 /// \brief The function definition return type breaking style to use. This
325 /// option is **deprecated** and is retained for backwards compatibility.
326 DefinitionReturnTypeBreakingStyle AlwaysBreakAfterDefinitionReturnType;
328 /// \brief The function declaration return type breaking style to use.
329 ReturnTypeBreakingStyle AlwaysBreakAfterReturnType;
331 /// \brief If ``true``, always break before multiline string literals.
333 /// This flag is mean to make cases where there are multiple multiline strings
334 /// in a file look more consistent. Thus, it will only take effect if wrapping
335 /// the string at that point leads to it being indented
336 /// ``ContinuationIndentWidth`` spaces from the start of the line.
339 /// aaaa = vs. aaaa = "bbbb"
343 bool AlwaysBreakBeforeMultilineStrings;
345 /// \brief If ``true``, always break after the ``template<...>`` of a template
349 /// template <typename T> vs. template <typename T> class C {};
352 bool AlwaysBreakTemplateDeclarations;
354 /// \brief If ``false``, a function call's arguments will either be all on the
355 /// same line or will have one line each.
359 /// f(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaa,
360 /// aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);
365 /// f(aaaaaaaaaaaaaaaaaaaa,
366 /// aaaaaaaaaaaaaaaaaaaa,
367 /// aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);
370 bool BinPackArguments;
372 /// \brief If ``false``, a function declaration's or function definition's
373 /// parameters will either all be on the same line or will have one line each.
376 /// void f(int aaaaaaaaaaaaaaaaaaaa, int aaaaaaaaaaaaaaaaaaaa,
377 /// int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}
380 /// void f(int aaaaaaaaaaaaaaaaaaaa,
381 /// int aaaaaaaaaaaaaaaaaaaa,
382 /// int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}
384 bool BinPackParameters;
386 /// \brief The style of breaking before or after binary operators.
387 enum BinaryOperatorStyle {
388 /// Break after operators.
390 /// LooooooooooongType loooooooooooooooooooooongVariable =
391 /// someLooooooooooooooooongFunction();
393 /// bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +
394 /// aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==
395 /// aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa &&
396 /// aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >
397 /// ccccccccccccccccccccccccccccccccccccccccc;
400 /// Break before operators that aren't assignments.
402 /// LooooooooooongType loooooooooooooooooooooongVariable =
403 /// someLooooooooooooooooongFunction();
405 /// bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
406 /// + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
407 /// == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
408 /// && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
409 /// > ccccccccccccccccccccccccccccccccccccccccc;
412 /// Break before operators.
414 /// LooooooooooongType loooooooooooooooooooooongVariable
415 /// = someLooooooooooooooooongFunction();
417 /// bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
418 /// + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
419 /// == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
420 /// && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
421 /// > ccccccccccccccccccccccccccccccccccccccccc;
426 /// \brief The way to wrap binary operators.
427 BinaryOperatorStyle BreakBeforeBinaryOperators;
429 /// \brief Different ways to attach braces to their surrounding context.
430 enum BraceBreakingStyle {
431 /// Always attach braces to surrounding context.
437 /// void foo() { bar(); }
442 /// enum X : int { A, B };
445 /// Like ``Attach``, but break before braces on function, namespace and
446 /// class definitions.
452 /// void foo() { bar(); }
459 /// enum X : int { A, B };
462 /// Like ``Attach``, but break before braces on enum, function, and record
469 /// void foo() { bar(); }
476 /// enum X : int { A, B };
479 /// Like ``Attach``, but break before function definitions, ``catch``, and
486 /// void foo() { bar(); }
500 /// Always break before braces.
507 /// void foo() { bar(); }
514 /// enum X : int { A, B };
517 /// Always break before braces and add an extra level of indentation to
518 /// braces of control statements, not to those of class, function
519 /// or other definitions.
528 /// void foo() { bar(); }
545 /// Like ``Attach``, but break before functions.
551 /// void foo() { bar(); }
557 /// enum X : int { A, B };
560 /// Configure each individual brace in `BraceWrapping`.
564 /// \brief The brace breaking style to use.
565 BraceBreakingStyle BreakBeforeBraces;
567 /// \brief Precise control over the wrapping of braces.
569 /// # Should be declared this way:
570 /// BreakBeforeBraces: Custom
574 struct BraceWrappingFlags {
575 /// \brief Wrap class definitions.
585 /// \brief Wrap control statements (``if``/``for``/``while``/``switch``/..).
592 /// for (int i = 0; i < 10; ++i)
599 /// for (int i = 0; i < 10; ++i) {
602 bool AfterControlStatement;
603 /// \brief Wrap enum definitions.
612 /// enum X : int { B };
615 /// \brief Wrap function definitions.
631 /// \brief Wrap namespace definitions.
647 /// \brief Wrap ObjC definitions (``@autoreleasepool``, interfaces, ..).
648 bool AfterObjCDeclaration;
649 /// \brief Wrap struct definitions.
663 /// \brief Wrap union definitions.
677 /// \brief Wrap before ``catch``.
693 /// \brief Wrap before ``else``.
707 /// \brief Indent the wrapped braces themselves.
709 /// \brief If ``false``, empty function body can be put on a single line.
710 /// This option is used only if the opening brace of the function has
711 /// already been wrapped, i.e. the `AfterFunction` brace wrapping mode is
712 /// set, and the function could/should not be put on a single line (as per
713 /// `AllowShortFunctionsOnASingleLine` and constructor formatting options).
715 /// int f() vs. inf f()
720 bool SplitEmptyFunction;
721 /// \brief If ``false``, empty record (e.g. class, struct or union) body
722 /// can be put on a single line. This option is used only if the opening
723 /// brace of the record has already been wrapped, i.e. the `AfterClass`
724 /// (for classes) brace wrapping mode is set.
726 /// class Foo vs. class Foo
731 bool SplitEmptyRecord;
732 /// \brief If ``false``, empty namespace body can be put on a single line.
733 /// This option is used only if the opening brace of the namespace has
734 /// already been wrapped, i.e. the `AfterNamespace` brace wrapping mode is
737 /// namespace Foo vs. namespace Foo
742 bool SplitEmptyNamespace;
745 /// \brief Control of individual brace wrapping cases.
747 /// If ``BreakBeforeBraces`` is set to ``BS_Custom``, use this to specify how
748 /// each individual brace case should be handled. Otherwise, this is ignored.
749 BraceWrappingFlags BraceWrapping;
751 /// \brief If ``true``, ternary operators will be placed after line breaks.
754 /// veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongDescription
756 /// : SecondValueVeryVeryVeryVeryLong;
759 /// veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongDescription ?
761 /// SecondValueVeryVeryVeryVeryLong;
763 bool BreakBeforeTernaryOperators;
765 /// \brief Different ways to break initializers.
766 enum BreakConstructorInitializersStyle {
767 /// Break constructor initializers before the colon and after the commas.
770 /// : initializer1(),
774 /// Break constructor initializers before the colon and commas, and align
775 /// the commas with the colon.
782 /// Break constructor initializers after the colon and commas.
791 /// \brief The constructor initializers style to use.
792 BreakConstructorInitializersStyle BreakConstructorInitializers;
794 /// \brief Break after each annotation on a field in Java files.
797 /// @Partial vs. @Partial @Mock DataLoad loader;
801 bool BreakAfterJavaFieldAnnotations;
803 /// \brief Allow breaking string literals when formatting.
804 bool BreakStringLiterals;
806 /// \brief The column limit.
808 /// A column limit of ``0`` means that there is no column limit. In this case,
809 /// clang-format will respect the input's line breaking decisions within
810 /// statements unless they contradict other rules.
811 unsigned ColumnLimit;
813 /// \brief A regular expression that describes comments with special meaning,
814 /// which should not be split into lines or otherwise changed.
816 /// // CommentPragmas: '^ FOOBAR pragma:'
817 /// // Will leave the following line unaffected
818 /// #include <vector> // FOOBAR pragma: keep
820 std::string CommentPragmas;
822 /// \brief If ``true``, in the class inheritance expression clang-format will
823 /// break before ``:`` and ``,`` if there is multiple inheritance.
826 /// class MyClass vs. class MyClass : public X, public Y {
831 bool BreakBeforeInheritanceComma;
833 /// \brief If ``true``, consecutive namespace declarations will be on the same
834 /// line. If ``false``, each namespace is declared on a new line.
837 /// namespace Foo { namespace Bar {
847 /// If it does not fit on a single line, the overflowing namespaces get
850 /// namespace Foo { namespace Bar {
851 /// namespace Extra {
854 bool CompactNamespaces;
856 /// \brief If the constructor initializers don't fit on a line, put each
857 /// initializer on its own line.
860 /// SomeClass::Constructor()
861 /// : aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa) {
866 /// SomeClass::Constructor()
867 /// : aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaa),
868 /// aaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa) {
872 bool ConstructorInitializerAllOnOneLineOrOnePerLine;
874 /// \brief The number of characters to use for indentation of constructor
875 /// initializer lists.
876 unsigned ConstructorInitializerIndentWidth;
878 /// \brief Indent width for line continuations.
880 /// ContinuationIndentWidth: 2
882 /// int i = // VeryVeryVeryVeryVeryLongComment
883 /// longFunction( // Again a long comment
886 unsigned ContinuationIndentWidth;
888 /// \brief If ``true``, format braced lists as best suited for C++11 braced
891 /// Important differences:
892 /// - No spaces inside the braced list.
893 /// - No line break before the closing brace.
894 /// - Indentation with the continuation indent, not with the block indent.
896 /// Fundamentally, C++11 braced lists are formatted exactly like function
897 /// calls would be formatted in their place. If the braced list follows a name
898 /// (e.g. a type or variable name), clang-format formats as if the ``{}`` were
899 /// the parentheses of a function call with that name. If there is no name,
900 /// a zero-length name is assumed.
903 /// vector<int> x{1, 2, 3, 4}; vs. vector<int> x{ 1, 2, 3, 4 };
904 /// vector<T> x{{}, {}, {}, {}}; vector<T> x{ {}, {}, {}, {} };
905 /// f(MyMap[{composite, key}]); f(MyMap[{ composite, key }]);
906 /// new int[3]{1, 2, 3}; new int[3]{ 1, 2, 3 };
908 bool Cpp11BracedListStyle;
910 /// \brief If ``true``, analyze the formatted file for the most common
911 /// alignment of ``&`` and ``*``.
912 /// Pointer and reference alignment styles are going to be updated according
913 /// to the preferences found in the file.
914 /// ``PointerAlignment`` is then used only as fallback.
915 bool DerivePointerAlignment;
917 /// \brief Disables formatting completely.
920 /// \brief If ``true``, clang-format detects whether function calls and
921 /// definitions are formatted with one parameter per line.
923 /// Each call can be bin-packed, one-per-line or inconclusive. If it is
924 /// inconclusive, e.g. completely on one line, but a decision needs to be
925 /// made, clang-format analyzes whether there are other bin-packed cases in
926 /// the input file and act accordingly.
928 /// NOTE: This is an experimental flag, that might go away or be renamed. Do
929 /// not use this in config files, etc. Use at your own risk.
930 bool ExperimentalAutoDetectBinPacking;
932 /// \brief If ``true``, clang-format adds missing namespace end comments and
933 /// fixes invalid existing ones.
936 /// namespace a { vs. namespace a {
938 /// } // namespace a; }
940 bool FixNamespaceComments;
942 /// \brief A vector of macros that should be interpreted as foreach loops
943 /// instead of as function calls.
945 /// These are expected to be macros of the form:
947 /// FOREACH(<variable-declaration>, ...)
951 /// In the .clang-format configuration file, this can be configured like:
953 /// ForEachMacros: ['RANGES_FOR', 'FOREACH']
956 /// For example: BOOST_FOREACH.
957 std::vector<std::string> ForEachMacros;
959 /// \brief See documentation of ``IncludeCategories``.
960 struct IncludeCategory {
961 /// \brief The regular expression that this category matches.
963 /// \brief The priority to assign to this category.
965 bool operator==(const IncludeCategory &Other) const {
966 return Regex == Other.Regex && Priority == Other.Priority;
970 /// \brief Regular expressions denoting the different ``#include`` categories
971 /// used for ordering ``#includes``.
973 /// These regular expressions are matched against the filename of an include
974 /// (including the <> or "") in order. The value belonging to the first
975 /// matching regular expression is assigned and ``#includes`` are sorted first
976 /// according to increasing category number and then alphabetically within
979 /// If none of the regular expressions match, INT_MAX is assigned as
980 /// category. The main header for a source file automatically gets category 0.
981 /// so that it is generally kept at the beginning of the ``#includes``
982 /// (http://llvm.org/docs/CodingStandards.html#include-style). However, you
983 /// can also assign negative priorities if you have certain headers that
984 /// always need to be first.
986 /// To configure this in the .clang-format file, use:
988 /// IncludeCategories:
989 /// - Regex: '^"(llvm|llvm-c|clang|clang-c)/'
991 /// - Regex: '^(<|"(gtest|gmock|isl|json)/)'
996 std::vector<IncludeCategory> IncludeCategories;
998 /// \brief Specify a regular expression of suffixes that are allowed in the
999 /// file-to-main-include mapping.
1001 /// When guessing whether a #include is the "main" include (to assign
1002 /// category 0, see above), use this regex of allowed suffixes to the header
1003 /// stem. A partial match is done, so that:
1004 /// - "" means "arbitrary suffix"
1005 /// - "$" means "no suffix"
1007 /// For example, if configured to "(_test)?$", then a header a.h would be seen
1008 /// as the "main" include in both a.cc and a_test.cc.
1009 std::string IncludeIsMainRegex;
1011 /// \brief Indent case labels one level from the switch statement.
1013 /// When ``false``, use the same indentation level as for the switch statement.
1014 /// Switch statement body is always indented one level more than case labels.
1017 /// switch (fool) { vs. switch (fool) {
1021 /// default: default:
1025 bool IndentCaseLabels;
1027 /// \brief The number of columns to use for indentation.
1033 /// if (true, false) {
1038 unsigned IndentWidth;
1040 /// \brief Indent if a function definition or declaration is wrapped after the
1044 /// LoooooooooooooooooooooooooooooooooooooooongReturnType
1045 /// LoooooooooooooooooooooooooooooooongFunctionDeclaration();
1048 /// LoooooooooooooooooooooooooooooooooooooooongReturnType
1049 /// LoooooooooooooooooooooooooooooooongFunctionDeclaration();
1051 bool IndentWrappedFunctionNames;
1053 /// \brief Quotation styles for JavaScript strings. Does not affect template
1055 enum JavaScriptQuoteStyle {
1056 /// Leave string quotes as they are.
1058 /// string1 = "foo";
1059 /// string2 = 'bar';
1062 /// Always use single quotes.
1064 /// string1 = 'foo';
1065 /// string2 = 'bar';
1068 /// Always use double quotes.
1070 /// string1 = "foo";
1071 /// string2 = "bar";
1076 /// \brief The JavaScriptQuoteStyle to use for JavaScript strings.
1077 JavaScriptQuoteStyle JavaScriptQuotes;
1079 /// \brief Whether to wrap JavaScript import/export statements.
1083 /// VeryLongImportsAreAnnoying,
1084 /// VeryLongImportsAreAnnoying,
1085 /// VeryLongImportsAreAnnoying,
1086 /// } from 'some/module.js'
1089 /// import {VeryLongImportsAreAnnoying, VeryLongImportsAreAnnoying, VeryLongImportsAreAnnoying,} from "some/module.js"
1091 bool JavaScriptWrapImports;
1093 /// \brief If true, the empty line at the start of blocks is kept.
1096 /// if (foo) { vs. if (foo) {
1101 bool KeepEmptyLinesAtTheStartOfBlocks;
1103 /// \brief Supported languages.
1105 /// When stored in a configuration file, specifies the language, that the
1106 /// configuration targets. When passed to the ``reformat()`` function, enables
1107 /// syntax features specific to the language.
1111 /// Should be used for C, C++.
1113 /// Should be used for Java.
1115 /// Should be used for JavaScript.
1117 /// Should be used for Objective-C, Objective-C++.
1119 /// Should be used for Protocol Buffers
1120 /// (https://developers.google.com/protocol-buffers/).
1122 /// Should be used for TableGen code.
1124 /// Should be used for Protocol Buffer messages in text format
1125 /// (https://developers.google.com/protocol-buffers/).
1128 bool isCpp() const { return Language == LK_Cpp || Language == LK_ObjC; }
1130 /// \brief Language, this format style is targeted at.
1131 LanguageKind Language;
1133 /// \brief A regular expression matching macros that start a block.
1136 /// MacroBlockBegin: "^NS_MAP_BEGIN|\
1138 /// MacroBlockEnd: "^\
1140 /// NS_TABLE_.*_END$"
1148 /// NS_TABLE_FOO_END
1157 /// NS_TABLE_FOO_END
1159 std::string MacroBlockBegin;
1161 /// \brief A regular expression matching macros that end a block.
1162 std::string MacroBlockEnd;
1164 /// \brief The maximum number of consecutive empty lines to keep.
1166 /// MaxEmptyLinesToKeep: 1 vs. MaxEmptyLinesToKeep: 0
1167 /// int f() { int f() {
1168 /// int = 1; int i = 1;
1170 /// i = foo(); return i;
1175 unsigned MaxEmptyLinesToKeep;
1177 /// \brief Different ways to indent namespace contents.
1178 enum NamespaceIndentationKind {
1179 /// Don't indent in namespaces.
1189 /// Indent only in inner namespaces (nested in other namespaces).
1199 /// Indent in all namespaces.
1211 /// \brief The indentation used for namespaces.
1212 NamespaceIndentationKind NamespaceIndentation;
1214 /// \brief The number of characters to use for indentation of ObjC blocks.
1216 /// ObjCBlockIndentWidth: 4
1218 /// [operation setCompletionBlock:^{
1219 /// [self onOperationDone];
1222 unsigned ObjCBlockIndentWidth;
1224 /// \brief Add a space after ``@property`` in Objective-C, i.e. use
1225 /// ``@property (readonly)`` instead of ``@property(readonly)``.
1226 bool ObjCSpaceAfterProperty;
1228 /// \brief Add a space in front of an Objective-C protocol list, i.e. use
1229 /// ``Foo <Protocol>`` instead of ``Foo<Protocol>``.
1230 bool ObjCSpaceBeforeProtocolList;
1232 /// \brief The penalty for breaking around an assignment operator.
1233 unsigned PenaltyBreakAssignment;
1235 /// \brief The penalty for breaking a function call after ``call(``.
1236 unsigned PenaltyBreakBeforeFirstCallParameter;
1238 /// \brief The penalty for each line break introduced inside a comment.
1239 unsigned PenaltyBreakComment;
1241 /// \brief The penalty for breaking before the first ``<<``.
1242 unsigned PenaltyBreakFirstLessLess;
1244 /// \brief The penalty for each line break introduced inside a string literal.
1245 unsigned PenaltyBreakString;
1247 /// \brief The penalty for each character outside of the column limit.
1248 unsigned PenaltyExcessCharacter;
1250 /// \brief Penalty for putting the return type of a function onto its own
1252 unsigned PenaltyReturnTypeOnItsOwnLine;
1254 /// \brief The ``&`` and ``*`` alignment style.
1255 enum PointerAlignmentStyle {
1256 /// Align pointer to the left.
1261 /// Align pointer to the right.
1266 /// Align pointer in the middle.
1273 /// \brief Pointer and reference alignment style.
1274 PointerAlignmentStyle PointerAlignment;
1276 /// \brief If ``true``, clang-format will attempt to re-flow comments.
1279 /// // veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongComment with plenty of information
1280 /// /* second veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongComment with plenty of information */
1283 /// // veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongComment with plenty of
1285 /// /* second veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongComment with plenty of
1286 /// * information */
1288 bool ReflowComments;
1290 /// \brief If ``true``, clang-format will sort ``#includes``.
1293 /// #include "b.h" vs. #include "a.h"
1294 /// #include "a.h" #include "b.h"
1298 /// \brief If ``true``, clang-format will sort using declarations.
1301 /// using std::cout; vs. using std::cin;
1302 /// using std::cin; using std::cout;
1304 bool SortUsingDeclarations;
1306 /// \brief If ``true``, a space is inserted after C style casts.
1309 /// (int)i; vs. (int) i;
1311 bool SpaceAfterCStyleCast;
1313 /// \brief If \c true, a space will be inserted after the 'template' keyword.
1316 /// template <int> void foo(); vs. template<int> void foo();
1318 bool SpaceAfterTemplateKeyword;
1320 /// \brief If ``false``, spaces will be removed before assignment operators.
1323 /// int a = 5; vs. int a=5;
1326 bool SpaceBeforeAssignmentOperators;
1328 /// \brief Different ways to put a space before opening parentheses.
1329 enum SpaceBeforeParensOptions {
1330 /// Never put a space before opening parentheses.
1339 /// Put a space before opening parentheses only after control statement
1340 /// keywords (``for/if/while...``).
1348 SBPO_ControlStatements,
1349 /// Always put a space before opening parentheses, except when it's
1350 /// prohibited by the syntax rules (in function-like macro definitions) or
1351 /// when determined by other style rules (after unary operators, opening
1352 /// parentheses, etc.)
1363 /// \brief Defines in which cases to put a space before opening parentheses.
1364 SpaceBeforeParensOptions SpaceBeforeParens;
1366 /// \brief If ``true``, spaces may be inserted into ``()``.
1369 /// void f( ) { vs. void f() {
1370 /// int x[] = {foo( ), bar( )}; int x[] = {foo(), bar()};
1371 /// if (true) { if (true) {
1376 bool SpaceInEmptyParentheses;
1378 /// \brief The number of spaces before trailing line comments
1379 /// (``//`` - comments).
1381 /// This does not affect trailing block comments (``/*`` - comments) as
1382 /// those commonly have different usage patterns and a number of special
1385 /// SpacesBeforeTrailingComments: 3
1387 /// if (true) { // foo1
1392 unsigned SpacesBeforeTrailingComments;
1394 /// \brief If ``true``, spaces will be inserted after ``<`` and before ``>``
1395 /// in template argument lists.
1398 /// static_cast< int >(arg); vs. static_cast<int>(arg);
1399 /// std::function< void(int) > fct; std::function<void(int)> fct;
1401 bool SpacesInAngles;
1403 /// \brief If ``true``, spaces are inserted inside container literals (e.g.
1404 /// ObjC and Javascript array and dict literals).
1407 /// var arr = [ 1, 2, 3 ]; vs. var arr = [1, 2, 3];
1408 /// f({a : 1, b : 2, c : 3}); f({a: 1, b: 2, c: 3});
1410 bool SpacesInContainerLiterals;
1412 /// \brief If ``true``, spaces may be inserted into C style casts.
1415 /// x = ( int32 )y vs. x = (int32)y
1417 bool SpacesInCStyleCastParentheses;
1419 /// \brief If ``true``, spaces will be inserted after ``(`` and before ``)``.
1422 /// t f( Deleted & ) & = delete; vs. t f(Deleted &) & = delete;
1424 bool SpacesInParentheses;
1426 /// \brief If ``true``, spaces will be inserted after ``[`` and before ``]``.
1427 /// Lambdas or unspecified size array declarations will not be affected.
1430 /// int a[ 5 ]; vs. int a[5];
1431 /// std::unique_ptr<int[]> foo() {} // Won't be affected
1433 bool SpacesInSquareBrackets;
1435 /// \brief Supported language standards.
1436 enum LanguageStandard {
1437 /// Use C++03-compatible syntax.
1439 /// Use features of C++11, C++14 and C++1z (e.g. ``A<A<int>>`` instead of
1440 /// ``A<A<int> >``).
1442 /// Automatic detection based on the input.
1446 /// \brief Format compatible with this standard, e.g. use ``A<A<int> >``
1447 /// instead of ``A<A<int>>`` for ``LS_Cpp03``.
1448 LanguageStandard Standard;
1450 /// \brief The number of columns used for tab stops.
1453 /// \brief Different ways to use tab in formatting.
1457 /// Use tabs only for indentation.
1459 /// Use tabs only for line continuation and indentation.
1460 UT_ForContinuationAndIndentation,
1461 /// Use tabs whenever we need to fill whitespace that spans at least from
1462 /// one tab stop to the next one.
1466 /// \brief The way to use tab characters in the resulting file.
1469 bool operator==(const FormatStyle &R) const {
1470 return AccessModifierOffset == R.AccessModifierOffset &&
1471 AlignAfterOpenBracket == R.AlignAfterOpenBracket &&
1472 AlignConsecutiveAssignments == R.AlignConsecutiveAssignments &&
1473 AlignConsecutiveDeclarations == R.AlignConsecutiveDeclarations &&
1474 AlignEscapedNewlines == R.AlignEscapedNewlines &&
1475 AlignOperands == R.AlignOperands &&
1476 AlignTrailingComments == R.AlignTrailingComments &&
1477 AllowAllParametersOfDeclarationOnNextLine ==
1478 R.AllowAllParametersOfDeclarationOnNextLine &&
1479 AllowShortBlocksOnASingleLine == R.AllowShortBlocksOnASingleLine &&
1480 AllowShortCaseLabelsOnASingleLine ==
1481 R.AllowShortCaseLabelsOnASingleLine &&
1482 AllowShortFunctionsOnASingleLine ==
1483 R.AllowShortFunctionsOnASingleLine &&
1484 AllowShortIfStatementsOnASingleLine ==
1485 R.AllowShortIfStatementsOnASingleLine &&
1486 AllowShortLoopsOnASingleLine == R.AllowShortLoopsOnASingleLine &&
1487 AlwaysBreakAfterReturnType == R.AlwaysBreakAfterReturnType &&
1488 AlwaysBreakBeforeMultilineStrings ==
1489 R.AlwaysBreakBeforeMultilineStrings &&
1490 AlwaysBreakTemplateDeclarations ==
1491 R.AlwaysBreakTemplateDeclarations &&
1492 BinPackArguments == R.BinPackArguments &&
1493 BinPackParameters == R.BinPackParameters &&
1494 BreakBeforeBinaryOperators == R.BreakBeforeBinaryOperators &&
1495 BreakBeforeBraces == R.BreakBeforeBraces &&
1496 BreakBeforeTernaryOperators == R.BreakBeforeTernaryOperators &&
1497 BreakConstructorInitializers == R.BreakConstructorInitializers &&
1498 CompactNamespaces == R.CompactNamespaces &&
1499 BreakAfterJavaFieldAnnotations == R.BreakAfterJavaFieldAnnotations &&
1500 BreakStringLiterals == R.BreakStringLiterals &&
1501 ColumnLimit == R.ColumnLimit && CommentPragmas == R.CommentPragmas &&
1502 BreakBeforeInheritanceComma == R.BreakBeforeInheritanceComma &&
1503 ConstructorInitializerAllOnOneLineOrOnePerLine ==
1504 R.ConstructorInitializerAllOnOneLineOrOnePerLine &&
1505 ConstructorInitializerIndentWidth ==
1506 R.ConstructorInitializerIndentWidth &&
1507 ContinuationIndentWidth == R.ContinuationIndentWidth &&
1508 Cpp11BracedListStyle == R.Cpp11BracedListStyle &&
1509 DerivePointerAlignment == R.DerivePointerAlignment &&
1510 DisableFormat == R.DisableFormat &&
1511 ExperimentalAutoDetectBinPacking ==
1512 R.ExperimentalAutoDetectBinPacking &&
1513 FixNamespaceComments == R.FixNamespaceComments &&
1514 ForEachMacros == R.ForEachMacros &&
1515 IncludeCategories == R.IncludeCategories &&
1516 IndentCaseLabels == R.IndentCaseLabels &&
1517 IndentWidth == R.IndentWidth && Language == R.Language &&
1518 IndentWrappedFunctionNames == R.IndentWrappedFunctionNames &&
1519 JavaScriptQuotes == R.JavaScriptQuotes &&
1520 JavaScriptWrapImports == R.JavaScriptWrapImports &&
1521 KeepEmptyLinesAtTheStartOfBlocks ==
1522 R.KeepEmptyLinesAtTheStartOfBlocks &&
1523 MacroBlockBegin == R.MacroBlockBegin &&
1524 MacroBlockEnd == R.MacroBlockEnd &&
1525 MaxEmptyLinesToKeep == R.MaxEmptyLinesToKeep &&
1526 NamespaceIndentation == R.NamespaceIndentation &&
1527 ObjCBlockIndentWidth == R.ObjCBlockIndentWidth &&
1528 ObjCSpaceAfterProperty == R.ObjCSpaceAfterProperty &&
1529 ObjCSpaceBeforeProtocolList == R.ObjCSpaceBeforeProtocolList &&
1530 PenaltyBreakAssignment ==
1531 R.PenaltyBreakAssignment &&
1532 PenaltyBreakBeforeFirstCallParameter ==
1533 R.PenaltyBreakBeforeFirstCallParameter &&
1534 PenaltyBreakComment == R.PenaltyBreakComment &&
1535 PenaltyBreakFirstLessLess == R.PenaltyBreakFirstLessLess &&
1536 PenaltyBreakString == R.PenaltyBreakString &&
1537 PenaltyExcessCharacter == R.PenaltyExcessCharacter &&
1538 PenaltyReturnTypeOnItsOwnLine == R.PenaltyReturnTypeOnItsOwnLine &&
1539 PointerAlignment == R.PointerAlignment &&
1540 SpaceAfterCStyleCast == R.SpaceAfterCStyleCast &&
1541 SpaceAfterTemplateKeyword == R.SpaceAfterTemplateKeyword &&
1542 SpaceBeforeAssignmentOperators == R.SpaceBeforeAssignmentOperators &&
1543 SpaceBeforeParens == R.SpaceBeforeParens &&
1544 SpaceInEmptyParentheses == R.SpaceInEmptyParentheses &&
1545 SpacesBeforeTrailingComments == R.SpacesBeforeTrailingComments &&
1546 SpacesInAngles == R.SpacesInAngles &&
1547 SpacesInContainerLiterals == R.SpacesInContainerLiterals &&
1548 SpacesInCStyleCastParentheses == R.SpacesInCStyleCastParentheses &&
1549 SpacesInParentheses == R.SpacesInParentheses &&
1550 SpacesInSquareBrackets == R.SpacesInSquareBrackets &&
1551 Standard == R.Standard && TabWidth == R.TabWidth &&
1556 /// \brief Returns a format style complying with the LLVM coding standards:
1557 /// http://llvm.org/docs/CodingStandards.html.
1558 FormatStyle getLLVMStyle();
1560 /// \brief Returns a format style complying with one of Google's style guides:
1561 /// http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml.
1562 /// http://google-styleguide.googlecode.com/svn/trunk/javascriptguide.xml.
1563 /// https://developers.google.com/protocol-buffers/docs/style.
1564 FormatStyle getGoogleStyle(FormatStyle::LanguageKind Language);
1566 /// \brief Returns a format style complying with Chromium's style guide:
1567 /// http://www.chromium.org/developers/coding-style.
1568 FormatStyle getChromiumStyle(FormatStyle::LanguageKind Language);
1570 /// \brief Returns a format style complying with Mozilla's style guide:
1571 /// https://developer.mozilla.org/en-US/docs/Developer_Guide/Coding_Style.
1572 FormatStyle getMozillaStyle();
1574 /// \brief Returns a format style complying with Webkit's style guide:
1575 /// http://www.webkit.org/coding/coding-style.html
1576 FormatStyle getWebKitStyle();
1578 /// \brief Returns a format style complying with GNU Coding Standards:
1579 /// http://www.gnu.org/prep/standards/standards.html
1580 FormatStyle getGNUStyle();
1582 /// \brief Returns style indicating formatting should be not applied at all.
1583 FormatStyle getNoStyle();
1585 /// \brief Gets a predefined style for the specified language by name.
1587 /// Currently supported names: LLVM, Google, Chromium, Mozilla. Names are
1588 /// compared case-insensitively.
1590 /// Returns ``true`` if the Style has been set.
1591 bool getPredefinedStyle(StringRef Name, FormatStyle::LanguageKind Language,
1592 FormatStyle *Style);
1594 /// \brief Parse configuration from YAML-formatted text.
1596 /// Style->Language is used to get the base style, if the ``BasedOnStyle``
1597 /// option is present.
1599 /// When ``BasedOnStyle`` is not present, options not present in the YAML
1600 /// document, are retained in \p Style.
1601 std::error_code parseConfiguration(StringRef Text, FormatStyle *Style);
1603 /// \brief Gets configuration in a YAML string.
1604 std::string configurationAsText(const FormatStyle &Style);
1606 /// \brief Returns the replacements necessary to sort all ``#include`` blocks
1607 /// that are affected by ``Ranges``.
1608 tooling::Replacements sortIncludes(const FormatStyle &Style, StringRef Code,
1609 ArrayRef<tooling::Range> Ranges,
1611 unsigned *Cursor = nullptr);
1613 /// \brief Returns the replacements corresponding to applying and formatting
1614 /// \p Replaces on success; otheriwse, return an llvm::Error carrying
1615 /// llvm::StringError.
1616 llvm::Expected<tooling::Replacements>
1617 formatReplacements(StringRef Code, const tooling::Replacements &Replaces,
1618 const FormatStyle &Style);
1620 /// \brief Returns the replacements corresponding to applying \p Replaces and
1621 /// cleaning up the code after that on success; otherwise, return an llvm::Error
1622 /// carrying llvm::StringError.
1623 /// This also supports inserting/deleting C++ #include directives:
1624 /// - If a replacement has offset UINT_MAX, length 0, and a replacement text
1625 /// that is an #include directive, this will insert the #include into the
1626 /// correct block in the \p Code. When searching for points to insert new
1627 /// header, this ignores #include's after the #include block(s) in the
1628 /// beginning of a file to avoid inserting headers into code sections where
1629 /// new #include's should not be added by default. These code sections
1631 /// - raw string literals (containing #include).
1633 /// - Special #include's among declarations (e.g. functions).
1634 /// - If a replacement has offset UINT_MAX, length 1, and a replacement text
1635 /// that is the name of the header to be removed, the header will be removed
1636 /// from \p Code if it exists.
1637 llvm::Expected<tooling::Replacements>
1638 cleanupAroundReplacements(StringRef Code, const tooling::Replacements &Replaces,
1639 const FormatStyle &Style);
1641 /// \brief Represents the status of a formatting attempt.
1642 struct FormattingAttemptStatus {
1643 /// \brief A value of ``false`` means that any of the affected ranges were not
1644 /// formatted due to a non-recoverable syntax error.
1645 bool FormatComplete = true;
1647 /// \brief If ``FormatComplete`` is false, ``Line`` records a one-based
1648 /// original line number at which a syntax error might have occurred. This is
1649 /// based on a best-effort analysis and could be imprecise.
1653 /// \brief Reformats the given \p Ranges in \p Code.
1655 /// Each range is extended on either end to its next bigger logic unit, i.e.
1656 /// everything that might influence its formatting or might be influenced by its
1659 /// Returns the ``Replacements`` necessary to make all \p Ranges comply with
1662 /// If ``Status`` is non-null, its value will be populated with the status of
1663 /// this formatting attempt. See \c FormattingAttemptStatus.
1664 tooling::Replacements reformat(const FormatStyle &Style, StringRef Code,
1665 ArrayRef<tooling::Range> Ranges,
1666 StringRef FileName = "<stdin>",
1667 FormattingAttemptStatus *Status = nullptr);
1669 /// \brief Same as above, except if ``IncompleteFormat`` is non-null, its value
1670 /// will be set to true if any of the affected ranges were not formatted due to
1671 /// a non-recoverable syntax error.
1672 tooling::Replacements reformat(const FormatStyle &Style, StringRef Code,
1673 ArrayRef<tooling::Range> Ranges,
1675 bool *IncompleteFormat);
1677 /// \brief Clean up any erroneous/redundant code in the given \p Ranges in \p
1680 /// Returns the ``Replacements`` that clean up all \p Ranges in \p Code.
1681 tooling::Replacements cleanup(const FormatStyle &Style, StringRef Code,
1682 ArrayRef<tooling::Range> Ranges,
1683 StringRef FileName = "<stdin>");
1685 /// \brief Fix namespace end comments in the given \p Ranges in \p Code.
1687 /// Returns the ``Replacements`` that fix the namespace comments in all
1688 /// \p Ranges in \p Code.
1689 tooling::Replacements fixNamespaceEndComments(const FormatStyle &Style,
1691 ArrayRef<tooling::Range> Ranges,
1692 StringRef FileName = "<stdin>");
1694 /// \brief Sort consecutive using declarations in the given \p Ranges in
1697 /// Returns the ``Replacements`` that sort the using declarations in all
1698 /// \p Ranges in \p Code.
1699 tooling::Replacements sortUsingDeclarations(const FormatStyle &Style,
1701 ArrayRef<tooling::Range> Ranges,
1702 StringRef FileName = "<stdin>");
1704 /// \brief Returns the ``LangOpts`` that the formatter expects you to set.
1706 /// \param Style determines specific settings for lexing mode.
1707 LangOptions getFormattingLangOpts(const FormatStyle &Style = getLLVMStyle());
1709 /// \brief Description to be used for help text for a ``llvm::cl`` option for
1710 /// specifying format style. The description is closely related to the operation
1711 /// of ``getStyle()``.
1712 extern const char *StyleOptionHelpDescription;
1714 /// \brief Construct a FormatStyle based on ``StyleName``.
1716 /// ``StyleName`` can take several forms:
1717 /// * "{<key>: <value>, ...}" - Set specic style parameters.
1718 /// * "<style name>" - One of the style names supported by
1719 /// getPredefinedStyle().
1720 /// * "file" - Load style configuration from a file called ``.clang-format``
1721 /// located in one of the parent directories of ``FileName`` or the current
1722 /// directory if ``FileName`` is empty.
1724 /// \param[in] StyleName Style name to interpret according to the description
1726 /// \param[in] FileName Path to start search for .clang-format if ``StyleName``
1728 /// \param[in] FallbackStyle The name of a predefined style used to fallback to
1729 /// in case \p StyleName is "file" and no file can be found.
1730 /// \param[in] Code The actual code to be formatted. Used to determine the
1731 /// language if the filename isn't sufficient.
1732 /// \param[in] FS The underlying file system, in which the file resides. By
1733 /// default, the file system is the real file system.
1735 /// \returns FormatStyle as specified by ``StyleName``. If ``StyleName`` is
1736 /// "file" and no file is found, returns ``FallbackStyle``. If no style could be
1737 /// determined, returns an Error.
1738 llvm::Expected<FormatStyle> getStyle(StringRef StyleName, StringRef FileName,
1739 StringRef FallbackStyle,
1740 StringRef Code = "",
1741 vfs::FileSystem *FS = nullptr);
1743 // \brief Returns a string representation of ``Language``.
1744 inline StringRef getLanguageName(FormatStyle::LanguageKind Language) {
1746 case FormatStyle::LK_Cpp:
1748 case FormatStyle::LK_ObjC:
1749 return "Objective-C";
1750 case FormatStyle::LK_Java:
1752 case FormatStyle::LK_JavaScript:
1753 return "JavaScript";
1754 case FormatStyle::LK_Proto:
1756 case FormatStyle::LK_TextProto:
1763 } // end namespace format
1764 } // end namespace clang
1768 struct is_error_code_enum<clang::format::ParseError> : std::true_type {};
1771 #endif // LLVM_CLANG_FORMAT_FORMAT_H