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>
35 class DiagnosticConsumer;
39 enum class ParseError { Success = 0, Error, Unsuitable };
40 class ParseErrorCategory final : public std::error_category {
42 const char *name() const noexcept override;
43 std::string message(int EV) const override;
45 const std::error_category &getParseCategory();
46 std::error_code make_error_code(ParseError e);
48 /// The ``FormatStyle`` is used to configure the formatting to follow
49 /// specific guidelines.
51 /// The extra indent or outdent of access modifiers, e.g. ``public:``.
52 int AccessModifierOffset;
54 /// Different styles for aligning after open brackets.
55 enum BracketAlignmentStyle {
56 /// Align parameters on the open bracket, e.g.:
58 /// someLongFunction(argument1,
62 /// Don't align, instead use ``ContinuationIndentWidth``, e.g.:
64 /// someLongFunction(argument1,
68 /// Always break after an open bracket, if the parameters don't fit
69 /// on a single line, e.g.:
72 /// argument1, argument2);
77 /// If ``true``, horizontally aligns arguments after an open bracket.
79 /// This applies to round brackets (parentheses), angle brackets and square
81 BracketAlignmentStyle AlignAfterOpenBracket;
83 /// If ``true``, aligns consecutive assignments.
85 /// This will align the assignment operators of consecutive lines. This
86 /// will result in formattings like
92 bool AlignConsecutiveAssignments;
94 /// If ``true``, aligns consecutive declarations.
96 /// This will align the declaration names of consecutive lines. This
97 /// will result in formattings like
101 /// std::string ccc = 23;
103 bool AlignConsecutiveDeclarations;
105 /// Different styles for aligning escaped newlines.
106 enum EscapedNewlineAlignmentStyle {
107 /// Don't align escaped newlines.
115 /// Align escaped newlines as far left as possible.
126 /// Align escaped newlines in the right-most column.
136 /// Options for aligning backslashes in escaped newlines.
137 EscapedNewlineAlignmentStyle AlignEscapedNewlines;
139 /// If ``true``, horizontally align operands of binary and ternary
142 /// Specifically, this aligns operands of a single expression that needs to be
143 /// split over multiple lines, e.g.:
145 /// int aaa = bbbbbbbbbbbbbbb +
150 /// If ``true``, aligns trailing comments.
153 /// int a; // My comment a vs. int a; // My comment a
154 /// int b = 2; // comment b int b = 2; // comment about b
156 bool AlignTrailingComments;
158 /// If the function declaration doesn't fit on a line,
159 /// allow putting all parameters of a function declaration onto
160 /// the next line even if ``BinPackParameters`` is ``false``.
164 /// int a, int b, int c, int d, int e);
167 /// void myFunction(int a,
173 bool AllowAllParametersOfDeclarationOnNextLine;
175 /// Allows contracting simple braced statements to a single line.
177 /// E.g., this allows ``if (a) { return; }`` to be put on a single line.
178 bool AllowShortBlocksOnASingleLine;
180 /// If ``true``, short case labels will be contracted to a single line.
183 /// switch (a) { vs. switch (a) {
184 /// case 1: x = 1; break; case 1:
185 /// case 2: return; x = 1;
191 bool AllowShortCaseLabelsOnASingleLine;
193 /// Different styles for merging short functions containing at most one
195 enum ShortFunctionStyle {
196 /// Never merge functions into a single line.
198 /// Only merge functions defined inside a class. Same as "inline",
199 /// except it does not implies "empty": i.e. top level empty functions
200 /// are not merged either.
203 /// void f() { foo(); }
212 /// Only merge empty functions.
220 /// Only merge functions defined inside a class. Implies "empty".
223 /// void f() { foo(); }
231 /// Merge all functions fitting on a single line.
234 /// void f() { foo(); }
236 /// void f() { bar(); }
241 /// Dependent on the value, ``int f() { return 0; }`` can be put on a
243 ShortFunctionStyle AllowShortFunctionsOnASingleLine;
245 /// If ``true``, ``if (a) return;`` can be put on a single line.
246 bool AllowShortIfStatementsOnASingleLine;
248 /// If ``true``, ``while (true) continue;`` can be put on a single
250 bool AllowShortLoopsOnASingleLine;
252 /// Different ways to break after the function definition return type.
253 /// This option is **deprecated** and is retained for backwards compatibility.
254 enum DefinitionReturnTypeBreakingStyle {
255 /// Break after return type automatically.
256 /// ``PenaltyReturnTypeOnItsOwnLine`` is taken into account.
258 /// Always break after the return type.
260 /// Always break after the return types of top-level functions.
264 /// Different ways to break after the function definition or
265 /// declaration return type.
266 enum ReturnTypeBreakingStyle {
267 /// Break after return type automatically.
268 /// ``PenaltyReturnTypeOnItsOwnLine`` is taken into account.
271 /// int f() { return 0; };
274 /// int f() { return 1; }
277 /// Always break after the return type.
293 /// Always break after the return types of top-level functions.
296 /// int f() { return 0; };
306 /// Always break after the return type of function definitions.
321 /// Always break after the return type of top-level definitions.
324 /// int f() { return 0; };
332 RTBS_TopLevelDefinitions,
335 /// The function definition return type breaking style to use. This
336 /// option is **deprecated** and is retained for backwards compatibility.
337 DefinitionReturnTypeBreakingStyle AlwaysBreakAfterDefinitionReturnType;
339 /// The function declaration return type breaking style to use.
340 ReturnTypeBreakingStyle AlwaysBreakAfterReturnType;
342 /// If ``true``, always break before multiline string literals.
344 /// This flag is mean to make cases where there are multiple multiline strings
345 /// in a file look more consistent. Thus, it will only take effect if wrapping
346 /// the string at that point leads to it being indented
347 /// ``ContinuationIndentWidth`` spaces from the start of the line.
350 /// aaaa = vs. aaaa = "bbbb"
354 bool AlwaysBreakBeforeMultilineStrings;
356 /// Different ways to break after the template declaration.
357 enum BreakTemplateDeclarationsStyle {
358 /// Do not force break before declaration.
359 /// ``PenaltyBreakTemplateDeclaration`` is taken into account.
361 /// template <typename T> T foo() {
363 /// template <typename T> T foo(int aaaaaaaaaaaaaaaaaaaaa,
364 /// int bbbbbbbbbbbbbbbbbbbbb) {
368 /// Force break after template declaration only when the following
369 /// declaration spans multiple lines.
371 /// template <typename T> T foo() {
373 /// template <typename T>
374 /// T foo(int aaaaaaaaaaaaaaaaaaaaa,
375 /// int bbbbbbbbbbbbbbbbbbbbb) {
379 /// Always break after template declaration.
381 /// template <typename T>
384 /// template <typename T>
385 /// T foo(int aaaaaaaaaaaaaaaaaaaaa,
386 /// int bbbbbbbbbbbbbbbbbbbbb) {
392 /// The template declaration breaking style to use.
393 BreakTemplateDeclarationsStyle AlwaysBreakTemplateDeclarations;
395 /// If ``false``, a function call's arguments will either be all on the
396 /// same line or will have one line each.
400 /// f(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaa,
401 /// aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);
406 /// f(aaaaaaaaaaaaaaaaaaaa,
407 /// aaaaaaaaaaaaaaaaaaaa,
408 /// aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);
411 bool BinPackArguments;
413 /// If ``false``, a function declaration's or function definition's
414 /// parameters will either all be on the same line or will have one line each.
417 /// void f(int aaaaaaaaaaaaaaaaaaaa, int aaaaaaaaaaaaaaaaaaaa,
418 /// int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}
421 /// void f(int aaaaaaaaaaaaaaaaaaaa,
422 /// int aaaaaaaaaaaaaaaaaaaa,
423 /// int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}
425 bool BinPackParameters;
427 /// The style of wrapping parameters on the same line (bin-packed) or
428 /// on one line each.
430 /// Automatically determine parameter bin-packing behavior.
432 /// Always bin-pack parameters.
434 /// Never bin-pack parameters.
438 /// The style of breaking before or after binary operators.
439 enum BinaryOperatorStyle {
440 /// Break after operators.
442 /// LooooooooooongType loooooooooooooooooooooongVariable =
443 /// someLooooooooooooooooongFunction();
445 /// bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +
446 /// aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==
447 /// aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa &&
448 /// aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >
449 /// ccccccccccccccccccccccccccccccccccccccccc;
452 /// Break before operators that aren't assignments.
454 /// LooooooooooongType loooooooooooooooooooooongVariable =
455 /// someLooooooooooooooooongFunction();
457 /// bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
458 /// + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
459 /// == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
460 /// && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
461 /// > ccccccccccccccccccccccccccccccccccccccccc;
464 /// Break before operators.
466 /// LooooooooooongType loooooooooooooooooooooongVariable
467 /// = someLooooooooooooooooongFunction();
469 /// bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
470 /// + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
471 /// == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
472 /// && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
473 /// > ccccccccccccccccccccccccccccccccccccccccc;
478 /// The way to wrap binary operators.
479 BinaryOperatorStyle BreakBeforeBinaryOperators;
481 /// Different ways to attach braces to their surrounding context.
482 enum BraceBreakingStyle {
483 /// Always attach braces to surrounding context.
489 /// void foo() { bar(); }
494 /// enum X : int { A, B };
497 /// Like ``Attach``, but break before braces on function, namespace and
498 /// class definitions.
504 /// void foo() { bar(); }
511 /// enum X : int { A, B };
514 /// Like ``Attach``, but break before braces on enum, function, and record
521 /// void foo() { bar(); }
528 /// enum X : int { A, B };
531 /// Like ``Attach``, but break before function definitions, ``catch``, and
539 /// void foo() { bar(); }
546 /// enum X : int { A, B };
549 /// Always break before braces.
556 /// void foo() { bar(); }
563 /// enum X : int { A, B };
566 /// Always break before braces and add an extra level of indentation to
567 /// braces of control statements, not to those of class, function
568 /// or other definitions.
577 /// void foo() { bar(); }
594 /// Like ``Attach``, but break before functions.
600 /// void foo() { bar(); }
606 /// enum X : int { A, B };
609 /// Configure each individual brace in `BraceWrapping`.
613 /// The brace breaking style to use.
614 BraceBreakingStyle BreakBeforeBraces;
616 /// Precise control over the wrapping of braces.
618 /// # Should be declared this way:
619 /// BreakBeforeBraces: Custom
623 struct BraceWrappingFlags {
624 /// Wrap class definitions.
634 /// Wrap control statements (``if``/``for``/``while``/``switch``/..).
641 /// for (int i = 0; i < 10; ++i)
648 /// for (int i = 0; i < 10; ++i) {
651 bool AfterControlStatement;
652 /// Wrap enum definitions.
661 /// enum X : int { B };
664 /// Wrap function definitions.
680 /// Wrap namespace definitions.
696 /// Wrap ObjC definitions (interfaces, implementations...).
697 /// \note @autoreleasepool and @synchronized blocks are wrapped
698 /// according to `AfterControlStatement` flag.
699 bool AfterObjCDeclaration;
700 /// Wrap struct definitions.
714 /// Wrap union definitions.
728 /// Wrap extern blocks.
741 bool AfterExternBlock;
742 /// Wrap before ``catch``.
758 /// Wrap before ``else``.
772 /// Indent the wrapped braces themselves.
774 /// If ``false``, empty function body can be put on a single line.
775 /// This option is used only if the opening brace of the function has
776 /// already been wrapped, i.e. the `AfterFunction` brace wrapping mode is
777 /// set, and the function could/should not be put on a single line (as per
778 /// `AllowShortFunctionsOnASingleLine` and constructor formatting options).
780 /// int f() vs. inf f()
785 bool SplitEmptyFunction;
786 /// If ``false``, empty record (e.g. class, struct or union) body
787 /// can be put on a single line. This option is used only if the opening
788 /// brace of the record has already been wrapped, i.e. the `AfterClass`
789 /// (for classes) brace wrapping mode is set.
791 /// class Foo vs. class Foo
796 bool SplitEmptyRecord;
797 /// If ``false``, empty namespace body can be put on a single line.
798 /// This option is used only if the opening brace of the namespace has
799 /// already been wrapped, i.e. the `AfterNamespace` brace wrapping mode is
802 /// namespace Foo vs. namespace Foo
807 bool SplitEmptyNamespace;
810 /// Control of individual brace wrapping cases.
812 /// If ``BreakBeforeBraces`` is set to ``BS_Custom``, use this to specify how
813 /// each individual brace case should be handled. Otherwise, this is ignored.
815 /// # Example of usage:
816 /// BreakBeforeBraces: Custom
819 /// AfterStruct: false
820 /// SplitEmptyFunction: false
822 BraceWrappingFlags BraceWrapping;
824 /// If ``true``, ternary operators will be placed after line breaks.
827 /// veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongDescription
829 /// : SecondValueVeryVeryVeryVeryLong;
832 /// veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongDescription ?
834 /// SecondValueVeryVeryVeryVeryLong;
836 bool BreakBeforeTernaryOperators;
838 /// Different ways to break initializers.
839 enum BreakConstructorInitializersStyle {
840 /// Break constructor initializers before the colon and after the commas.
843 /// : initializer1(),
847 /// Break constructor initializers before the colon and commas, and align
848 /// the commas with the colon.
855 /// Break constructor initializers after the colon and commas.
864 /// The constructor initializers style to use.
865 BreakConstructorInitializersStyle BreakConstructorInitializers;
867 /// Break after each annotation on a field in Java files.
870 /// @Partial vs. @Partial @Mock DataLoad loader;
874 bool BreakAfterJavaFieldAnnotations;
876 /// Allow breaking string literals when formatting.
877 bool BreakStringLiterals;
879 /// The column limit.
881 /// A column limit of ``0`` means that there is no column limit. In this case,
882 /// clang-format will respect the input's line breaking decisions within
883 /// statements unless they contradict other rules.
884 unsigned ColumnLimit;
886 /// A regular expression that describes comments with special meaning,
887 /// which should not be split into lines or otherwise changed.
889 /// // CommentPragmas: '^ FOOBAR pragma:'
890 /// // Will leave the following line unaffected
891 /// #include <vector> // FOOBAR pragma: keep
893 std::string CommentPragmas;
895 /// Different ways to break inheritance list.
896 enum BreakInheritanceListStyle {
897 /// Break inheritance list before the colon and after the commas.
905 /// Break inheritance list before the colon and commas, and align
906 /// the commas with the colon.
914 /// Break inheritance list after the colon and commas.
924 /// The inheritance list style to use.
925 BreakInheritanceListStyle BreakInheritanceList;
927 /// If ``true``, consecutive namespace declarations will be on the same
928 /// line. If ``false``, each namespace is declared on a new line.
931 /// namespace Foo { namespace Bar {
941 /// If it does not fit on a single line, the overflowing namespaces get
944 /// namespace Foo { namespace Bar {
945 /// namespace Extra {
948 bool CompactNamespaces;
950 /// If the constructor initializers don't fit on a line, put each
951 /// initializer on its own line.
954 /// SomeClass::Constructor()
955 /// : aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa) {
960 /// SomeClass::Constructor()
961 /// : aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaa),
962 /// aaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa) {
966 bool ConstructorInitializerAllOnOneLineOrOnePerLine;
968 /// The number of characters to use for indentation of constructor
969 /// initializer lists as well as inheritance lists.
970 unsigned ConstructorInitializerIndentWidth;
972 /// Indent width for line continuations.
974 /// ContinuationIndentWidth: 2
976 /// int i = // VeryVeryVeryVeryVeryLongComment
977 /// longFunction( // Again a long comment
980 unsigned ContinuationIndentWidth;
982 /// If ``true``, format braced lists as best suited for C++11 braced
985 /// Important differences:
986 /// - No spaces inside the braced list.
987 /// - No line break before the closing brace.
988 /// - Indentation with the continuation indent, not with the block indent.
990 /// Fundamentally, C++11 braced lists are formatted exactly like function
991 /// calls would be formatted in their place. If the braced list follows a name
992 /// (e.g. a type or variable name), clang-format formats as if the ``{}`` were
993 /// the parentheses of a function call with that name. If there is no name,
994 /// a zero-length name is assumed.
997 /// vector<int> x{1, 2, 3, 4}; vs. vector<int> x{ 1, 2, 3, 4 };
998 /// vector<T> x{{}, {}, {}, {}}; vector<T> x{ {}, {}, {}, {} };
999 /// f(MyMap[{composite, key}]); f(MyMap[{ composite, key }]);
1000 /// new int[3]{1, 2, 3}; new int[3]{ 1, 2, 3 };
1002 bool Cpp11BracedListStyle;
1004 /// If ``true``, analyze the formatted file for the most common
1005 /// alignment of ``&`` and ``*``.
1006 /// Pointer and reference alignment styles are going to be updated according
1007 /// to the preferences found in the file.
1008 /// ``PointerAlignment`` is then used only as fallback.
1009 bool DerivePointerAlignment;
1011 /// Disables formatting completely.
1014 /// If ``true``, clang-format detects whether function calls and
1015 /// definitions are formatted with one parameter per line.
1017 /// Each call can be bin-packed, one-per-line or inconclusive. If it is
1018 /// inconclusive, e.g. completely on one line, but a decision needs to be
1019 /// made, clang-format analyzes whether there are other bin-packed cases in
1020 /// the input file and act accordingly.
1022 /// NOTE: This is an experimental flag, that might go away or be renamed. Do
1023 /// not use this in config files, etc. Use at your own risk.
1024 bool ExperimentalAutoDetectBinPacking;
1026 /// If ``true``, clang-format adds missing namespace end comments and
1027 /// fixes invalid existing ones.
1030 /// namespace a { vs. namespace a {
1032 /// } // namespace a; }
1034 bool FixNamespaceComments;
1036 /// A vector of macros that should be interpreted as foreach loops
1037 /// instead of as function calls.
1039 /// These are expected to be macros of the form:
1041 /// FOREACH(<variable-declaration>, ...)
1045 /// In the .clang-format configuration file, this can be configured like:
1047 /// ForEachMacros: ['RANGES_FOR', 'FOREACH']
1050 /// For example: BOOST_FOREACH.
1051 std::vector<std::string> ForEachMacros;
1053 /// A vector of macros that should be interpreted as complete
1056 /// Typical macros are expressions, and require a semi-colon to be
1057 /// added; sometimes this is not the case, and this allows to make
1058 /// clang-format aware of such cases.
1060 /// For example: Q_UNUSED
1061 std::vector<std::string> StatementMacros;
1063 tooling::IncludeStyle IncludeStyle;
1065 /// Indent case labels one level from the switch statement.
1067 /// When ``false``, use the same indentation level as for the switch statement.
1068 /// Switch statement body is always indented one level more than case labels.
1071 /// switch (fool) { vs. switch (fool) {
1075 /// default: default:
1079 bool IndentCaseLabels;
1081 /// Options for indenting preprocessor directives.
1082 enum PPDirectiveIndentStyle {
1083 /// Does not indent any directives.
1092 /// Indents directives after the hash.
1103 /// The preprocessor directive indenting style to use.
1104 PPDirectiveIndentStyle IndentPPDirectives;
1106 /// The number of columns to use for indentation.
1112 /// if (true, false) {
1117 unsigned IndentWidth;
1119 /// Indent if a function definition or declaration is wrapped after the
1123 /// LoooooooooooooooooooooooooooooooooooooooongReturnType
1124 /// LoooooooooooooooooooooooooooooooongFunctionDeclaration();
1127 /// LoooooooooooooooooooooooooooooooooooooooongReturnType
1128 /// LoooooooooooooooooooooooooooooooongFunctionDeclaration();
1130 bool IndentWrappedFunctionNames;
1132 /// A vector of prefixes ordered by the desired groups for Java imports.
1134 /// Each group is seperated by a newline. Static imports will also follow the
1135 /// same grouping convention above all non-static imports. One group's prefix
1136 /// can be a subset of another - the longest prefix is always matched. Within
1137 /// a group, the imports are ordered lexicographically.
1139 /// In the .clang-format configuration file, this can be configured like
1140 /// in the following yaml example. This will result in imports being
1141 /// formatted as in the Java example below.
1143 /// JavaImportGroups: ['com.example', 'com', 'org']
1147 /// import static com.example.function1;
1149 /// import static com.test.function2;
1151 /// import static org.example.function3;
1153 /// import com.example.ClassA;
1154 /// import com.example.Test;
1155 /// import com.example.a.ClassB;
1157 /// import com.test.ClassC;
1159 /// import org.example.ClassD;
1161 std::vector<std::string> JavaImportGroups;
1163 /// Quotation styles for JavaScript strings. Does not affect template
1165 enum JavaScriptQuoteStyle {
1166 /// Leave string quotes as they are.
1168 /// string1 = "foo";
1169 /// string2 = 'bar';
1172 /// Always use single quotes.
1174 /// string1 = 'foo';
1175 /// string2 = 'bar';
1178 /// Always use double quotes.
1180 /// string1 = "foo";
1181 /// string2 = "bar";
1186 /// The JavaScriptQuoteStyle to use for JavaScript strings.
1187 JavaScriptQuoteStyle JavaScriptQuotes;
1189 /// Whether to wrap JavaScript import/export statements.
1193 /// VeryLongImportsAreAnnoying,
1194 /// VeryLongImportsAreAnnoying,
1195 /// VeryLongImportsAreAnnoying,
1196 /// } from 'some/module.js'
1199 /// import {VeryLongImportsAreAnnoying, VeryLongImportsAreAnnoying, VeryLongImportsAreAnnoying,} from "some/module.js"
1201 bool JavaScriptWrapImports;
1203 /// If true, the empty line at the start of blocks is kept.
1206 /// if (foo) { vs. if (foo) {
1211 bool KeepEmptyLinesAtTheStartOfBlocks;
1213 /// Supported languages.
1215 /// When stored in a configuration file, specifies the language, that the
1216 /// configuration targets. When passed to the ``reformat()`` function, enables
1217 /// syntax features specific to the language.
1221 /// Should be used for C, C++.
1223 /// Should be used for Java.
1225 /// Should be used for JavaScript.
1227 /// Should be used for Objective-C, Objective-C++.
1229 /// Should be used for Protocol Buffers
1230 /// (https://developers.google.com/protocol-buffers/).
1232 /// Should be used for TableGen code.
1234 /// Should be used for Protocol Buffer messages in text format
1235 /// (https://developers.google.com/protocol-buffers/).
1238 bool isCpp() const { return Language == LK_Cpp || Language == LK_ObjC; }
1240 /// Language, this format style is targeted at.
1241 LanguageKind Language;
1243 /// A regular expression matching macros that start a block.
1246 /// MacroBlockBegin: "^NS_MAP_BEGIN|\
1248 /// MacroBlockEnd: "^\
1250 /// NS_TABLE_.*_END$"
1258 /// NS_TABLE_FOO_END
1267 /// NS_TABLE_FOO_END
1269 std::string MacroBlockBegin;
1271 /// A regular expression matching macros that end a block.
1272 std::string MacroBlockEnd;
1274 /// The maximum number of consecutive empty lines to keep.
1276 /// MaxEmptyLinesToKeep: 1 vs. MaxEmptyLinesToKeep: 0
1277 /// int f() { int f() {
1278 /// int = 1; int i = 1;
1280 /// i = foo(); return i;
1285 unsigned MaxEmptyLinesToKeep;
1287 /// Different ways to indent namespace contents.
1288 enum NamespaceIndentationKind {
1289 /// Don't indent in namespaces.
1299 /// Indent only in inner namespaces (nested in other namespaces).
1309 /// Indent in all namespaces.
1321 /// The indentation used for namespaces.
1322 NamespaceIndentationKind NamespaceIndentation;
1324 /// Controls bin-packing Objective-C protocol conformance list
1325 /// items into as few lines as possible when they go over ``ColumnLimit``.
1327 /// If ``Auto`` (the default), delegates to the value in
1328 /// ``BinPackParameters``. If that is ``true``, bin-packs Objective-C
1329 /// protocol conformance list items into as few lines as possible
1330 /// whenever they go over ``ColumnLimit``.
1332 /// If ``Always``, always bin-packs Objective-C protocol conformance
1333 /// list items into as few lines as possible whenever they go over
1334 /// ``ColumnLimit``.
1336 /// If ``Never``, lays out Objective-C protocol conformance list items
1337 /// onto individual lines whenever they go over ``ColumnLimit``.
1340 /// Always (or Auto, if BinPackParameters=true):
1341 /// @interface ccccccccccccc () <
1342 /// ccccccccccccc, ccccccccccccc,
1343 /// ccccccccccccc, ccccccccccccc> {
1346 /// Never (or Auto, if BinPackParameters=false):
1347 /// @interface ddddddddddddd () <
1351 /// ddddddddddddd> {
1354 BinPackStyle ObjCBinPackProtocolList;
1356 /// The number of characters to use for indentation of ObjC blocks.
1358 /// ObjCBlockIndentWidth: 4
1360 /// [operation setCompletionBlock:^{
1361 /// [self onOperationDone];
1364 unsigned ObjCBlockIndentWidth;
1366 /// Add a space after ``@property`` in Objective-C, i.e. use
1367 /// ``@property (readonly)`` instead of ``@property(readonly)``.
1368 bool ObjCSpaceAfterProperty;
1370 /// Add a space in front of an Objective-C protocol list, i.e. use
1371 /// ``Foo <Protocol>`` instead of ``Foo<Protocol>``.
1372 bool ObjCSpaceBeforeProtocolList;
1374 /// The penalty for breaking around an assignment operator.
1375 unsigned PenaltyBreakAssignment;
1377 /// The penalty for breaking a function call after ``call(``.
1378 unsigned PenaltyBreakBeforeFirstCallParameter;
1380 /// The penalty for each line break introduced inside a comment.
1381 unsigned PenaltyBreakComment;
1383 /// The penalty for breaking before the first ``<<``.
1384 unsigned PenaltyBreakFirstLessLess;
1386 /// The penalty for each line break introduced inside a string literal.
1387 unsigned PenaltyBreakString;
1389 /// The penalty for breaking after template declaration.
1390 unsigned PenaltyBreakTemplateDeclaration;
1392 /// The penalty for each character outside of the column limit.
1393 unsigned PenaltyExcessCharacter;
1395 /// Penalty for putting the return type of a function onto its own
1397 unsigned PenaltyReturnTypeOnItsOwnLine;
1399 /// The ``&`` and ``*`` alignment style.
1400 enum PointerAlignmentStyle {
1401 /// Align pointer to the left.
1406 /// Align pointer to the right.
1411 /// Align pointer in the middle.
1418 /// Pointer and reference alignment style.
1419 PointerAlignmentStyle PointerAlignment;
1421 /// See documentation of ``RawStringFormats``.
1422 struct RawStringFormat {
1423 /// The language of this raw string.
1424 LanguageKind Language;
1425 /// A list of raw string delimiters that match this language.
1426 std::vector<std::string> Delimiters;
1427 /// A list of enclosing function names that match this language.
1428 std::vector<std::string> EnclosingFunctions;
1429 /// The canonical delimiter for this language.
1430 std::string CanonicalDelimiter;
1431 /// The style name on which this raw string format is based on.
1432 /// If not specified, the raw string format is based on the style that this
1433 /// format is based on.
1434 std::string BasedOnStyle;
1435 bool operator==(const RawStringFormat &Other) const {
1436 return Language == Other.Language && Delimiters == Other.Delimiters &&
1437 EnclosingFunctions == Other.EnclosingFunctions &&
1438 CanonicalDelimiter == Other.CanonicalDelimiter &&
1439 BasedOnStyle == Other.BasedOnStyle;
1443 /// Defines hints for detecting supported languages code blocks in raw
1446 /// A raw string with a matching delimiter or a matching enclosing function
1447 /// name will be reformatted assuming the specified language based on the
1448 /// style for that language defined in the .clang-format file. If no style has
1449 /// been defined in the .clang-format file for the specific language, a
1450 /// predefined style given by 'BasedOnStyle' is used. If 'BasedOnStyle' is not
1451 /// found, the formatting is based on llvm style. A matching delimiter takes
1452 /// precedence over a matching enclosing function name for determining the
1453 /// language of the raw string contents.
1455 /// If a canonical delimiter is specified, occurrences of other delimiters for
1456 /// the same language will be updated to the canonical if possible.
1458 /// There should be at most one specification per language and each delimiter
1459 /// and enclosing function should not occur in multiple specifications.
1461 /// To configure this in the .clang-format file, use:
1463 /// RawStringFormats:
1464 /// - Language: TextProto
1468 /// EnclosingFunctions:
1469 /// - 'PARSE_TEXT_PROTO'
1470 /// BasedOnStyle: google
1475 /// BasedOnStyle: llvm
1476 /// CanonicalDelimiter: 'cc'
1478 std::vector<RawStringFormat> RawStringFormats;
1480 /// If ``true``, clang-format will attempt to re-flow comments.
1483 /// // veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongComment with plenty of information
1484 /// /* second veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongComment with plenty of information */
1487 /// // veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongComment with plenty of
1489 /// /* second veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongComment with plenty of
1490 /// * information */
1492 bool ReflowComments;
1494 /// If ``true``, clang-format will sort ``#includes``.
1497 /// #include "b.h" vs. #include "a.h"
1498 /// #include "a.h" #include "b.h"
1502 /// If ``true``, clang-format will sort using declarations.
1504 /// The order of using declarations is defined as follows:
1505 /// Split the strings by "::" and discard any initial empty strings. The last
1506 /// element of each list is a non-namespace name; all others are namespace
1507 /// names. Sort the lists of names lexicographically, where the sort order of
1508 /// individual names is that all non-namespace names come before all namespace
1509 /// names, and within those groups, names are in case-insensitive
1510 /// lexicographic order.
1513 /// using std::cout; vs. using std::cin;
1514 /// using std::cin; using std::cout;
1516 bool SortUsingDeclarations;
1518 /// If ``true``, a space is inserted after C style casts.
1521 /// (int) i; vs. (int)i;
1523 bool SpaceAfterCStyleCast;
1525 /// If \c true, a space will be inserted after the 'template' keyword.
1528 /// template <int> void foo(); vs. template<int> void foo();
1530 bool SpaceAfterTemplateKeyword;
1532 /// If ``false``, spaces will be removed before assignment operators.
1535 /// int a = 5; vs. int a=5;
1538 bool SpaceBeforeAssignmentOperators;
1540 /// If ``true``, a space will be inserted before a C++11 braced list
1541 /// used to initialize an object (after the preceding identifier or type).
1544 /// Foo foo { bar }; vs. Foo foo{ bar };
1546 /// vector<int> { 1, 2, 3 }; vector<int>{ 1, 2, 3 };
1547 /// new int[3] { 1, 2, 3 }; new int[3]{ 1, 2, 3 };
1549 bool SpaceBeforeCpp11BracedList;
1551 /// If ``false``, spaces will be removed before constructor initializer
1555 /// Foo::Foo() : a(a) {} Foo::Foo(): a(a) {}
1557 bool SpaceBeforeCtorInitializerColon;
1559 /// If ``false``, spaces will be removed before inheritance colon.
1562 /// class Foo : Bar {} vs. class Foo: Bar {}
1564 bool SpaceBeforeInheritanceColon;
1566 /// Different ways to put a space before opening parentheses.
1567 enum SpaceBeforeParensOptions {
1568 /// Never put a space before opening parentheses.
1577 /// Put a space before opening parentheses only after control statement
1578 /// keywords (``for/if/while...``).
1586 SBPO_ControlStatements,
1587 /// Always put a space before opening parentheses, except when it's
1588 /// prohibited by the syntax rules (in function-like macro definitions) or
1589 /// when determined by other style rules (after unary operators, opening
1590 /// parentheses, etc.)
1601 /// Defines in which cases to put a space before opening parentheses.
1602 SpaceBeforeParensOptions SpaceBeforeParens;
1604 /// If ``false``, spaces will be removed before range-based for loop
1608 /// for (auto v : values) {} vs. for(auto v: values) {}
1610 bool SpaceBeforeRangeBasedForLoopColon;
1612 /// If ``true``, spaces may be inserted into ``()``.
1615 /// void f( ) { vs. void f() {
1616 /// int x[] = {foo( ), bar( )}; int x[] = {foo(), bar()};
1617 /// if (true) { if (true) {
1622 bool SpaceInEmptyParentheses;
1624 /// The number of spaces before trailing line comments
1625 /// (``//`` - comments).
1627 /// This does not affect trailing block comments (``/*`` - comments) as
1628 /// those commonly have different usage patterns and a number of special
1631 /// SpacesBeforeTrailingComments: 3
1633 /// if (true) { // foo1
1638 unsigned SpacesBeforeTrailingComments;
1640 /// If ``true``, spaces will be inserted after ``<`` and before ``>``
1641 /// in template argument lists.
1644 /// static_cast< int >(arg); vs. static_cast<int>(arg);
1645 /// std::function< void(int) > fct; std::function<void(int)> fct;
1647 bool SpacesInAngles;
1649 /// If ``true``, spaces are inserted inside container literals (e.g.
1650 /// ObjC and Javascript array and dict literals).
1653 /// var arr = [ 1, 2, 3 ]; vs. var arr = [1, 2, 3];
1654 /// f({a : 1, b : 2, c : 3}); f({a: 1, b: 2, c: 3});
1656 bool SpacesInContainerLiterals;
1658 /// If ``true``, spaces may be inserted into C style casts.
1661 /// x = ( int32 )y vs. x = (int32)y
1663 bool SpacesInCStyleCastParentheses;
1665 /// If ``true``, spaces will be inserted after ``(`` and before ``)``.
1668 /// t f( Deleted & ) & = delete; vs. t f(Deleted &) & = delete;
1670 bool SpacesInParentheses;
1672 /// If ``true``, spaces will be inserted after ``[`` and before ``]``.
1673 /// Lambdas or unspecified size array declarations will not be affected.
1676 /// int a[ 5 ]; vs. int a[5];
1677 /// std::unique_ptr<int[]> foo() {} // Won't be affected
1679 bool SpacesInSquareBrackets;
1681 /// Supported language standards.
1682 enum LanguageStandard {
1683 /// Use C++03-compatible syntax.
1685 /// Use features of C++11, C++14 and C++1z (e.g. ``A<A<int>>`` instead of
1686 /// ``A<A<int> >``).
1688 /// Automatic detection based on the input.
1692 /// Format compatible with this standard, e.g. use ``A<A<int> >``
1693 /// instead of ``A<A<int>>`` for ``LS_Cpp03``.
1694 LanguageStandard Standard;
1696 /// The number of columns used for tab stops.
1699 /// Different ways to use tab in formatting.
1703 /// Use tabs only for indentation.
1705 /// Use tabs only for line continuation and indentation.
1706 UT_ForContinuationAndIndentation,
1707 /// Use tabs whenever we need to fill whitespace that spans at least from
1708 /// one tab stop to the next one.
1712 /// The way to use tab characters in the resulting file.
1715 bool operator==(const FormatStyle &R) const {
1716 return AccessModifierOffset == R.AccessModifierOffset &&
1717 AlignAfterOpenBracket == R.AlignAfterOpenBracket &&
1718 AlignConsecutiveAssignments == R.AlignConsecutiveAssignments &&
1719 AlignConsecutiveDeclarations == R.AlignConsecutiveDeclarations &&
1720 AlignEscapedNewlines == R.AlignEscapedNewlines &&
1721 AlignOperands == R.AlignOperands &&
1722 AlignTrailingComments == R.AlignTrailingComments &&
1723 AllowAllParametersOfDeclarationOnNextLine ==
1724 R.AllowAllParametersOfDeclarationOnNextLine &&
1725 AllowShortBlocksOnASingleLine == R.AllowShortBlocksOnASingleLine &&
1726 AllowShortCaseLabelsOnASingleLine ==
1727 R.AllowShortCaseLabelsOnASingleLine &&
1728 AllowShortFunctionsOnASingleLine ==
1729 R.AllowShortFunctionsOnASingleLine &&
1730 AllowShortIfStatementsOnASingleLine ==
1731 R.AllowShortIfStatementsOnASingleLine &&
1732 AllowShortLoopsOnASingleLine == R.AllowShortLoopsOnASingleLine &&
1733 AlwaysBreakAfterReturnType == R.AlwaysBreakAfterReturnType &&
1734 AlwaysBreakBeforeMultilineStrings ==
1735 R.AlwaysBreakBeforeMultilineStrings &&
1736 AlwaysBreakTemplateDeclarations ==
1737 R.AlwaysBreakTemplateDeclarations &&
1738 BinPackArguments == R.BinPackArguments &&
1739 BinPackParameters == R.BinPackParameters &&
1740 BreakBeforeBinaryOperators == R.BreakBeforeBinaryOperators &&
1741 BreakBeforeBraces == R.BreakBeforeBraces &&
1742 BreakBeforeTernaryOperators == R.BreakBeforeTernaryOperators &&
1743 BreakConstructorInitializers == R.BreakConstructorInitializers &&
1744 CompactNamespaces == R.CompactNamespaces &&
1745 BreakAfterJavaFieldAnnotations == R.BreakAfterJavaFieldAnnotations &&
1746 BreakStringLiterals == R.BreakStringLiterals &&
1747 ColumnLimit == R.ColumnLimit && CommentPragmas == R.CommentPragmas &&
1748 BreakInheritanceList == R.BreakInheritanceList &&
1749 ConstructorInitializerAllOnOneLineOrOnePerLine ==
1750 R.ConstructorInitializerAllOnOneLineOrOnePerLine &&
1751 ConstructorInitializerIndentWidth ==
1752 R.ConstructorInitializerIndentWidth &&
1753 ContinuationIndentWidth == R.ContinuationIndentWidth &&
1754 Cpp11BracedListStyle == R.Cpp11BracedListStyle &&
1755 DerivePointerAlignment == R.DerivePointerAlignment &&
1756 DisableFormat == R.DisableFormat &&
1757 ExperimentalAutoDetectBinPacking ==
1758 R.ExperimentalAutoDetectBinPacking &&
1759 FixNamespaceComments == R.FixNamespaceComments &&
1760 ForEachMacros == R.ForEachMacros &&
1761 IncludeStyle.IncludeBlocks == R.IncludeStyle.IncludeBlocks &&
1762 IncludeStyle.IncludeCategories == R.IncludeStyle.IncludeCategories &&
1763 IndentCaseLabels == R.IndentCaseLabels &&
1764 IndentPPDirectives == R.IndentPPDirectives &&
1765 IndentWidth == R.IndentWidth && Language == R.Language &&
1766 IndentWrappedFunctionNames == R.IndentWrappedFunctionNames &&
1767 JavaImportGroups == R.JavaImportGroups &&
1768 JavaScriptQuotes == R.JavaScriptQuotes &&
1769 JavaScriptWrapImports == R.JavaScriptWrapImports &&
1770 KeepEmptyLinesAtTheStartOfBlocks ==
1771 R.KeepEmptyLinesAtTheStartOfBlocks &&
1772 MacroBlockBegin == R.MacroBlockBegin &&
1773 MacroBlockEnd == R.MacroBlockEnd &&
1774 MaxEmptyLinesToKeep == R.MaxEmptyLinesToKeep &&
1775 NamespaceIndentation == R.NamespaceIndentation &&
1776 ObjCBinPackProtocolList == R.ObjCBinPackProtocolList &&
1777 ObjCBlockIndentWidth == R.ObjCBlockIndentWidth &&
1778 ObjCSpaceAfterProperty == R.ObjCSpaceAfterProperty &&
1779 ObjCSpaceBeforeProtocolList == R.ObjCSpaceBeforeProtocolList &&
1780 PenaltyBreakAssignment == R.PenaltyBreakAssignment &&
1781 PenaltyBreakBeforeFirstCallParameter ==
1782 R.PenaltyBreakBeforeFirstCallParameter &&
1783 PenaltyBreakComment == R.PenaltyBreakComment &&
1784 PenaltyBreakFirstLessLess == R.PenaltyBreakFirstLessLess &&
1785 PenaltyBreakString == R.PenaltyBreakString &&
1786 PenaltyExcessCharacter == R.PenaltyExcessCharacter &&
1787 PenaltyReturnTypeOnItsOwnLine == R.PenaltyReturnTypeOnItsOwnLine &&
1788 PenaltyBreakTemplateDeclaration ==
1789 R.PenaltyBreakTemplateDeclaration &&
1790 PointerAlignment == R.PointerAlignment &&
1791 RawStringFormats == R.RawStringFormats &&
1792 SpaceAfterCStyleCast == R.SpaceAfterCStyleCast &&
1793 SpaceAfterTemplateKeyword == R.SpaceAfterTemplateKeyword &&
1794 SpaceBeforeAssignmentOperators == R.SpaceBeforeAssignmentOperators &&
1795 SpaceBeforeCpp11BracedList == R.SpaceBeforeCpp11BracedList &&
1796 SpaceBeforeCtorInitializerColon ==
1797 R.SpaceBeforeCtorInitializerColon &&
1798 SpaceBeforeInheritanceColon == R.SpaceBeforeInheritanceColon &&
1799 SpaceBeforeParens == R.SpaceBeforeParens &&
1800 SpaceBeforeRangeBasedForLoopColon ==
1801 R.SpaceBeforeRangeBasedForLoopColon &&
1802 SpaceInEmptyParentheses == R.SpaceInEmptyParentheses &&
1803 SpacesBeforeTrailingComments == R.SpacesBeforeTrailingComments &&
1804 SpacesInAngles == R.SpacesInAngles &&
1805 SpacesInContainerLiterals == R.SpacesInContainerLiterals &&
1806 SpacesInCStyleCastParentheses == R.SpacesInCStyleCastParentheses &&
1807 SpacesInParentheses == R.SpacesInParentheses &&
1808 SpacesInSquareBrackets == R.SpacesInSquareBrackets &&
1809 Standard == R.Standard && TabWidth == R.TabWidth &&
1810 StatementMacros == R.StatementMacros && UseTab == R.UseTab;
1813 llvm::Optional<FormatStyle> GetLanguageStyle(LanguageKind Language) const;
1815 // Stores per-language styles. A FormatStyle instance inside has an empty
1816 // StyleSet. A FormatStyle instance returned by the Get method has its
1817 // StyleSet set to a copy of the originating StyleSet, effectively keeping the
1818 // internal representation of that StyleSet alive.
1820 // The memory management and ownership reminds of a birds nest: chicks
1821 // leaving the nest take photos of the nest with them.
1822 struct FormatStyleSet {
1823 typedef std::map<FormatStyle::LanguageKind, FormatStyle> MapType;
1825 llvm::Optional<FormatStyle> Get(FormatStyle::LanguageKind Language) const;
1827 // Adds \p Style to this FormatStyleSet. Style must not have an associated
1829 // Style.Language should be different than LK_None. If this FormatStyleSet
1830 // already contains an entry for Style.Language, that gets replaced with the
1832 void Add(FormatStyle Style);
1834 // Clears this FormatStyleSet.
1838 std::shared_ptr<MapType> Styles;
1841 static FormatStyleSet BuildStyleSetFromConfiguration(
1842 const FormatStyle &MainStyle,
1843 const std::vector<FormatStyle> &ConfigurationStyles);
1846 FormatStyleSet StyleSet;
1848 friend std::error_code parseConfiguration(StringRef Text, FormatStyle *Style);
1851 /// Returns a format style complying with the LLVM coding standards:
1852 /// http://llvm.org/docs/CodingStandards.html.
1853 FormatStyle getLLVMStyle();
1855 /// Returns a format style complying with one of Google's style guides:
1856 /// http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml.
1857 /// http://google-styleguide.googlecode.com/svn/trunk/javascriptguide.xml.
1858 /// https://developers.google.com/protocol-buffers/docs/style.
1859 FormatStyle getGoogleStyle(FormatStyle::LanguageKind Language);
1861 /// Returns a format style complying with Chromium's style guide:
1862 /// http://www.chromium.org/developers/coding-style.
1863 FormatStyle getChromiumStyle(FormatStyle::LanguageKind Language);
1865 /// Returns a format style complying with Mozilla's style guide:
1866 /// https://developer.mozilla.org/en-US/docs/Developer_Guide/Coding_Style.
1867 FormatStyle getMozillaStyle();
1869 /// Returns a format style complying with Webkit's style guide:
1870 /// http://www.webkit.org/coding/coding-style.html
1871 FormatStyle getWebKitStyle();
1873 /// Returns a format style complying with GNU Coding Standards:
1874 /// http://www.gnu.org/prep/standards/standards.html
1875 FormatStyle getGNUStyle();
1877 /// Returns style indicating formatting should be not applied at all.
1878 FormatStyle getNoStyle();
1880 /// Gets a predefined style for the specified language by name.
1882 /// Currently supported names: LLVM, Google, Chromium, Mozilla. Names are
1883 /// compared case-insensitively.
1885 /// Returns ``true`` if the Style has been set.
1886 bool getPredefinedStyle(StringRef Name, FormatStyle::LanguageKind Language,
1887 FormatStyle *Style);
1889 /// Parse configuration from YAML-formatted text.
1891 /// Style->Language is used to get the base style, if the ``BasedOnStyle``
1892 /// option is present.
1894 /// The FormatStyleSet of Style is reset.
1896 /// When ``BasedOnStyle`` is not present, options not present in the YAML
1897 /// document, are retained in \p Style.
1898 std::error_code parseConfiguration(StringRef Text, FormatStyle *Style);
1900 /// Gets configuration in a YAML string.
1901 std::string configurationAsText(const FormatStyle &Style);
1903 /// Returns the replacements necessary to sort all ``#include`` blocks
1904 /// that are affected by ``Ranges``.
1905 tooling::Replacements sortIncludes(const FormatStyle &Style, StringRef Code,
1906 ArrayRef<tooling::Range> Ranges,
1908 unsigned *Cursor = nullptr);
1910 /// Returns the replacements corresponding to applying and formatting
1911 /// \p Replaces on success; otheriwse, return an llvm::Error carrying
1912 /// llvm::StringError.
1913 llvm::Expected<tooling::Replacements>
1914 formatReplacements(StringRef Code, const tooling::Replacements &Replaces,
1915 const FormatStyle &Style);
1917 /// Returns the replacements corresponding to applying \p Replaces and
1918 /// cleaning up the code after that on success; otherwise, return an llvm::Error
1919 /// carrying llvm::StringError.
1920 /// This also supports inserting/deleting C++ #include directives:
1921 /// - If a replacement has offset UINT_MAX, length 0, and a replacement text
1922 /// that is an #include directive, this will insert the #include into the
1923 /// correct block in the \p Code.
1924 /// - If a replacement has offset UINT_MAX, length 1, and a replacement text
1925 /// that is the name of the header to be removed, the header will be removed
1926 /// from \p Code if it exists.
1927 /// The include manipulation is done via `tooling::HeaderInclude`, see its
1928 /// documentation for more details on how include insertion points are found and
1929 /// what edits are produced.
1930 llvm::Expected<tooling::Replacements>
1931 cleanupAroundReplacements(StringRef Code, const tooling::Replacements &Replaces,
1932 const FormatStyle &Style);
1934 /// Represents the status of a formatting attempt.
1935 struct FormattingAttemptStatus {
1936 /// A value of ``false`` means that any of the affected ranges were not
1937 /// formatted due to a non-recoverable syntax error.
1938 bool FormatComplete = true;
1940 /// If ``FormatComplete`` is false, ``Line`` records a one-based
1941 /// original line number at which a syntax error might have occurred. This is
1942 /// based on a best-effort analysis and could be imprecise.
1946 /// Reformats the given \p Ranges in \p Code.
1948 /// Each range is extended on either end to its next bigger logic unit, i.e.
1949 /// everything that might influence its formatting or might be influenced by its
1952 /// Returns the ``Replacements`` necessary to make all \p Ranges comply with
1955 /// If ``Status`` is non-null, its value will be populated with the status of
1956 /// this formatting attempt. See \c FormattingAttemptStatus.
1957 tooling::Replacements reformat(const FormatStyle &Style, StringRef Code,
1958 ArrayRef<tooling::Range> Ranges,
1959 StringRef FileName = "<stdin>",
1960 FormattingAttemptStatus *Status = nullptr);
1962 /// Same as above, except if ``IncompleteFormat`` is non-null, its value
1963 /// will be set to true if any of the affected ranges were not formatted due to
1964 /// a non-recoverable syntax error.
1965 tooling::Replacements reformat(const FormatStyle &Style, StringRef Code,
1966 ArrayRef<tooling::Range> Ranges,
1968 bool *IncompleteFormat);
1970 /// Clean up any erroneous/redundant code in the given \p Ranges in \p
1973 /// Returns the ``Replacements`` that clean up all \p Ranges in \p Code.
1974 tooling::Replacements cleanup(const FormatStyle &Style, StringRef Code,
1975 ArrayRef<tooling::Range> Ranges,
1976 StringRef FileName = "<stdin>");
1978 /// Fix namespace end comments in the given \p Ranges in \p Code.
1980 /// Returns the ``Replacements`` that fix the namespace comments in all
1981 /// \p Ranges in \p Code.
1982 tooling::Replacements fixNamespaceEndComments(const FormatStyle &Style,
1984 ArrayRef<tooling::Range> Ranges,
1985 StringRef FileName = "<stdin>");
1987 /// Sort consecutive using declarations in the given \p Ranges in
1990 /// Returns the ``Replacements`` that sort the using declarations in all
1991 /// \p Ranges in \p Code.
1992 tooling::Replacements sortUsingDeclarations(const FormatStyle &Style,
1994 ArrayRef<tooling::Range> Ranges,
1995 StringRef FileName = "<stdin>");
1997 /// Returns the ``LangOpts`` that the formatter expects you to set.
1999 /// \param Style determines specific settings for lexing mode.
2000 LangOptions getFormattingLangOpts(const FormatStyle &Style = getLLVMStyle());
2002 /// Description to be used for help text for a ``llvm::cl`` option for
2003 /// specifying format style. The description is closely related to the operation
2004 /// of ``getStyle()``.
2005 extern const char *StyleOptionHelpDescription;
2007 /// The suggested format style to use by default. This allows tools using
2008 /// `getStyle` to have a consistent default style.
2009 /// Different builds can modify the value to the preferred styles.
2010 extern const char *DefaultFormatStyle;
2012 /// The suggested predefined style to use as the fallback style in `getStyle`.
2013 /// Different builds can modify the value to the preferred styles.
2014 extern const char *DefaultFallbackStyle;
2016 /// Construct a FormatStyle based on ``StyleName``.
2018 /// ``StyleName`` can take several forms:
2019 /// * "{<key>: <value>, ...}" - Set specic style parameters.
2020 /// * "<style name>" - One of the style names supported by
2021 /// getPredefinedStyle().
2022 /// * "file" - Load style configuration from a file called ``.clang-format``
2023 /// located in one of the parent directories of ``FileName`` or the current
2024 /// directory if ``FileName`` is empty.
2026 /// \param[in] StyleName Style name to interpret according to the description
2028 /// \param[in] FileName Path to start search for .clang-format if ``StyleName``
2030 /// \param[in] FallbackStyle The name of a predefined style used to fallback to
2031 /// in case \p StyleName is "file" and no file can be found.
2032 /// \param[in] Code The actual code to be formatted. Used to determine the
2033 /// language if the filename isn't sufficient.
2034 /// \param[in] FS The underlying file system, in which the file resides. By
2035 /// default, the file system is the real file system.
2037 /// \returns FormatStyle as specified by ``StyleName``. If ``StyleName`` is
2038 /// "file" and no file is found, returns ``FallbackStyle``. If no style could be
2039 /// determined, returns an Error.
2040 llvm::Expected<FormatStyle> getStyle(StringRef StyleName, StringRef FileName,
2041 StringRef FallbackStyle,
2042 StringRef Code = "",
2043 llvm::vfs::FileSystem *FS = nullptr);
2045 // Guesses the language from the ``FileName`` and ``Code`` to be formatted.
2046 // Defaults to FormatStyle::LK_Cpp.
2047 FormatStyle::LanguageKind guessLanguage(StringRef FileName, StringRef Code);
2049 // Returns a string representation of ``Language``.
2050 inline StringRef getLanguageName(FormatStyle::LanguageKind Language) {
2052 case FormatStyle::LK_Cpp:
2054 case FormatStyle::LK_ObjC:
2055 return "Objective-C";
2056 case FormatStyle::LK_Java:
2058 case FormatStyle::LK_JavaScript:
2059 return "JavaScript";
2060 case FormatStyle::LK_Proto:
2062 case FormatStyle::LK_TextProto:
2069 } // end namespace format
2070 } // end namespace clang
2074 struct is_error_code_enum<clang::format::ParseError> : std::true_type {};
2077 #endif // LLVM_CLANG_FORMAT_FORMAT_H