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 If ``true``, aligns escaped newlines as far left as possible.
102 /// Otherwise puts them into the right-most column.
116 bool AlignEscapedNewlinesLeft;
118 /// \brief If ``true``, horizontally align operands of binary and ternary
121 /// Specifically, this aligns operands of a single expression that needs to be
122 /// split over multiple lines, e.g.:
124 /// int aaa = bbbbbbbbbbbbbbb +
129 /// \brief If ``true``, aligns trailing comments.
132 /// int a; // My comment a vs. int a; // My comment a
133 /// int b = 2; // comment b int b = 2; // comment about b
135 bool AlignTrailingComments;
137 /// \brief Allow putting all parameters of a function declaration onto
138 /// the next line even if ``BinPackParameters`` is ``false``.
141 /// myFunction(foo, vs. myFunction(foo, bar, plop);
145 bool AllowAllParametersOfDeclarationOnNextLine;
147 /// \brief Allows contracting simple braced statements to a single line.
149 /// E.g., this allows ``if (a) { return; }`` to be put on a single line.
150 bool AllowShortBlocksOnASingleLine;
152 /// \brief If ``true``, short case labels will be contracted to a single line.
155 /// switch (a) { vs. switch (a) {
156 /// case 1: x = 1; break; case 1:
157 /// case 2: return; x = 1;
163 bool AllowShortCaseLabelsOnASingleLine;
165 /// \brief Different styles for merging short functions containing at most one
167 enum ShortFunctionStyle {
168 /// \brief Never merge functions into a single line.
170 /// \brief Only merge empty functions.
172 /// void f() { bar(); }
178 /// \brief Only merge functions defined inside a class. Implies "empty".
181 /// void f() { foo(); }
185 /// \brief Merge all functions fitting on a single line.
188 /// void f() { foo(); }
190 /// void f() { bar(); }
195 /// \brief Dependent on the value, ``int f() { return 0; }`` can be put on a
197 ShortFunctionStyle AllowShortFunctionsOnASingleLine;
199 /// \brief If ``true``, ``if (a) return;`` can be put on a single line.
200 bool AllowShortIfStatementsOnASingleLine;
202 /// \brief If ``true``, ``while (true) continue;`` can be put on a single
204 bool AllowShortLoopsOnASingleLine;
206 /// \brief Different ways to break after the function definition return type.
207 /// This option is **deprecated** and is retained for backwards compatibility.
208 enum DefinitionReturnTypeBreakingStyle {
209 /// Break after return type automatically.
210 /// ``PenaltyReturnTypeOnItsOwnLine`` is taken into account.
212 /// Always break after the return type.
214 /// Always break after the return types of top-level functions.
218 /// \brief Different ways to break after the function definition or
219 /// declaration return type.
220 enum ReturnTypeBreakingStyle {
221 /// Break after return type automatically.
222 /// ``PenaltyReturnTypeOnItsOwnLine`` is taken into account.
225 /// int f() { return 0; };
228 /// int f() { return 1; }
231 /// Always break after the return type.
247 /// Always break after the return types of top-level functions.
250 /// int f() { return 0; };
260 /// Always break after the return type of function definitions.
275 /// Always break after the return type of top-level definitions.
278 /// int f() { return 0; };
286 RTBS_TopLevelDefinitions,
289 /// \brief The function definition return type breaking style to use. This
290 /// option is **deprecated** and is retained for backwards compatibility.
291 DefinitionReturnTypeBreakingStyle AlwaysBreakAfterDefinitionReturnType;
293 /// \brief The function declaration return type breaking style to use.
294 ReturnTypeBreakingStyle AlwaysBreakAfterReturnType;
296 /// \brief If ``true``, always break before multiline string literals.
298 /// This flag is mean to make cases where there are multiple multiline strings
299 /// in a file look more consistent. Thus, it will only take effect if wrapping
300 /// the string at that point leads to it being indented
301 /// ``ContinuationIndentWidth`` spaces from the start of the line.
304 /// aaaa = vs. aaaa = "bbbb"
308 bool AlwaysBreakBeforeMultilineStrings;
310 /// \brief If ``true``, always break after the ``template<...>`` of a template
314 /// template <typename T> vs. template <typename T> class C {};
317 bool AlwaysBreakTemplateDeclarations;
319 /// \brief If ``false``, a function call's arguments will either be all on the
320 /// same line or will have one line each.
324 /// f(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaa,
325 /// aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);
330 /// f(aaaaaaaaaaaaaaaaaaaa,
331 /// aaaaaaaaaaaaaaaaaaaa,
332 /// aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);
335 bool BinPackArguments;
337 /// \brief If ``false``, a function declaration's or function definition's
338 /// parameters will either all be on the same line or will have one line each.
341 /// void f(int aaaaaaaaaaaaaaaaaaaa, int aaaaaaaaaaaaaaaaaaaa,
342 /// int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}
345 /// void f(int aaaaaaaaaaaaaaaaaaaa,
346 /// int aaaaaaaaaaaaaaaaaaaa,
347 /// int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}
349 bool BinPackParameters;
351 /// \brief The style of breaking before or after binary operators.
352 enum BinaryOperatorStyle {
353 /// Break after operators.
355 /// LooooooooooongType loooooooooooooooooooooongVariable =
356 /// someLooooooooooooooooongFunction();
358 /// bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +
359 /// aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==
360 /// aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa &&
361 /// aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >
362 /// ccccccccccccccccccccccccccccccccccccccccc;
365 /// Break before operators that aren't assignments.
367 /// LooooooooooongType loooooooooooooooooooooongVariable =
368 /// someLooooooooooooooooongFunction();
370 /// bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
371 /// + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
372 /// == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
373 /// && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
374 /// > ccccccccccccccccccccccccccccccccccccccccc;
377 /// Break before operators.
379 /// LooooooooooongType loooooooooooooooooooooongVariable
380 /// = someLooooooooooooooooongFunction();
382 /// bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
383 /// + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
384 /// == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
385 /// && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
386 /// > ccccccccccccccccccccccccccccccccccccccccc;
391 /// \brief The way to wrap binary operators.
392 BinaryOperatorStyle BreakBeforeBinaryOperators;
394 /// \brief Different ways to attach braces to their surrounding context.
395 enum BraceBreakingStyle {
396 /// Always attach braces to surrounding context.
402 /// void foo() { bar(); }
407 /// enum X : int { A, B };
410 /// Like ``Attach``, but break before braces on function, namespace and
411 /// class definitions.
417 /// void foo() { bar(); }
424 /// enum X : int { A, B };
427 /// Like ``Attach``, but break before braces on enum, function, and record
434 /// void foo() { bar(); }
441 /// enum X : int { A, B };
444 /// Like ``Attach``, but break before function definitions, ``catch``, and
451 /// void foo() { bar(); }
465 /// Always break before braces.
472 /// void foo() { bar(); }
479 /// enum X : int { A, B };
482 /// Always break before braces and add an extra level of indentation to
483 /// braces of control statements, not to those of class, function
484 /// or other definitions.
493 /// void foo() { bar(); }
510 /// Like ``Attach``, but break before functions.
516 /// void foo() { bar(); }
522 /// enum X : int { A, B };
525 /// Configure each individual brace in `BraceWrapping`.
529 /// \brief The brace breaking style to use.
530 BraceBreakingStyle BreakBeforeBraces;
532 /// \brief Precise control over the wrapping of braces.
534 /// # Should be declared this way:
535 /// BreakBeforeBraces: Custom
539 struct BraceWrappingFlags {
540 /// \brief Wrap class definitions.
550 /// \brief Wrap control statements (``if``/``for``/``while``/``switch``/..).
557 /// for (int i = 0; i < 10; ++i)
564 /// for (int i = 0; i < 10; ++i) {
567 bool AfterControlStatement;
568 /// \brief Wrap enum definitions.
577 /// enum X : int { B };
580 /// \brief Wrap function definitions.
596 /// \brief Wrap namespace definitions.
612 /// \brief Wrap ObjC definitions (``@autoreleasepool``, interfaces, ..).
613 bool AfterObjCDeclaration;
614 /// \brief Wrap struct definitions.
628 /// \brief Wrap union definitions.
642 /// \brief Wrap before ``catch``.
658 /// \brief Wrap before ``else``.
672 /// \brief Indent the wrapped braces themselves.
676 /// \brief Control of individual brace wrapping cases.
678 /// If ``BreakBeforeBraces`` is set to ``BS_Custom``, use this to specify how
679 /// each individual brace case should be handled. Otherwise, this is ignored.
680 BraceWrappingFlags BraceWrapping;
682 /// \brief If ``true``, ternary operators will be placed after line breaks.
685 /// veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongDescription
687 /// : SecondValueVeryVeryVeryVeryLong;
690 /// veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongDescription ?
692 /// SecondValueVeryVeryVeryVeryLong;
694 bool BreakBeforeTernaryOperators;
696 /// \brief Always break constructor initializers before commas and align
697 /// the commas with the colon.
700 /// SomeClass::Constructor() vs. SomeClass::Constructor() : a(a),
705 bool BreakConstructorInitializersBeforeComma;
707 /// \brief Break after each annotation on a field in Java files.
710 /// @Partial vs. @Partial @Mock DataLoad loader;
714 bool BreakAfterJavaFieldAnnotations;
716 /// \brief Allow breaking string literals when formatting.
717 bool BreakStringLiterals;
719 /// \brief The column limit.
721 /// A column limit of ``0`` means that there is no column limit. In this case,
722 /// clang-format will respect the input's line breaking decisions within
723 /// statements unless they contradict other rules.
724 unsigned ColumnLimit;
726 /// \brief A regular expression that describes comments with special meaning,
727 /// which should not be split into lines or otherwise changed.
729 /// // CommentPragmas: '^ FOOBAR pragma:'
730 /// // Will leave the following line unaffected
731 /// #include <vector> // FOOBAR pragma: keep
733 std::string CommentPragmas;
735 /// \brief If ``true``, in the class inheritance expression clang-format will
736 /// break before ``:`` and ``,`` if there is multiple inheritance.
739 /// class MyClass vs. class MyClass : public X, public Y {
744 bool BreakBeforeInheritanceComma;
746 /// \brief If the constructor initializers don't fit on a line, put each
747 /// initializer on its own line.
750 /// SomeClass::Constructor()
751 /// : aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa) {
756 /// SomeClass::Constructor()
757 /// : aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaa),
758 /// aaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa) {
762 bool ConstructorInitializerAllOnOneLineOrOnePerLine;
764 /// \brief The number of characters to use for indentation of constructor
765 /// initializer lists.
766 unsigned ConstructorInitializerIndentWidth;
768 /// \brief Indent width for line continuations.
770 /// ContinuationIndentWidth: 2
772 /// int i = // VeryVeryVeryVeryVeryLongComment
773 /// longFunction( // Again a long comment
776 unsigned ContinuationIndentWidth;
778 /// \brief If ``true``, format braced lists as best suited for C++11 braced
781 /// Important differences:
782 /// - No spaces inside the braced list.
783 /// - No line break before the closing brace.
784 /// - Indentation with the continuation indent, not with the block indent.
786 /// Fundamentally, C++11 braced lists are formatted exactly like function
787 /// calls would be formatted in their place. If the braced list follows a name
788 /// (e.g. a type or variable name), clang-format formats as if the ``{}`` were
789 /// the parentheses of a function call with that name. If there is no name,
790 /// a zero-length name is assumed.
793 /// vector<int> x{1, 2, 3, 4}; vs. vector<int> x{ 1, 2, 3, 4 };
794 /// vector<T> x{{}, {}, {}, {}}; vector<T> x{ {}, {}, {}, {} };
795 /// f(MyMap[{composite, key}]); f(MyMap[{ composite, key }]);
796 /// new int[3]{1, 2, 3}; new int[3]{ 1, 2, 3 };
798 bool Cpp11BracedListStyle;
800 /// \brief If ``true``, analyze the formatted file for the most common
801 /// alignment of ``&`` and ``*``.
802 /// Pointer and reference alignment styles are going to be updated according
803 /// to the preferences found in the file.
804 /// ``PointerAlignment`` is then used only as fallback.
805 bool DerivePointerAlignment;
807 /// \brief Disables formatting completely.
810 /// \brief If ``true``, clang-format detects whether function calls and
811 /// definitions are formatted with one parameter per line.
813 /// Each call can be bin-packed, one-per-line or inconclusive. If it is
814 /// inconclusive, e.g. completely on one line, but a decision needs to be
815 /// made, clang-format analyzes whether there are other bin-packed cases in
816 /// the input file and act accordingly.
818 /// NOTE: This is an experimental flag, that might go away or be renamed. Do
819 /// not use this in config files, etc. Use at your own risk.
820 bool ExperimentalAutoDetectBinPacking;
822 /// \brief If ``true``, clang-format adds missing namespace end comments and
823 /// fixes invalid existing ones.
826 /// namespace a { vs. namespace a {
828 /// } // namespace a; }
830 bool FixNamespaceComments;
832 /// \brief A vector of macros that should be interpreted as foreach loops
833 /// instead of as function calls.
835 /// These are expected to be macros of the form:
837 /// FOREACH(<variable-declaration>, ...)
841 /// In the .clang-format configuration file, this can be configured like:
843 /// ForEachMacros: ['RANGES_FOR', 'FOREACH']
846 /// For example: BOOST_FOREACH.
847 std::vector<std::string> ForEachMacros;
849 /// \brief See documentation of ``IncludeCategories``.
850 struct IncludeCategory {
851 /// \brief The regular expression that this category matches.
853 /// \brief The priority to assign to this category.
855 bool operator==(const IncludeCategory &Other) const {
856 return Regex == Other.Regex && Priority == Other.Priority;
860 /// \brief Regular expressions denoting the different ``#include`` categories
861 /// used for ordering ``#includes``.
863 /// These regular expressions are matched against the filename of an include
864 /// (including the <> or "") in order. The value belonging to the first
865 /// matching regular expression is assigned and ``#includes`` are sorted first
866 /// according to increasing category number and then alphabetically within
869 /// If none of the regular expressions match, INT_MAX is assigned as
870 /// category. The main header for a source file automatically gets category 0.
871 /// so that it is generally kept at the beginning of the ``#includes``
872 /// (http://llvm.org/docs/CodingStandards.html#include-style). However, you
873 /// can also assign negative priorities if you have certain headers that
874 /// always need to be first.
876 /// To configure this in the .clang-format file, use:
878 /// IncludeCategories:
879 /// - Regex: '^"(llvm|llvm-c|clang|clang-c)/'
881 /// - Regex: '^(<|"(gtest|isl|json)/)'
886 std::vector<IncludeCategory> IncludeCategories;
888 /// \brief Specify a regular expression of suffixes that are allowed in the
889 /// file-to-main-include mapping.
891 /// When guessing whether a #include is the "main" include (to assign
892 /// category 0, see above), use this regex of allowed suffixes to the header
893 /// stem. A partial match is done, so that:
894 /// - "" means "arbitrary suffix"
895 /// - "$" means "no suffix"
897 /// For example, if configured to "(_test)?$", then a header a.h would be seen
898 /// as the "main" include in both a.cc and a_test.cc.
899 std::string IncludeIsMainRegex;
901 /// \brief Indent case labels one level from the switch statement.
903 /// When ``false``, use the same indentation level as for the switch statement.
904 /// Switch statement body is always indented one level more than case labels.
907 /// switch (fool) { vs. switch (fool) {
911 /// default: default:
915 bool IndentCaseLabels;
917 /// \brief The number of columns to use for indentation.
923 /// if (true, false) {
928 unsigned IndentWidth;
930 /// \brief Indent if a function definition or declaration is wrapped after the
934 /// LoooooooooooooooooooooooooooooooooooooooongReturnType
935 /// LoooooooooooooooooooooooooooooooongFunctionDeclaration();
938 /// LoooooooooooooooooooooooooooooooooooooooongReturnType
939 /// LoooooooooooooooooooooooooooooooongFunctionDeclaration();
941 bool IndentWrappedFunctionNames;
943 /// \brief Quotation styles for JavaScript strings. Does not affect template
945 enum JavaScriptQuoteStyle {
946 /// Leave string quotes as they are.
952 /// Always use single quotes.
958 /// Always use double quotes.
966 /// \brief The JavaScriptQuoteStyle to use for JavaScript strings.
967 JavaScriptQuoteStyle JavaScriptQuotes;
969 /// \brief Whether to wrap JavaScript import/export statements.
973 /// VeryLongImportsAreAnnoying,
974 /// VeryLongImportsAreAnnoying,
975 /// VeryLongImportsAreAnnoying,
976 /// } from 'some/module.js'
979 /// import {VeryLongImportsAreAnnoying, VeryLongImportsAreAnnoying, VeryLongImportsAreAnnoying,} from "some/module.js"
981 bool JavaScriptWrapImports;
983 /// \brief If true, the empty line at the start of blocks is kept.
986 /// if (foo) { vs. if (foo) {
991 bool KeepEmptyLinesAtTheStartOfBlocks;
993 /// \brief Supported languages.
995 /// When stored in a configuration file, specifies the language, that the
996 /// configuration targets. When passed to the ``reformat()`` function, enables
997 /// syntax features specific to the language.
1001 /// Should be used for C, C++.
1003 /// Should be used for Java.
1005 /// Should be used for JavaScript.
1007 /// Should be used for Objective-C, Objective-C++.
1009 /// Should be used for Protocol Buffers
1010 /// (https://developers.google.com/protocol-buffers/).
1012 /// Should be used for TableGen code.
1015 bool isCpp() const { return Language == LK_Cpp || Language == LK_ObjC; }
1017 /// \brief Language, this format style is targeted at.
1018 LanguageKind Language;
1020 /// \brief A regular expression matching macros that start a block.
1023 /// MacroBlockBegin: "^NS_MAP_BEGIN|\
1025 /// MacroBlockEnd: "^\
1027 /// NS_TABLE_.*_END$"
1035 /// NS_TABLE_FOO_END
1044 /// NS_TABLE_FOO_END
1046 std::string MacroBlockBegin;
1048 /// \brief A regular expression matching macros that end a block.
1049 std::string MacroBlockEnd;
1051 /// \brief The maximum number of consecutive empty lines to keep.
1053 /// MaxEmptyLinesToKeep: 1 vs. MaxEmptyLinesToKeep: 0
1054 /// int f() { int f() {
1055 /// int = 1; int i = 1;
1057 /// i = foo(); return i;
1062 unsigned MaxEmptyLinesToKeep;
1064 /// \brief Different ways to indent namespace contents.
1065 enum NamespaceIndentationKind {
1066 /// Don't indent in namespaces.
1076 /// Indent only in inner namespaces (nested in other namespaces).
1086 /// Indent in all namespaces.
1098 /// \brief The indentation used for namespaces.
1099 NamespaceIndentationKind NamespaceIndentation;
1101 /// \brief The number of characters to use for indentation of ObjC blocks.
1103 /// ObjCBlockIndentWidth: 4
1105 /// [operation setCompletionBlock:^{
1106 /// [self onOperationDone];
1109 unsigned ObjCBlockIndentWidth;
1111 /// \brief Add a space after ``@property`` in Objective-C, i.e. use
1112 /// ``@property (readonly)`` instead of ``@property(readonly)``.
1113 bool ObjCSpaceAfterProperty;
1115 /// \brief Add a space in front of an Objective-C protocol list, i.e. use
1116 /// ``Foo <Protocol>`` instead of ``Foo<Protocol>``.
1117 bool ObjCSpaceBeforeProtocolList;
1119 /// \brief The penalty for breaking a function call after ``call(``.
1120 unsigned PenaltyBreakBeforeFirstCallParameter;
1122 /// \brief The penalty for each line break introduced inside a comment.
1123 unsigned PenaltyBreakComment;
1125 /// \brief The penalty for breaking before the first ``<<``.
1126 unsigned PenaltyBreakFirstLessLess;
1128 /// \brief The penalty for each line break introduced inside a string literal.
1129 unsigned PenaltyBreakString;
1131 /// \brief The penalty for each character outside of the column limit.
1132 unsigned PenaltyExcessCharacter;
1134 /// \brief Penalty for putting the return type of a function onto its own
1136 unsigned PenaltyReturnTypeOnItsOwnLine;
1138 /// \brief The ``&`` and ``*`` alignment style.
1139 enum PointerAlignmentStyle {
1140 /// Align pointer to the left.
1145 /// Align pointer to the right.
1150 /// Align pointer in the middle.
1157 /// \brief Pointer and reference alignment style.
1158 PointerAlignmentStyle PointerAlignment;
1160 /// \brief If ``true``, clang-format will attempt to re-flow comments.
1163 /// // veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongComment with plenty of information
1164 /// /* second veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongComment with plenty of information */
1167 /// // veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongComment with plenty of
1169 /// /* second veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongComment with plenty of
1170 /// * information */
1172 bool ReflowComments;
1174 /// \brief If ``true``, clang-format will sort ``#includes``.
1177 /// #include "b.h" vs. #include "a.h"
1178 /// #include "a.h" #include "b.h"
1182 /// \brief If ``true``, a space is inserted after C style casts.
1185 /// (int)i; vs. (int) i;
1187 bool SpaceAfterCStyleCast;
1189 /// \brief If \c true, a space will be inserted after the 'template' keyword.
1192 /// template <int> void foo(); vs. template<int> void foo();
1194 bool SpaceAfterTemplateKeyword;
1196 /// \brief If ``false``, spaces will be removed before assignment operators.
1199 /// int a = 5; vs. int a=5;
1202 bool SpaceBeforeAssignmentOperators;
1204 /// \brief Different ways to put a space before opening parentheses.
1205 enum SpaceBeforeParensOptions {
1206 /// Never put a space before opening parentheses.
1215 /// Put a space before opening parentheses only after control statement
1216 /// keywords (``for/if/while...``).
1224 SBPO_ControlStatements,
1225 /// Always put a space before opening parentheses, except when it's
1226 /// prohibited by the syntax rules (in function-like macro definitions) or
1227 /// when determined by other style rules (after unary operators, opening
1228 /// parentheses, etc.)
1239 /// \brief Defines in which cases to put a space before opening parentheses.
1240 SpaceBeforeParensOptions SpaceBeforeParens;
1242 /// \brief If ``true``, spaces may be inserted into ``()``.
1245 /// void f( ) { vs. void f() {
1246 /// int x[] = {foo( ), bar( )}; int x[] = {foo(), bar()};
1247 /// if (true) { if (true) {
1252 bool SpaceInEmptyParentheses;
1254 /// \brief The number of spaces before trailing line comments
1255 /// (``//`` - comments).
1257 /// This does not affect trailing block comments (``/*`` - comments) as
1258 /// those commonly have different usage patterns and a number of special
1261 /// SpacesBeforeTrailingComments: 3
1263 /// if (true) { // foo1
1268 unsigned SpacesBeforeTrailingComments;
1270 /// \brief If ``true``, spaces will be inserted after ``<`` and before ``>``
1271 /// in template argument lists.
1274 /// static_cast< int >(arg); vs. static_cast<int>(arg);
1275 /// std::function< void(int) > fct; std::function<void(int)> fct;
1277 bool SpacesInAngles;
1279 /// \brief If ``true``, spaces are inserted inside container literals (e.g.
1280 /// ObjC and Javascript array and dict literals).
1283 /// var arr = [ 1, 2, 3 ]; vs. var arr = [1, 2, 3];
1284 /// f({a : 1, b : 2, c : 3}); f({a: 1, b: 2, c: 3});
1286 bool SpacesInContainerLiterals;
1288 /// \brief If ``true``, spaces may be inserted into C style casts.
1291 /// x = ( int32 )y vs. x = (int32)y
1293 bool SpacesInCStyleCastParentheses;
1295 /// \brief If ``true``, spaces will be inserted after ``(`` and before ``)``.
1298 /// t f( Deleted & ) & = delete; vs. t f(Deleted &) & = delete;
1300 bool SpacesInParentheses;
1302 /// \brief If ``true``, spaces will be inserted after ``[`` and before ``]``.
1303 /// Lambdas or unspecified size array declarations will not be affected.
1306 /// int a[ 5 ]; vs. int a[5];
1307 /// std::unique_ptr<int[]> foo() {} // Won't be affected
1309 bool SpacesInSquareBrackets;
1311 /// \brief Supported language standards.
1312 enum LanguageStandard {
1313 /// Use C++03-compatible syntax.
1315 /// Use features of C++11, C++14 and C++1z (e.g. ``A<A<int>>`` instead of
1316 /// ``A<A<int> >``).
1318 /// Automatic detection based on the input.
1322 /// \brief Format compatible with this standard, e.g. use ``A<A<int> >``
1323 /// instead of ``A<A<int>>`` for ``LS_Cpp03``.
1324 LanguageStandard Standard;
1326 /// \brief The number of columns used for tab stops.
1329 /// \brief Different ways to use tab in formatting.
1333 /// Use tabs only for indentation.
1335 /// Use tabs only for line continuation and indentation.
1336 UT_ForContinuationAndIndentation,
1337 /// Use tabs whenever we need to fill whitespace that spans at least from
1338 /// one tab stop to the next one.
1342 /// \brief The way to use tab characters in the resulting file.
1345 bool operator==(const FormatStyle &R) const {
1346 return AccessModifierOffset == R.AccessModifierOffset &&
1347 AlignAfterOpenBracket == R.AlignAfterOpenBracket &&
1348 AlignConsecutiveAssignments == R.AlignConsecutiveAssignments &&
1349 AlignConsecutiveDeclarations == R.AlignConsecutiveDeclarations &&
1350 AlignEscapedNewlinesLeft == R.AlignEscapedNewlinesLeft &&
1351 AlignOperands == R.AlignOperands &&
1352 AlignTrailingComments == R.AlignTrailingComments &&
1353 AllowAllParametersOfDeclarationOnNextLine ==
1354 R.AllowAllParametersOfDeclarationOnNextLine &&
1355 AllowShortBlocksOnASingleLine == R.AllowShortBlocksOnASingleLine &&
1356 AllowShortCaseLabelsOnASingleLine ==
1357 R.AllowShortCaseLabelsOnASingleLine &&
1358 AllowShortFunctionsOnASingleLine ==
1359 R.AllowShortFunctionsOnASingleLine &&
1360 AllowShortIfStatementsOnASingleLine ==
1361 R.AllowShortIfStatementsOnASingleLine &&
1362 AllowShortLoopsOnASingleLine == R.AllowShortLoopsOnASingleLine &&
1363 AlwaysBreakAfterReturnType == R.AlwaysBreakAfterReturnType &&
1364 AlwaysBreakBeforeMultilineStrings ==
1365 R.AlwaysBreakBeforeMultilineStrings &&
1366 AlwaysBreakTemplateDeclarations ==
1367 R.AlwaysBreakTemplateDeclarations &&
1368 BinPackArguments == R.BinPackArguments &&
1369 BinPackParameters == R.BinPackParameters &&
1370 BreakBeforeBinaryOperators == R.BreakBeforeBinaryOperators &&
1371 BreakBeforeBraces == R.BreakBeforeBraces &&
1372 BreakBeforeTernaryOperators == R.BreakBeforeTernaryOperators &&
1373 BreakConstructorInitializersBeforeComma ==
1374 R.BreakConstructorInitializersBeforeComma &&
1375 BreakAfterJavaFieldAnnotations == R.BreakAfterJavaFieldAnnotations &&
1376 BreakStringLiterals == R.BreakStringLiterals &&
1377 ColumnLimit == R.ColumnLimit && CommentPragmas == R.CommentPragmas &&
1378 BreakBeforeInheritanceComma == R.BreakBeforeInheritanceComma &&
1379 ConstructorInitializerAllOnOneLineOrOnePerLine ==
1380 R.ConstructorInitializerAllOnOneLineOrOnePerLine &&
1381 ConstructorInitializerIndentWidth ==
1382 R.ConstructorInitializerIndentWidth &&
1383 ContinuationIndentWidth == R.ContinuationIndentWidth &&
1384 Cpp11BracedListStyle == R.Cpp11BracedListStyle &&
1385 DerivePointerAlignment == R.DerivePointerAlignment &&
1386 DisableFormat == R.DisableFormat &&
1387 ExperimentalAutoDetectBinPacking ==
1388 R.ExperimentalAutoDetectBinPacking &&
1389 FixNamespaceComments == R.FixNamespaceComments &&
1390 ForEachMacros == R.ForEachMacros &&
1391 IncludeCategories == R.IncludeCategories &&
1392 IndentCaseLabels == R.IndentCaseLabels &&
1393 IndentWidth == R.IndentWidth && Language == R.Language &&
1394 IndentWrappedFunctionNames == R.IndentWrappedFunctionNames &&
1395 JavaScriptQuotes == R.JavaScriptQuotes &&
1396 JavaScriptWrapImports == R.JavaScriptWrapImports &&
1397 KeepEmptyLinesAtTheStartOfBlocks ==
1398 R.KeepEmptyLinesAtTheStartOfBlocks &&
1399 MacroBlockBegin == R.MacroBlockBegin &&
1400 MacroBlockEnd == R.MacroBlockEnd &&
1401 MaxEmptyLinesToKeep == R.MaxEmptyLinesToKeep &&
1402 NamespaceIndentation == R.NamespaceIndentation &&
1403 ObjCBlockIndentWidth == R.ObjCBlockIndentWidth &&
1404 ObjCSpaceAfterProperty == R.ObjCSpaceAfterProperty &&
1405 ObjCSpaceBeforeProtocolList == R.ObjCSpaceBeforeProtocolList &&
1406 PenaltyBreakBeforeFirstCallParameter ==
1407 R.PenaltyBreakBeforeFirstCallParameter &&
1408 PenaltyBreakComment == R.PenaltyBreakComment &&
1409 PenaltyBreakFirstLessLess == R.PenaltyBreakFirstLessLess &&
1410 PenaltyBreakString == R.PenaltyBreakString &&
1411 PenaltyExcessCharacter == R.PenaltyExcessCharacter &&
1412 PenaltyReturnTypeOnItsOwnLine == R.PenaltyReturnTypeOnItsOwnLine &&
1413 PointerAlignment == R.PointerAlignment &&
1414 SpaceAfterCStyleCast == R.SpaceAfterCStyleCast &&
1415 SpaceAfterTemplateKeyword == R.SpaceAfterTemplateKeyword &&
1416 SpaceBeforeAssignmentOperators == R.SpaceBeforeAssignmentOperators &&
1417 SpaceBeforeParens == R.SpaceBeforeParens &&
1418 SpaceInEmptyParentheses == R.SpaceInEmptyParentheses &&
1419 SpacesBeforeTrailingComments == R.SpacesBeforeTrailingComments &&
1420 SpacesInAngles == R.SpacesInAngles &&
1421 SpacesInContainerLiterals == R.SpacesInContainerLiterals &&
1422 SpacesInCStyleCastParentheses == R.SpacesInCStyleCastParentheses &&
1423 SpacesInParentheses == R.SpacesInParentheses &&
1424 SpacesInSquareBrackets == R.SpacesInSquareBrackets &&
1425 Standard == R.Standard && TabWidth == R.TabWidth &&
1430 /// \brief Returns a format style complying with the LLVM coding standards:
1431 /// http://llvm.org/docs/CodingStandards.html.
1432 FormatStyle getLLVMStyle();
1434 /// \brief Returns a format style complying with one of Google's style guides:
1435 /// http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml.
1436 /// http://google-styleguide.googlecode.com/svn/trunk/javascriptguide.xml.
1437 /// https://developers.google.com/protocol-buffers/docs/style.
1438 FormatStyle getGoogleStyle(FormatStyle::LanguageKind Language);
1440 /// \brief Returns a format style complying with Chromium's style guide:
1441 /// http://www.chromium.org/developers/coding-style.
1442 FormatStyle getChromiumStyle(FormatStyle::LanguageKind Language);
1444 /// \brief Returns a format style complying with Mozilla's style guide:
1445 /// https://developer.mozilla.org/en-US/docs/Developer_Guide/Coding_Style.
1446 FormatStyle getMozillaStyle();
1448 /// \brief Returns a format style complying with Webkit's style guide:
1449 /// http://www.webkit.org/coding/coding-style.html
1450 FormatStyle getWebKitStyle();
1452 /// \brief Returns a format style complying with GNU Coding Standards:
1453 /// http://www.gnu.org/prep/standards/standards.html
1454 FormatStyle getGNUStyle();
1456 /// \brief Returns style indicating formatting should be not applied at all.
1457 FormatStyle getNoStyle();
1459 /// \brief Gets a predefined style for the specified language by name.
1461 /// Currently supported names: LLVM, Google, Chromium, Mozilla. Names are
1462 /// compared case-insensitively.
1464 /// Returns ``true`` if the Style has been set.
1465 bool getPredefinedStyle(StringRef Name, FormatStyle::LanguageKind Language,
1466 FormatStyle *Style);
1468 /// \brief Parse configuration from YAML-formatted text.
1470 /// Style->Language is used to get the base style, if the ``BasedOnStyle``
1471 /// option is present.
1473 /// When ``BasedOnStyle`` is not present, options not present in the YAML
1474 /// document, are retained in \p Style.
1475 std::error_code parseConfiguration(StringRef Text, FormatStyle *Style);
1477 /// \brief Gets configuration in a YAML string.
1478 std::string configurationAsText(const FormatStyle &Style);
1480 /// \brief Returns the replacements necessary to sort all ``#include`` blocks
1481 /// that are affected by ``Ranges``.
1482 tooling::Replacements sortIncludes(const FormatStyle &Style, StringRef Code,
1483 ArrayRef<tooling::Range> Ranges,
1485 unsigned *Cursor = nullptr);
1487 /// \brief Returns the replacements corresponding to applying and formatting
1488 /// \p Replaces on success; otheriwse, return an llvm::Error carrying
1489 /// llvm::StringError.
1490 llvm::Expected<tooling::Replacements>
1491 formatReplacements(StringRef Code, const tooling::Replacements &Replaces,
1492 const FormatStyle &Style);
1494 /// \brief Returns the replacements corresponding to applying \p Replaces and
1495 /// cleaning up the code after that on success; otherwise, return an llvm::Error
1496 /// carrying llvm::StringError.
1497 /// This also supports inserting/deleting C++ #include directives:
1498 /// - If a replacement has offset UINT_MAX, length 0, and a replacement text
1499 /// that is an #include directive, this will insert the #include into the
1500 /// correct block in the \p Code. When searching for points to insert new
1501 /// header, this ignores #include's after the #include block(s) in the
1502 /// beginning of a file to avoid inserting headers into code sections where
1503 /// new #include's should not be added by default. These code sections
1505 /// - raw string literals (containing #include).
1507 /// - Special #include's among declarations (e.g. functions).
1508 /// - If a replacement has offset UINT_MAX, length 1, and a replacement text
1509 /// that is the name of the header to be removed, the header will be removed
1510 /// from \p Code if it exists.
1511 llvm::Expected<tooling::Replacements>
1512 cleanupAroundReplacements(StringRef Code, const tooling::Replacements &Replaces,
1513 const FormatStyle &Style);
1515 /// \brief Reformats the given \p Ranges in \p Code.
1517 /// Each range is extended on either end to its next bigger logic unit, i.e.
1518 /// everything that might influence its formatting or might be influenced by its
1521 /// Returns the ``Replacements`` necessary to make all \p Ranges comply with
1524 /// If ``IncompleteFormat`` is non-null, its value will be set to true if any
1525 /// of the affected ranges were not formatted due to a non-recoverable syntax
1527 tooling::Replacements reformat(const FormatStyle &Style, StringRef Code,
1528 ArrayRef<tooling::Range> Ranges,
1529 StringRef FileName = "<stdin>",
1530 bool *IncompleteFormat = nullptr);
1532 /// \brief Clean up any erroneous/redundant code in the given \p Ranges in \p
1535 /// Returns the ``Replacements`` that clean up all \p Ranges in \p Code.
1536 tooling::Replacements cleanup(const FormatStyle &Style, StringRef Code,
1537 ArrayRef<tooling::Range> Ranges,
1538 StringRef FileName = "<stdin>");
1540 /// \brief Fix namespace end comments in the given \p Ranges in \p Code.
1542 /// Returns the ``Replacements`` that fix the namespace comments in all
1543 /// \p Ranges in \p Code.
1544 tooling::Replacements fixNamespaceEndComments(const FormatStyle &Style,
1546 ArrayRef<tooling::Range> Ranges,
1547 StringRef FileName = "<stdin>");
1549 /// \brief Returns the ``LangOpts`` that the formatter expects you to set.
1551 /// \param Style determines specific settings for lexing mode.
1552 LangOptions getFormattingLangOpts(const FormatStyle &Style = getLLVMStyle());
1554 /// \brief Description to be used for help text for a ``llvm::cl`` option for
1555 /// specifying format style. The description is closely related to the operation
1556 /// of ``getStyle()``.
1557 extern const char *StyleOptionHelpDescription;
1559 /// \brief Construct a FormatStyle based on ``StyleName``.
1561 /// ``StyleName`` can take several forms:
1562 /// * "{<key>: <value>, ...}" - Set specic style parameters.
1563 /// * "<style name>" - One of the style names supported by
1564 /// getPredefinedStyle().
1565 /// * "file" - Load style configuration from a file called ``.clang-format``
1566 /// located in one of the parent directories of ``FileName`` or the current
1567 /// directory if ``FileName`` is empty.
1569 /// \param[in] StyleName Style name to interpret according to the description
1571 /// \param[in] FileName Path to start search for .clang-format if ``StyleName``
1573 /// \param[in] FallbackStyle The name of a predefined style used to fallback to
1574 /// in case \p StyleName is "file" and no file can be found.
1575 /// \param[in] Code The actual code to be formatted. Used to determine the
1576 /// language if the filename isn't sufficient.
1577 /// \param[in] FS The underlying file system, in which the file resides. By
1578 /// default, the file system is the real file system.
1580 /// \returns FormatStyle as specified by ``StyleName``. If ``StyleName`` is
1581 /// "file" and no file is found, returns ``FallbackStyle``. If no style could be
1582 /// determined, returns an Error.
1583 llvm::Expected<FormatStyle> getStyle(StringRef StyleName, StringRef FileName,
1584 StringRef FallbackStyle,
1585 StringRef Code = "",
1586 vfs::FileSystem *FS = nullptr);
1588 // \brief Returns a string representation of ``Language``.
1589 inline StringRef getLanguageName(FormatStyle::LanguageKind Language) {
1591 case FormatStyle::LK_Cpp:
1593 case FormatStyle::LK_ObjC:
1594 return "Objective-C";
1595 case FormatStyle::LK_Java:
1597 case FormatStyle::LK_JavaScript:
1598 return "JavaScript";
1599 case FormatStyle::LK_Proto:
1606 } // end namespace format
1607 } // end namespace clang
1611 struct is_error_code_enum<clang::format::ParseError> : std::true_type {};
1614 #endif // LLVM_CLANG_FORMAT_FORMAT_H