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 "clang/Tooling/Inclusions/IncludeStyle.h"
21 #include "llvm/ADT/ArrayRef.h"
22 #include "llvm/Support/Regex.h"
23 #include <system_error>
29 class DiagnosticConsumer;
37 enum class ParseError { Success = 0, Error, Unsuitable };
38 class ParseErrorCategory final : public std::error_category {
40 const char *name() const noexcept override;
41 std::string message(int EV) const override;
43 const std::error_category &getParseCategory();
44 std::error_code make_error_code(ParseError e);
46 /// The ``FormatStyle`` is used to configure the formatting to follow
47 /// specific guidelines.
49 /// The extra indent or outdent of access modifiers, e.g. ``public:``.
50 int AccessModifierOffset;
52 /// Different styles for aligning after open brackets.
53 enum BracketAlignmentStyle {
54 /// Align parameters on the open bracket, e.g.:
56 /// someLongFunction(argument1,
60 /// Don't align, instead use ``ContinuationIndentWidth``, e.g.:
62 /// someLongFunction(argument1,
66 /// Always break after an open bracket, if the parameters don't fit
67 /// on a single line, e.g.:
70 /// argument1, argument2);
75 /// If ``true``, horizontally aligns arguments after an open bracket.
77 /// This applies to round brackets (parentheses), angle brackets and square
79 BracketAlignmentStyle AlignAfterOpenBracket;
81 /// If ``true``, aligns consecutive assignments.
83 /// This will align the assignment operators of consecutive lines. This
84 /// will result in formattings like
90 bool AlignConsecutiveAssignments;
92 /// If ``true``, aligns consecutive declarations.
94 /// This will align the declaration names of consecutive lines. This
95 /// will result in formattings like
99 /// std::string ccc = 23;
101 bool AlignConsecutiveDeclarations;
103 /// Different styles for aligning escaped newlines.
104 enum EscapedNewlineAlignmentStyle {
105 /// Don't align escaped newlines.
113 /// Align escaped newlines as far left as possible.
124 /// Align escaped newlines in the right-most column.
134 /// Options for aligning backslashes in escaped newlines.
135 EscapedNewlineAlignmentStyle AlignEscapedNewlines;
137 /// If ``true``, horizontally align operands of binary and ternary
140 /// Specifically, this aligns operands of a single expression that needs to be
141 /// split over multiple lines, e.g.:
143 /// int aaa = bbbbbbbbbbbbbbb +
148 /// If ``true``, aligns trailing comments.
151 /// int a; // My comment a vs. int a; // My comment a
152 /// int b = 2; // comment b int b = 2; // comment about b
154 bool AlignTrailingComments;
156 /// If the function declaration doesn't fit on a line,
157 /// allow putting all parameters of a function declaration onto
158 /// the next line even if ``BinPackParameters`` is ``false``.
162 /// int a, int b, int c, int d, int e);
165 /// void myFunction(int a,
171 bool AllowAllParametersOfDeclarationOnNextLine;
173 /// Allows contracting simple braced statements to a single line.
175 /// E.g., this allows ``if (a) { return; }`` to be put on a single line.
176 bool AllowShortBlocksOnASingleLine;
178 /// If ``true``, short case labels will be contracted to a single line.
181 /// switch (a) { vs. switch (a) {
182 /// case 1: x = 1; break; case 1:
183 /// case 2: return; x = 1;
189 bool AllowShortCaseLabelsOnASingleLine;
191 /// Different styles for merging short functions containing at most one
193 enum ShortFunctionStyle {
194 /// Never merge functions into a single line.
196 /// Only merge functions defined inside a class. Same as "inline",
197 /// except it does not implies "empty": i.e. top level empty functions
198 /// are not merged either.
201 /// void f() { foo(); }
210 /// Only merge empty functions.
218 /// Only merge functions defined inside a class. Implies "empty".
221 /// void f() { foo(); }
229 /// Merge all functions fitting on a single line.
232 /// void f() { foo(); }
234 /// void f() { bar(); }
239 /// Dependent on the value, ``int f() { return 0; }`` can be put on a
241 ShortFunctionStyle AllowShortFunctionsOnASingleLine;
243 /// If ``true``, ``if (a) return;`` can be put on a single line.
244 bool AllowShortIfStatementsOnASingleLine;
246 /// If ``true``, ``while (true) continue;`` can be put on a single
248 bool AllowShortLoopsOnASingleLine;
250 /// Different ways to break after the function definition return type.
251 /// This option is **deprecated** and is retained for backwards compatibility.
252 enum DefinitionReturnTypeBreakingStyle {
253 /// Break after return type automatically.
254 /// ``PenaltyReturnTypeOnItsOwnLine`` is taken into account.
256 /// Always break after the return type.
258 /// Always break after the return types of top-level functions.
262 /// Different ways to break after the function definition or
263 /// declaration return type.
264 enum ReturnTypeBreakingStyle {
265 /// Break after return type automatically.
266 /// ``PenaltyReturnTypeOnItsOwnLine`` is taken into account.
269 /// int f() { return 0; };
272 /// int f() { return 1; }
275 /// Always break after the return type.
291 /// Always break after the return types of top-level functions.
294 /// int f() { return 0; };
304 /// Always break after the return type of function definitions.
319 /// Always break after the return type of top-level definitions.
322 /// int f() { return 0; };
330 RTBS_TopLevelDefinitions,
333 /// The function definition return type breaking style to use. This
334 /// option is **deprecated** and is retained for backwards compatibility.
335 DefinitionReturnTypeBreakingStyle AlwaysBreakAfterDefinitionReturnType;
337 /// The function declaration return type breaking style to use.
338 ReturnTypeBreakingStyle AlwaysBreakAfterReturnType;
340 /// If ``true``, always break before multiline string literals.
342 /// This flag is mean to make cases where there are multiple multiline strings
343 /// in a file look more consistent. Thus, it will only take effect if wrapping
344 /// the string at that point leads to it being indented
345 /// ``ContinuationIndentWidth`` spaces from the start of the line.
348 /// aaaa = vs. aaaa = "bbbb"
352 bool AlwaysBreakBeforeMultilineStrings;
354 /// Different ways to break after the template declaration.
355 enum BreakTemplateDeclarationsStyle {
356 /// Do not force break before declaration.
357 /// ``PenaltyBreakTemplateDeclaration`` is taken into account.
359 /// template <typename T> T foo() {
361 /// template <typename T> T foo(int aaaaaaaaaaaaaaaaaaaaa,
362 /// int bbbbbbbbbbbbbbbbbbbbb) {
366 /// Force break after template declaration only when the following
367 /// declaration spans multiple lines.
369 /// template <typename T> T foo() {
371 /// template <typename T>
372 /// T foo(int aaaaaaaaaaaaaaaaaaaaa,
373 /// int bbbbbbbbbbbbbbbbbbbbb) {
377 /// Always break after template declaration.
379 /// template <typename T>
382 /// template <typename T>
383 /// T foo(int aaaaaaaaaaaaaaaaaaaaa,
384 /// int bbbbbbbbbbbbbbbbbbbbb) {
390 /// The template declaration breaking style to use.
391 BreakTemplateDeclarationsStyle AlwaysBreakTemplateDeclarations;
393 /// If ``false``, a function call's arguments will either be all on the
394 /// same line or will have one line each.
398 /// f(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaa,
399 /// aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);
404 /// f(aaaaaaaaaaaaaaaaaaaa,
405 /// aaaaaaaaaaaaaaaaaaaa,
406 /// aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);
409 bool BinPackArguments;
411 /// If ``false``, a function declaration's or function definition's
412 /// parameters will either all be on the same line or will have one line each.
415 /// void f(int aaaaaaaaaaaaaaaaaaaa, int aaaaaaaaaaaaaaaaaaaa,
416 /// int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}
419 /// void f(int aaaaaaaaaaaaaaaaaaaa,
420 /// int aaaaaaaaaaaaaaaaaaaa,
421 /// int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}
423 bool BinPackParameters;
425 /// The style of wrapping parameters on the same line (bin-packed) or
426 /// on one line each.
428 /// Automatically determine parameter bin-packing behavior.
430 /// Always bin-pack parameters.
432 /// Never bin-pack parameters.
436 /// The style of breaking before or after binary operators.
437 enum BinaryOperatorStyle {
438 /// Break after operators.
440 /// LooooooooooongType loooooooooooooooooooooongVariable =
441 /// someLooooooooooooooooongFunction();
443 /// bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +
444 /// aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==
445 /// aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa &&
446 /// aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >
447 /// ccccccccccccccccccccccccccccccccccccccccc;
450 /// Break before operators that aren't assignments.
452 /// LooooooooooongType loooooooooooooooooooooongVariable =
453 /// someLooooooooooooooooongFunction();
455 /// bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
456 /// + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
457 /// == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
458 /// && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
459 /// > ccccccccccccccccccccccccccccccccccccccccc;
462 /// Break before operators.
464 /// LooooooooooongType loooooooooooooooooooooongVariable
465 /// = someLooooooooooooooooongFunction();
467 /// bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
468 /// + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
469 /// == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
470 /// && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
471 /// > ccccccccccccccccccccccccccccccccccccccccc;
476 /// The way to wrap binary operators.
477 BinaryOperatorStyle BreakBeforeBinaryOperators;
479 /// Different ways to attach braces to their surrounding context.
480 enum BraceBreakingStyle {
481 /// Always attach braces to surrounding context.
487 /// void foo() { bar(); }
492 /// enum X : int { A, B };
495 /// Like ``Attach``, but break before braces on function, namespace and
496 /// class definitions.
502 /// void foo() { bar(); }
509 /// enum X : int { A, B };
512 /// Like ``Attach``, but break before braces on enum, function, and record
519 /// void foo() { bar(); }
526 /// enum X : int { A, B };
529 /// Like ``Attach``, but break before function definitions, ``catch``, and
536 /// void foo() { bar(); }
550 /// Always break before braces.
557 /// void foo() { bar(); }
564 /// enum X : int { A, B };
567 /// Always break before braces and add an extra level of indentation to
568 /// braces of control statements, not to those of class, function
569 /// or other definitions.
578 /// void foo() { bar(); }
595 /// Like ``Attach``, but break before functions.
601 /// void foo() { bar(); }
607 /// enum X : int { A, B };
610 /// Configure each individual brace in `BraceWrapping`.
614 /// The brace breaking style to use.
615 BraceBreakingStyle BreakBeforeBraces;
617 /// Precise control over the wrapping of braces.
619 /// # Should be declared this way:
620 /// BreakBeforeBraces: Custom
624 struct BraceWrappingFlags {
625 /// Wrap class definitions.
635 /// Wrap control statements (``if``/``for``/``while``/``switch``/..).
642 /// for (int i = 0; i < 10; ++i)
649 /// for (int i = 0; i < 10; ++i) {
652 bool AfterControlStatement;
653 /// Wrap enum definitions.
662 /// enum X : int { B };
665 /// Wrap function definitions.
681 /// Wrap namespace definitions.
697 /// Wrap ObjC definitions (interfaces, implementations...).
698 /// \note @autoreleasepool and @synchronized blocks are wrapped
699 /// according to `AfterControlStatement` flag.
700 bool AfterObjCDeclaration;
701 /// Wrap struct definitions.
715 /// Wrap union definitions.
729 /// Wrap extern blocks.
742 bool AfterExternBlock;
743 /// Wrap before ``catch``.
759 /// Wrap before ``else``.
773 /// Indent the wrapped braces themselves.
775 /// If ``false``, empty function body can be put on a single line.
776 /// This option is used only if the opening brace of the function has
777 /// already been wrapped, i.e. the `AfterFunction` brace wrapping mode is
778 /// set, and the function could/should not be put on a single line (as per
779 /// `AllowShortFunctionsOnASingleLine` and constructor formatting options).
781 /// int f() vs. inf f()
786 bool SplitEmptyFunction;
787 /// If ``false``, empty record (e.g. class, struct or union) body
788 /// can be put on a single line. This option is used only if the opening
789 /// brace of the record has already been wrapped, i.e. the `AfterClass`
790 /// (for classes) brace wrapping mode is set.
792 /// class Foo vs. class Foo
797 bool SplitEmptyRecord;
798 /// If ``false``, empty namespace body can be put on a single line.
799 /// This option is used only if the opening brace of the namespace has
800 /// already been wrapped, i.e. the `AfterNamespace` brace wrapping mode is
803 /// namespace Foo vs. namespace Foo
808 bool SplitEmptyNamespace;
811 /// Control of individual brace wrapping cases.
813 /// If ``BreakBeforeBraces`` is set to ``BS_Custom``, use this to specify how
814 /// each individual brace case should be handled. Otherwise, this is ignored.
816 /// # Example of usage:
817 /// BreakBeforeBraces: Custom
820 /// AfterStruct: false
821 /// SplitEmptyFunction: false
823 BraceWrappingFlags BraceWrapping;
825 /// If ``true``, ternary operators will be placed after line breaks.
828 /// veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongDescription
830 /// : SecondValueVeryVeryVeryVeryLong;
833 /// veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongDescription ?
835 /// SecondValueVeryVeryVeryVeryLong;
837 bool BreakBeforeTernaryOperators;
839 /// Different ways to break initializers.
840 enum BreakConstructorInitializersStyle {
841 /// Break constructor initializers before the colon and after the commas.
844 /// : initializer1(),
848 /// Break constructor initializers before the colon and commas, and align
849 /// the commas with the colon.
856 /// Break constructor initializers after the colon and commas.
865 /// The constructor initializers style to use.
866 BreakConstructorInitializersStyle BreakConstructorInitializers;
868 /// Break after each annotation on a field in Java files.
871 /// @Partial vs. @Partial @Mock DataLoad loader;
875 bool BreakAfterJavaFieldAnnotations;
877 /// Allow breaking string literals when formatting.
878 bool BreakStringLiterals;
880 /// The column limit.
882 /// A column limit of ``0`` means that there is no column limit. In this case,
883 /// clang-format will respect the input's line breaking decisions within
884 /// statements unless they contradict other rules.
885 unsigned ColumnLimit;
887 /// A regular expression that describes comments with special meaning,
888 /// which should not be split into lines or otherwise changed.
890 /// // CommentPragmas: '^ FOOBAR pragma:'
891 /// // Will leave the following line unaffected
892 /// #include <vector> // FOOBAR pragma: keep
894 std::string CommentPragmas;
896 /// Different ways to break inheritance list.
897 enum BreakInheritanceListStyle {
898 /// Break inheritance list before the colon and after the commas.
906 /// Break inheritance list before the colon and commas, and align
907 /// the commas with the colon.
915 /// Break inheritance list after the colon and commas.
925 /// The inheritance list style to use.
926 BreakInheritanceListStyle BreakInheritanceList;
928 /// If ``true``, consecutive namespace declarations will be on the same
929 /// line. If ``false``, each namespace is declared on a new line.
932 /// namespace Foo { namespace Bar {
942 /// If it does not fit on a single line, the overflowing namespaces get
945 /// namespace Foo { namespace Bar {
946 /// namespace Extra {
949 bool CompactNamespaces;
951 /// If the constructor initializers don't fit on a line, put each
952 /// initializer on its own line.
955 /// SomeClass::Constructor()
956 /// : aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa) {
961 /// SomeClass::Constructor()
962 /// : aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaa),
963 /// aaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa) {
967 bool ConstructorInitializerAllOnOneLineOrOnePerLine;
969 /// The number of characters to use for indentation of constructor
970 /// initializer lists as well as inheritance lists.
971 unsigned ConstructorInitializerIndentWidth;
973 /// Indent width for line continuations.
975 /// ContinuationIndentWidth: 2
977 /// int i = // VeryVeryVeryVeryVeryLongComment
978 /// longFunction( // Again a long comment
981 unsigned ContinuationIndentWidth;
983 /// If ``true``, format braced lists as best suited for C++11 braced
986 /// Important differences:
987 /// - No spaces inside the braced list.
988 /// - No line break before the closing brace.
989 /// - Indentation with the continuation indent, not with the block indent.
991 /// Fundamentally, C++11 braced lists are formatted exactly like function
992 /// calls would be formatted in their place. If the braced list follows a name
993 /// (e.g. a type or variable name), clang-format formats as if the ``{}`` were
994 /// the parentheses of a function call with that name. If there is no name,
995 /// a zero-length name is assumed.
998 /// vector<int> x{1, 2, 3, 4}; vs. vector<int> x{ 1, 2, 3, 4 };
999 /// vector<T> x{{}, {}, {}, {}}; vector<T> x{ {}, {}, {}, {} };
1000 /// f(MyMap[{composite, key}]); f(MyMap[{ composite, key }]);
1001 /// new int[3]{1, 2, 3}; new int[3]{ 1, 2, 3 };
1003 bool Cpp11BracedListStyle;
1005 /// If ``true``, analyze the formatted file for the most common
1006 /// alignment of ``&`` and ``*``.
1007 /// Pointer and reference alignment styles are going to be updated according
1008 /// to the preferences found in the file.
1009 /// ``PointerAlignment`` is then used only as fallback.
1010 bool DerivePointerAlignment;
1012 /// Disables formatting completely.
1015 /// If ``true``, clang-format detects whether function calls and
1016 /// definitions are formatted with one parameter per line.
1018 /// Each call can be bin-packed, one-per-line or inconclusive. If it is
1019 /// inconclusive, e.g. completely on one line, but a decision needs to be
1020 /// made, clang-format analyzes whether there are other bin-packed cases in
1021 /// the input file and act accordingly.
1023 /// NOTE: This is an experimental flag, that might go away or be renamed. Do
1024 /// not use this in config files, etc. Use at your own risk.
1025 bool ExperimentalAutoDetectBinPacking;
1027 /// If ``true``, clang-format adds missing namespace end comments and
1028 /// fixes invalid existing ones.
1031 /// namespace a { vs. namespace a {
1033 /// } // namespace a; }
1035 bool FixNamespaceComments;
1037 /// A vector of macros that should be interpreted as foreach loops
1038 /// instead of as function calls.
1040 /// These are expected to be macros of the form:
1042 /// FOREACH(<variable-declaration>, ...)
1046 /// In the .clang-format configuration file, this can be configured like:
1048 /// ForEachMacros: ['RANGES_FOR', 'FOREACH']
1051 /// For example: BOOST_FOREACH.
1052 std::vector<std::string> ForEachMacros;
1054 tooling::IncludeStyle IncludeStyle;
1056 /// Indent case labels one level from the switch statement.
1058 /// When ``false``, use the same indentation level as for the switch statement.
1059 /// Switch statement body is always indented one level more than case labels.
1062 /// switch (fool) { vs. switch (fool) {
1066 /// default: default:
1070 bool IndentCaseLabels;
1072 /// Options for indenting preprocessor directives.
1073 enum PPDirectiveIndentStyle {
1074 /// Does not indent any directives.
1083 /// Indents directives after the hash.
1094 /// The preprocessor directive indenting style to use.
1095 PPDirectiveIndentStyle IndentPPDirectives;
1097 /// The number of columns to use for indentation.
1103 /// if (true, false) {
1108 unsigned IndentWidth;
1110 /// Indent if a function definition or declaration is wrapped after the
1114 /// LoooooooooooooooooooooooooooooooooooooooongReturnType
1115 /// LoooooooooooooooooooooooooooooooongFunctionDeclaration();
1118 /// LoooooooooooooooooooooooooooooooooooooooongReturnType
1119 /// LoooooooooooooooooooooooooooooooongFunctionDeclaration();
1121 bool IndentWrappedFunctionNames;
1123 /// Quotation styles for JavaScript strings. Does not affect template
1125 enum JavaScriptQuoteStyle {
1126 /// Leave string quotes as they are.
1128 /// string1 = "foo";
1129 /// string2 = 'bar';
1132 /// Always use single quotes.
1134 /// string1 = 'foo';
1135 /// string2 = 'bar';
1138 /// Always use double quotes.
1140 /// string1 = "foo";
1141 /// string2 = "bar";
1146 /// The JavaScriptQuoteStyle to use for JavaScript strings.
1147 JavaScriptQuoteStyle JavaScriptQuotes;
1149 /// Whether to wrap JavaScript import/export statements.
1153 /// VeryLongImportsAreAnnoying,
1154 /// VeryLongImportsAreAnnoying,
1155 /// VeryLongImportsAreAnnoying,
1156 /// } from 'some/module.js'
1159 /// import {VeryLongImportsAreAnnoying, VeryLongImportsAreAnnoying, VeryLongImportsAreAnnoying,} from "some/module.js"
1161 bool JavaScriptWrapImports;
1163 /// If true, the empty line at the start of blocks is kept.
1166 /// if (foo) { vs. if (foo) {
1171 bool KeepEmptyLinesAtTheStartOfBlocks;
1173 /// Supported languages.
1175 /// When stored in a configuration file, specifies the language, that the
1176 /// configuration targets. When passed to the ``reformat()`` function, enables
1177 /// syntax features specific to the language.
1181 /// Should be used for C, C++.
1183 /// Should be used for Java.
1185 /// Should be used for JavaScript.
1187 /// Should be used for Objective-C, Objective-C++.
1189 /// Should be used for Protocol Buffers
1190 /// (https://developers.google.com/protocol-buffers/).
1192 /// Should be used for TableGen code.
1194 /// Should be used for Protocol Buffer messages in text format
1195 /// (https://developers.google.com/protocol-buffers/).
1198 bool isCpp() const { return Language == LK_Cpp || Language == LK_ObjC; }
1200 /// Language, this format style is targeted at.
1201 LanguageKind Language;
1203 /// A regular expression matching macros that start a block.
1206 /// MacroBlockBegin: "^NS_MAP_BEGIN|\
1208 /// MacroBlockEnd: "^\
1210 /// NS_TABLE_.*_END$"
1218 /// NS_TABLE_FOO_END
1227 /// NS_TABLE_FOO_END
1229 std::string MacroBlockBegin;
1231 /// A regular expression matching macros that end a block.
1232 std::string MacroBlockEnd;
1234 /// The maximum number of consecutive empty lines to keep.
1236 /// MaxEmptyLinesToKeep: 1 vs. MaxEmptyLinesToKeep: 0
1237 /// int f() { int f() {
1238 /// int = 1; int i = 1;
1240 /// i = foo(); return i;
1245 unsigned MaxEmptyLinesToKeep;
1247 /// Different ways to indent namespace contents.
1248 enum NamespaceIndentationKind {
1249 /// Don't indent in namespaces.
1259 /// Indent only in inner namespaces (nested in other namespaces).
1269 /// Indent in all namespaces.
1281 /// The indentation used for namespaces.
1282 NamespaceIndentationKind NamespaceIndentation;
1284 /// Controls bin-packing Objective-C protocol conformance list
1285 /// items into as few lines as possible when they go over ``ColumnLimit``.
1287 /// If ``Auto`` (the default), delegates to the value in
1288 /// ``BinPackParameters``. If that is ``true``, bin-packs Objective-C
1289 /// protocol conformance list items into as few lines as possible
1290 /// whenever they go over ``ColumnLimit``.
1292 /// If ``Always``, always bin-packs Objective-C protocol conformance
1293 /// list items into as few lines as possible whenever they go over
1294 /// ``ColumnLimit``.
1296 /// If ``Never``, lays out Objective-C protocol conformance list items
1297 /// onto individual lines whenever they go over ``ColumnLimit``.
1300 /// Always (or Auto, if BinPackParameters=true):
1301 /// @interface ccccccccccccc () <
1302 /// ccccccccccccc, ccccccccccccc,
1303 /// ccccccccccccc, ccccccccccccc> {
1306 /// Never (or Auto, if BinPackParameters=false):
1307 /// @interface ddddddddddddd () <
1311 /// ddddddddddddd> {
1314 BinPackStyle ObjCBinPackProtocolList;
1316 /// The number of characters to use for indentation of ObjC blocks.
1318 /// ObjCBlockIndentWidth: 4
1320 /// [operation setCompletionBlock:^{
1321 /// [self onOperationDone];
1324 unsigned ObjCBlockIndentWidth;
1326 /// Add a space after ``@property`` in Objective-C, i.e. use
1327 /// ``@property (readonly)`` instead of ``@property(readonly)``.
1328 bool ObjCSpaceAfterProperty;
1330 /// Add a space in front of an Objective-C protocol list, i.e. use
1331 /// ``Foo <Protocol>`` instead of ``Foo<Protocol>``.
1332 bool ObjCSpaceBeforeProtocolList;
1334 /// The penalty for breaking around an assignment operator.
1335 unsigned PenaltyBreakAssignment;
1337 /// The penalty for breaking a function call after ``call(``.
1338 unsigned PenaltyBreakBeforeFirstCallParameter;
1340 /// The penalty for each line break introduced inside a comment.
1341 unsigned PenaltyBreakComment;
1343 /// The penalty for breaking before the first ``<<``.
1344 unsigned PenaltyBreakFirstLessLess;
1346 /// The penalty for each line break introduced inside a string literal.
1347 unsigned PenaltyBreakString;
1349 /// The penalty for breaking after template declaration.
1350 unsigned PenaltyBreakTemplateDeclaration;
1352 /// The penalty for each character outside of the column limit.
1353 unsigned PenaltyExcessCharacter;
1355 /// Penalty for putting the return type of a function onto its own
1357 unsigned PenaltyReturnTypeOnItsOwnLine;
1359 /// The ``&`` and ``*`` alignment style.
1360 enum PointerAlignmentStyle {
1361 /// Align pointer to the left.
1366 /// Align pointer to the right.
1371 /// Align pointer in the middle.
1378 /// Pointer and reference alignment style.
1379 PointerAlignmentStyle PointerAlignment;
1381 /// See documentation of ``RawStringFormats``.
1382 struct RawStringFormat {
1383 /// The language of this raw string.
1384 LanguageKind Language;
1385 /// A list of raw string delimiters that match this language.
1386 std::vector<std::string> Delimiters;
1387 /// A list of enclosing function names that match this language.
1388 std::vector<std::string> EnclosingFunctions;
1389 /// The canonical delimiter for this language.
1390 std::string CanonicalDelimiter;
1391 /// The style name on which this raw string format is based on.
1392 /// If not specified, the raw string format is based on the style that this
1393 /// format is based on.
1394 std::string BasedOnStyle;
1395 bool operator==(const RawStringFormat &Other) const {
1396 return Language == Other.Language && Delimiters == Other.Delimiters &&
1397 EnclosingFunctions == Other.EnclosingFunctions &&
1398 CanonicalDelimiter == Other.CanonicalDelimiter &&
1399 BasedOnStyle == Other.BasedOnStyle;
1403 /// Defines hints for detecting supported languages code blocks in raw
1406 /// A raw string with a matching delimiter or a matching enclosing function
1407 /// name will be reformatted assuming the specified language based on the
1408 /// style for that language defined in the .clang-format file. If no style has
1409 /// been defined in the .clang-format file for the specific language, a
1410 /// predefined style given by 'BasedOnStyle' is used. If 'BasedOnStyle' is not
1411 /// found, the formatting is based on llvm style. A matching delimiter takes
1412 /// precedence over a matching enclosing function name for determining the
1413 /// language of the raw string contents.
1415 /// If a canonical delimiter is specified, occurrences of other delimiters for
1416 /// the same language will be updated to the canonical if possible.
1418 /// There should be at most one specification per language and each delimiter
1419 /// and enclosing function should not occur in multiple specifications.
1421 /// To configure this in the .clang-format file, use:
1423 /// RawStringFormats:
1424 /// - Language: TextProto
1428 /// EnclosingFunctions:
1429 /// - 'PARSE_TEXT_PROTO'
1430 /// BasedOnStyle: google
1435 /// BasedOnStyle: llvm
1436 /// CanonicalDelimiter: 'cc'
1438 std::vector<RawStringFormat> RawStringFormats;
1440 /// If ``true``, clang-format will attempt to re-flow comments.
1443 /// // veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongComment with plenty of information
1444 /// /* second veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongComment with plenty of information */
1447 /// // veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongComment with plenty of
1449 /// /* second veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongComment with plenty of
1450 /// * information */
1452 bool ReflowComments;
1454 /// If ``true``, clang-format will sort ``#includes``.
1457 /// #include "b.h" vs. #include "a.h"
1458 /// #include "a.h" #include "b.h"
1462 /// If ``true``, clang-format will sort using declarations.
1464 /// The order of using declarations is defined as follows:
1465 /// Split the strings by "::" and discard any initial empty strings. The last
1466 /// element of each list is a non-namespace name; all others are namespace
1467 /// names. Sort the lists of names lexicographically, where the sort order of
1468 /// individual names is that all non-namespace names come before all namespace
1469 /// names, and within those groups, names are in case-insensitive
1470 /// lexicographic order.
1473 /// using std::cout; vs. using std::cin;
1474 /// using std::cin; using std::cout;
1476 bool SortUsingDeclarations;
1478 /// If ``true``, a space is inserted after C style casts.
1481 /// (int) i; vs. (int)i;
1483 bool SpaceAfterCStyleCast;
1485 /// If \c true, a space will be inserted after the 'template' keyword.
1488 /// template <int> void foo(); vs. template<int> void foo();
1490 bool SpaceAfterTemplateKeyword;
1492 /// If ``false``, spaces will be removed before assignment operators.
1495 /// int a = 5; vs. int a=5;
1498 bool SpaceBeforeAssignmentOperators;
1500 /// If ``true``, a space will be inserted before a C++11 braced list
1501 /// used to initialize an object (after the preceding identifier or type).
1504 /// Foo foo { bar }; vs. Foo foo{ bar };
1506 /// vector<int> { 1, 2, 3 }; vector<int>{ 1, 2, 3 };
1507 /// new int[3] { 1, 2, 3 }; new int[3]{ 1, 2, 3 };
1509 bool SpaceBeforeCpp11BracedList;
1511 /// If ``false``, spaces will be removed before constructor initializer
1515 /// Foo::Foo() : a(a) {} Foo::Foo(): a(a) {}
1517 bool SpaceBeforeCtorInitializerColon;
1519 /// If ``false``, spaces will be removed before inheritance colon.
1522 /// class Foo : Bar {} vs. class Foo: Bar {}
1524 bool SpaceBeforeInheritanceColon;
1526 /// Different ways to put a space before opening parentheses.
1527 enum SpaceBeforeParensOptions {
1528 /// Never put a space before opening parentheses.
1537 /// Put a space before opening parentheses only after control statement
1538 /// keywords (``for/if/while...``).
1546 SBPO_ControlStatements,
1547 /// Always put a space before opening parentheses, except when it's
1548 /// prohibited by the syntax rules (in function-like macro definitions) or
1549 /// when determined by other style rules (after unary operators, opening
1550 /// parentheses, etc.)
1561 /// Defines in which cases to put a space before opening parentheses.
1562 SpaceBeforeParensOptions SpaceBeforeParens;
1564 /// If ``false``, spaces will be removed before range-based for loop
1568 /// for (auto v : values) {} vs. for(auto v: values) {}
1570 bool SpaceBeforeRangeBasedForLoopColon;
1572 /// If ``true``, spaces may be inserted into ``()``.
1575 /// void f( ) { vs. void f() {
1576 /// int x[] = {foo( ), bar( )}; int x[] = {foo(), bar()};
1577 /// if (true) { if (true) {
1582 bool SpaceInEmptyParentheses;
1584 /// The number of spaces before trailing line comments
1585 /// (``//`` - comments).
1587 /// This does not affect trailing block comments (``/*`` - comments) as
1588 /// those commonly have different usage patterns and a number of special
1591 /// SpacesBeforeTrailingComments: 3
1593 /// if (true) { // foo1
1598 unsigned SpacesBeforeTrailingComments;
1600 /// If ``true``, spaces will be inserted after ``<`` and before ``>``
1601 /// in template argument lists.
1604 /// static_cast< int >(arg); vs. static_cast<int>(arg);
1605 /// std::function< void(int) > fct; std::function<void(int)> fct;
1607 bool SpacesInAngles;
1609 /// If ``true``, spaces are inserted inside container literals (e.g.
1610 /// ObjC and Javascript array and dict literals).
1613 /// var arr = [ 1, 2, 3 ]; vs. var arr = [1, 2, 3];
1614 /// f({a : 1, b : 2, c : 3}); f({a: 1, b: 2, c: 3});
1616 bool SpacesInContainerLiterals;
1618 /// If ``true``, spaces may be inserted into C style casts.
1621 /// x = ( int32 )y vs. x = (int32)y
1623 bool SpacesInCStyleCastParentheses;
1625 /// If ``true``, spaces will be inserted after ``(`` and before ``)``.
1628 /// t f( Deleted & ) & = delete; vs. t f(Deleted &) & = delete;
1630 bool SpacesInParentheses;
1632 /// If ``true``, spaces will be inserted after ``[`` and before ``]``.
1633 /// Lambdas or unspecified size array declarations will not be affected.
1636 /// int a[ 5 ]; vs. int a[5];
1637 /// std::unique_ptr<int[]> foo() {} // Won't be affected
1639 bool SpacesInSquareBrackets;
1641 /// Supported language standards.
1642 enum LanguageStandard {
1643 /// Use C++03-compatible syntax.
1645 /// Use features of C++11, C++14 and C++1z (e.g. ``A<A<int>>`` instead of
1646 /// ``A<A<int> >``).
1648 /// Automatic detection based on the input.
1652 /// Format compatible with this standard, e.g. use ``A<A<int> >``
1653 /// instead of ``A<A<int>>`` for ``LS_Cpp03``.
1654 LanguageStandard Standard;
1656 /// The number of columns used for tab stops.
1659 /// Different ways to use tab in formatting.
1663 /// Use tabs only for indentation.
1665 /// Use tabs only for line continuation and indentation.
1666 UT_ForContinuationAndIndentation,
1667 /// Use tabs whenever we need to fill whitespace that spans at least from
1668 /// one tab stop to the next one.
1672 /// The way to use tab characters in the resulting file.
1675 bool operator==(const FormatStyle &R) const {
1676 return AccessModifierOffset == R.AccessModifierOffset &&
1677 AlignAfterOpenBracket == R.AlignAfterOpenBracket &&
1678 AlignConsecutiveAssignments == R.AlignConsecutiveAssignments &&
1679 AlignConsecutiveDeclarations == R.AlignConsecutiveDeclarations &&
1680 AlignEscapedNewlines == R.AlignEscapedNewlines &&
1681 AlignOperands == R.AlignOperands &&
1682 AlignTrailingComments == R.AlignTrailingComments &&
1683 AllowAllParametersOfDeclarationOnNextLine ==
1684 R.AllowAllParametersOfDeclarationOnNextLine &&
1685 AllowShortBlocksOnASingleLine == R.AllowShortBlocksOnASingleLine &&
1686 AllowShortCaseLabelsOnASingleLine ==
1687 R.AllowShortCaseLabelsOnASingleLine &&
1688 AllowShortFunctionsOnASingleLine ==
1689 R.AllowShortFunctionsOnASingleLine &&
1690 AllowShortIfStatementsOnASingleLine ==
1691 R.AllowShortIfStatementsOnASingleLine &&
1692 AllowShortLoopsOnASingleLine == R.AllowShortLoopsOnASingleLine &&
1693 AlwaysBreakAfterReturnType == R.AlwaysBreakAfterReturnType &&
1694 AlwaysBreakBeforeMultilineStrings ==
1695 R.AlwaysBreakBeforeMultilineStrings &&
1696 AlwaysBreakTemplateDeclarations ==
1697 R.AlwaysBreakTemplateDeclarations &&
1698 BinPackArguments == R.BinPackArguments &&
1699 BinPackParameters == R.BinPackParameters &&
1700 BreakBeforeBinaryOperators == R.BreakBeforeBinaryOperators &&
1701 BreakBeforeBraces == R.BreakBeforeBraces &&
1702 BreakBeforeTernaryOperators == R.BreakBeforeTernaryOperators &&
1703 BreakConstructorInitializers == R.BreakConstructorInitializers &&
1704 CompactNamespaces == R.CompactNamespaces &&
1705 BreakAfterJavaFieldAnnotations == R.BreakAfterJavaFieldAnnotations &&
1706 BreakStringLiterals == R.BreakStringLiterals &&
1707 ColumnLimit == R.ColumnLimit && CommentPragmas == R.CommentPragmas &&
1708 BreakInheritanceList == R.BreakInheritanceList &&
1709 ConstructorInitializerAllOnOneLineOrOnePerLine ==
1710 R.ConstructorInitializerAllOnOneLineOrOnePerLine &&
1711 ConstructorInitializerIndentWidth ==
1712 R.ConstructorInitializerIndentWidth &&
1713 ContinuationIndentWidth == R.ContinuationIndentWidth &&
1714 Cpp11BracedListStyle == R.Cpp11BracedListStyle &&
1715 DerivePointerAlignment == R.DerivePointerAlignment &&
1716 DisableFormat == R.DisableFormat &&
1717 ExperimentalAutoDetectBinPacking ==
1718 R.ExperimentalAutoDetectBinPacking &&
1719 FixNamespaceComments == R.FixNamespaceComments &&
1720 ForEachMacros == R.ForEachMacros &&
1721 IncludeStyle.IncludeBlocks == R.IncludeStyle.IncludeBlocks &&
1722 IncludeStyle.IncludeCategories == R.IncludeStyle.IncludeCategories &&
1723 IndentCaseLabels == R.IndentCaseLabels &&
1724 IndentPPDirectives == R.IndentPPDirectives &&
1725 IndentWidth == R.IndentWidth && Language == R.Language &&
1726 IndentWrappedFunctionNames == R.IndentWrappedFunctionNames &&
1727 JavaScriptQuotes == R.JavaScriptQuotes &&
1728 JavaScriptWrapImports == R.JavaScriptWrapImports &&
1729 KeepEmptyLinesAtTheStartOfBlocks ==
1730 R.KeepEmptyLinesAtTheStartOfBlocks &&
1731 MacroBlockBegin == R.MacroBlockBegin &&
1732 MacroBlockEnd == R.MacroBlockEnd &&
1733 MaxEmptyLinesToKeep == R.MaxEmptyLinesToKeep &&
1734 NamespaceIndentation == R.NamespaceIndentation &&
1735 ObjCBinPackProtocolList == R.ObjCBinPackProtocolList &&
1736 ObjCBlockIndentWidth == R.ObjCBlockIndentWidth &&
1737 ObjCSpaceAfterProperty == R.ObjCSpaceAfterProperty &&
1738 ObjCSpaceBeforeProtocolList == R.ObjCSpaceBeforeProtocolList &&
1739 PenaltyBreakAssignment == R.PenaltyBreakAssignment &&
1740 PenaltyBreakBeforeFirstCallParameter ==
1741 R.PenaltyBreakBeforeFirstCallParameter &&
1742 PenaltyBreakComment == R.PenaltyBreakComment &&
1743 PenaltyBreakFirstLessLess == R.PenaltyBreakFirstLessLess &&
1744 PenaltyBreakString == R.PenaltyBreakString &&
1745 PenaltyExcessCharacter == R.PenaltyExcessCharacter &&
1746 PenaltyReturnTypeOnItsOwnLine == R.PenaltyReturnTypeOnItsOwnLine &&
1747 PenaltyBreakTemplateDeclaration ==
1748 R.PenaltyBreakTemplateDeclaration &&
1749 PointerAlignment == R.PointerAlignment &&
1750 RawStringFormats == R.RawStringFormats &&
1751 SpaceAfterCStyleCast == R.SpaceAfterCStyleCast &&
1752 SpaceAfterTemplateKeyword == R.SpaceAfterTemplateKeyword &&
1753 SpaceBeforeAssignmentOperators == R.SpaceBeforeAssignmentOperators &&
1754 SpaceBeforeCpp11BracedList == R.SpaceBeforeCpp11BracedList &&
1755 SpaceBeforeCtorInitializerColon ==
1756 R.SpaceBeforeCtorInitializerColon &&
1757 SpaceBeforeInheritanceColon == R.SpaceBeforeInheritanceColon &&
1758 SpaceBeforeParens == R.SpaceBeforeParens &&
1759 SpaceBeforeRangeBasedForLoopColon ==
1760 R.SpaceBeforeRangeBasedForLoopColon &&
1761 SpaceInEmptyParentheses == R.SpaceInEmptyParentheses &&
1762 SpacesBeforeTrailingComments == R.SpacesBeforeTrailingComments &&
1763 SpacesInAngles == R.SpacesInAngles &&
1764 SpacesInContainerLiterals == R.SpacesInContainerLiterals &&
1765 SpacesInCStyleCastParentheses == R.SpacesInCStyleCastParentheses &&
1766 SpacesInParentheses == R.SpacesInParentheses &&
1767 SpacesInSquareBrackets == R.SpacesInSquareBrackets &&
1768 Standard == R.Standard && TabWidth == R.TabWidth &&
1772 llvm::Optional<FormatStyle> GetLanguageStyle(LanguageKind Language) const;
1774 // Stores per-language styles. A FormatStyle instance inside has an empty
1775 // StyleSet. A FormatStyle instance returned by the Get method has its
1776 // StyleSet set to a copy of the originating StyleSet, effectively keeping the
1777 // internal representation of that StyleSet alive.
1779 // The memory management and ownership reminds of a birds nest: chicks
1780 // leaving the nest take photos of the nest with them.
1781 struct FormatStyleSet {
1782 typedef std::map<FormatStyle::LanguageKind, FormatStyle> MapType;
1784 llvm::Optional<FormatStyle> Get(FormatStyle::LanguageKind Language) const;
1786 // Adds \p Style to this FormatStyleSet. Style must not have an associated
1788 // Style.Language should be different than LK_None. If this FormatStyleSet
1789 // already contains an entry for Style.Language, that gets replaced with the
1791 void Add(FormatStyle Style);
1793 // Clears this FormatStyleSet.
1797 std::shared_ptr<MapType> Styles;
1800 static FormatStyleSet BuildStyleSetFromConfiguration(
1801 const FormatStyle &MainStyle,
1802 const std::vector<FormatStyle> &ConfigurationStyles);
1805 FormatStyleSet StyleSet;
1807 friend std::error_code parseConfiguration(StringRef Text, FormatStyle *Style);
1810 /// Returns a format style complying with the LLVM coding standards:
1811 /// http://llvm.org/docs/CodingStandards.html.
1812 FormatStyle getLLVMStyle();
1814 /// Returns a format style complying with one of Google's style guides:
1815 /// http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml.
1816 /// http://google-styleguide.googlecode.com/svn/trunk/javascriptguide.xml.
1817 /// https://developers.google.com/protocol-buffers/docs/style.
1818 FormatStyle getGoogleStyle(FormatStyle::LanguageKind Language);
1820 /// Returns a format style complying with Chromium's style guide:
1821 /// http://www.chromium.org/developers/coding-style.
1822 FormatStyle getChromiumStyle(FormatStyle::LanguageKind Language);
1824 /// Returns a format style complying with Mozilla's style guide:
1825 /// https://developer.mozilla.org/en-US/docs/Developer_Guide/Coding_Style.
1826 FormatStyle getMozillaStyle();
1828 /// Returns a format style complying with Webkit's style guide:
1829 /// http://www.webkit.org/coding/coding-style.html
1830 FormatStyle getWebKitStyle();
1832 /// Returns a format style complying with GNU Coding Standards:
1833 /// http://www.gnu.org/prep/standards/standards.html
1834 FormatStyle getGNUStyle();
1836 /// Returns style indicating formatting should be not applied at all.
1837 FormatStyle getNoStyle();
1839 /// Gets a predefined style for the specified language by name.
1841 /// Currently supported names: LLVM, Google, Chromium, Mozilla. Names are
1842 /// compared case-insensitively.
1844 /// Returns ``true`` if the Style has been set.
1845 bool getPredefinedStyle(StringRef Name, FormatStyle::LanguageKind Language,
1846 FormatStyle *Style);
1848 /// Parse configuration from YAML-formatted text.
1850 /// Style->Language is used to get the base style, if the ``BasedOnStyle``
1851 /// option is present.
1853 /// The FormatStyleSet of Style is reset.
1855 /// When ``BasedOnStyle`` is not present, options not present in the YAML
1856 /// document, are retained in \p Style.
1857 std::error_code parseConfiguration(StringRef Text, FormatStyle *Style);
1859 /// Gets configuration in a YAML string.
1860 std::string configurationAsText(const FormatStyle &Style);
1862 /// Returns the replacements necessary to sort all ``#include`` blocks
1863 /// that are affected by ``Ranges``.
1864 tooling::Replacements sortIncludes(const FormatStyle &Style, StringRef Code,
1865 ArrayRef<tooling::Range> Ranges,
1867 unsigned *Cursor = nullptr);
1869 /// Returns the replacements corresponding to applying and formatting
1870 /// \p Replaces on success; otheriwse, return an llvm::Error carrying
1871 /// llvm::StringError.
1872 llvm::Expected<tooling::Replacements>
1873 formatReplacements(StringRef Code, const tooling::Replacements &Replaces,
1874 const FormatStyle &Style);
1876 /// Returns the replacements corresponding to applying \p Replaces and
1877 /// cleaning up the code after that on success; otherwise, return an llvm::Error
1878 /// carrying llvm::StringError.
1879 /// This also supports inserting/deleting C++ #include directives:
1880 /// - If a replacement has offset UINT_MAX, length 0, and a replacement text
1881 /// that is an #include directive, this will insert the #include into the
1882 /// correct block in the \p Code.
1883 /// - If a replacement has offset UINT_MAX, length 1, and a replacement text
1884 /// that is the name of the header to be removed, the header will be removed
1885 /// from \p Code if it exists.
1886 /// The include manipulation is done via `tooling::HeaderInclude`, see its
1887 /// documentation for more details on how include insertion points are found and
1888 /// what edits are produced.
1889 llvm::Expected<tooling::Replacements>
1890 cleanupAroundReplacements(StringRef Code, const tooling::Replacements &Replaces,
1891 const FormatStyle &Style);
1893 /// Represents the status of a formatting attempt.
1894 struct FormattingAttemptStatus {
1895 /// A value of ``false`` means that any of the affected ranges were not
1896 /// formatted due to a non-recoverable syntax error.
1897 bool FormatComplete = true;
1899 /// If ``FormatComplete`` is false, ``Line`` records a one-based
1900 /// original line number at which a syntax error might have occurred. This is
1901 /// based on a best-effort analysis and could be imprecise.
1905 /// Reformats the given \p Ranges in \p Code.
1907 /// Each range is extended on either end to its next bigger logic unit, i.e.
1908 /// everything that might influence its formatting or might be influenced by its
1911 /// Returns the ``Replacements`` necessary to make all \p Ranges comply with
1914 /// If ``Status`` is non-null, its value will be populated with the status of
1915 /// this formatting attempt. See \c FormattingAttemptStatus.
1916 tooling::Replacements reformat(const FormatStyle &Style, StringRef Code,
1917 ArrayRef<tooling::Range> Ranges,
1918 StringRef FileName = "<stdin>",
1919 FormattingAttemptStatus *Status = nullptr);
1921 /// Same as above, except if ``IncompleteFormat`` is non-null, its value
1922 /// will be set to true if any of the affected ranges were not formatted due to
1923 /// a non-recoverable syntax error.
1924 tooling::Replacements reformat(const FormatStyle &Style, StringRef Code,
1925 ArrayRef<tooling::Range> Ranges,
1927 bool *IncompleteFormat);
1929 /// Clean up any erroneous/redundant code in the given \p Ranges in \p
1932 /// Returns the ``Replacements`` that clean up all \p Ranges in \p Code.
1933 tooling::Replacements cleanup(const FormatStyle &Style, StringRef Code,
1934 ArrayRef<tooling::Range> Ranges,
1935 StringRef FileName = "<stdin>");
1937 /// Fix namespace end comments in the given \p Ranges in \p Code.
1939 /// Returns the ``Replacements`` that fix the namespace comments in all
1940 /// \p Ranges in \p Code.
1941 tooling::Replacements fixNamespaceEndComments(const FormatStyle &Style,
1943 ArrayRef<tooling::Range> Ranges,
1944 StringRef FileName = "<stdin>");
1946 /// Sort consecutive using declarations in the given \p Ranges in
1949 /// Returns the ``Replacements`` that sort the using declarations in all
1950 /// \p Ranges in \p Code.
1951 tooling::Replacements sortUsingDeclarations(const FormatStyle &Style,
1953 ArrayRef<tooling::Range> Ranges,
1954 StringRef FileName = "<stdin>");
1956 /// Returns the ``LangOpts`` that the formatter expects you to set.
1958 /// \param Style determines specific settings for lexing mode.
1959 LangOptions getFormattingLangOpts(const FormatStyle &Style = getLLVMStyle());
1961 /// Description to be used for help text for a ``llvm::cl`` option for
1962 /// specifying format style. The description is closely related to the operation
1963 /// of ``getStyle()``.
1964 extern const char *StyleOptionHelpDescription;
1966 /// The suggested format style to use by default. This allows tools using
1967 /// `getStyle` to have a consistent default style.
1968 /// Different builds can modify the value to the preferred styles.
1969 extern const char *DefaultFormatStyle;
1971 /// The suggested predefined style to use as the fallback style in `getStyle`.
1972 /// Different builds can modify the value to the preferred styles.
1973 extern const char *DefaultFallbackStyle;
1975 /// Construct a FormatStyle based on ``StyleName``.
1977 /// ``StyleName`` can take several forms:
1978 /// * "{<key>: <value>, ...}" - Set specic style parameters.
1979 /// * "<style name>" - One of the style names supported by
1980 /// getPredefinedStyle().
1981 /// * "file" - Load style configuration from a file called ``.clang-format``
1982 /// located in one of the parent directories of ``FileName`` or the current
1983 /// directory if ``FileName`` is empty.
1985 /// \param[in] StyleName Style name to interpret according to the description
1987 /// \param[in] FileName Path to start search for .clang-format if ``StyleName``
1989 /// \param[in] FallbackStyle The name of a predefined style used to fallback to
1990 /// in case \p StyleName is "file" and no file can be found.
1991 /// \param[in] Code The actual code to be formatted. Used to determine the
1992 /// language if the filename isn't sufficient.
1993 /// \param[in] FS The underlying file system, in which the file resides. By
1994 /// default, the file system is the real file system.
1996 /// \returns FormatStyle as specified by ``StyleName``. If ``StyleName`` is
1997 /// "file" and no file is found, returns ``FallbackStyle``. If no style could be
1998 /// determined, returns an Error.
1999 llvm::Expected<FormatStyle> getStyle(StringRef StyleName, StringRef FileName,
2000 StringRef FallbackStyle,
2001 StringRef Code = "",
2002 vfs::FileSystem *FS = nullptr);
2004 // Guesses the language from the ``FileName`` and ``Code`` to be formatted.
2005 // Defaults to FormatStyle::LK_Cpp.
2006 FormatStyle::LanguageKind guessLanguage(StringRef FileName, StringRef Code);
2008 // Returns a string representation of ``Language``.
2009 inline StringRef getLanguageName(FormatStyle::LanguageKind Language) {
2011 case FormatStyle::LK_Cpp:
2013 case FormatStyle::LK_ObjC:
2014 return "Objective-C";
2015 case FormatStyle::LK_Java:
2017 case FormatStyle::LK_JavaScript:
2018 return "JavaScript";
2019 case FormatStyle::LK_Proto:
2021 case FormatStyle::LK_TextProto:
2028 } // end namespace format
2029 } // end namespace clang
2033 struct is_error_code_enum<clang::format::ParseError> : std::true_type {};
2036 #endif // LLVM_CLANG_FORMAT_FORMAT_H