1 //===--- Format.h - Format C++ code -----------------------------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 ///
9 /// \file
10 /// Various functions to configurably format source code.
11 ///
12 //===----------------------------------------------------------------------===//
13
14 #ifndef LLVM_CLANG_FORMAT_FORMAT_H
15 #define LLVM_CLANG_FORMAT_FORMAT_H
16
17 #include "clang/Basic/LangOptions.h"
18 #include "clang/Tooling/Core/Replacement.h"
19 #include "clang/Tooling/Inclusions/IncludeStyle.h"
20 #include "llvm/ADT/ArrayRef.h"
21 #include "llvm/Support/Regex.h"
22 #include <system_error>
23
24 namespace llvm {
25 namespace vfs {
26 class FileSystem;
27 }
28 } // namespace llvm
29
30 namespace clang {
31
32 class Lexer;
33 class SourceManager;
34 class DiagnosticConsumer;
35
36 namespace format {
37
38 enum class ParseError { Success = 0, Error, Unsuitable };
39 class ParseErrorCategory final : public std::error_category {
40 public:
41 const char *name() const noexcept override;
42 std::string message(int EV) const override;
43 };
44 const std::error_category &getParseCategory();
45 std::error_code make_error_code(ParseError e);
46
47 /// The ``FormatStyle`` is used to configure the formatting to follow
48 /// specific guidelines.
49 struct FormatStyle {
50 /// The extra indent or outdent of access modifiers, e.g. ``public:``.
51 int AccessModifierOffset;
52
53 /// Different styles for aligning after open brackets.
54 enum BracketAlignmentStyle {
55 /// Align parameters on the open bracket, e.g.:
56 /// \code
57 /// someLongFunction(argument1,
58 /// argument2);
59 /// \endcode
60 BAS_Align,
61 /// Don't align, instead use ``ContinuationIndentWidth``, e.g.:
62 /// \code
63 /// someLongFunction(argument1,
64 /// argument2);
65 /// \endcode
66 BAS_DontAlign,
67 /// Always break after an open bracket, if the parameters don't fit
68 /// on a single line, e.g.:
69 /// \code
70 /// someLongFunction(
71 /// argument1, argument2);
72 /// \endcode
73 BAS_AlwaysBreak,
74 };
75
76 /// If ``true``, horizontally aligns arguments after an open bracket.
77 ///
78 /// This applies to round brackets (parentheses), angle brackets and square
79 /// brackets.
80 BracketAlignmentStyle AlignAfterOpenBracket;
81
82 /// \brief If ``true``, aligns consecutive C/C++ preprocessor macros.
83 ///
84 /// This will align C/C++ preprocessor macros of consecutive lines.
85 /// Will result in formattings like
86 /// \code
87 /// #define SHORT_NAME 42
88 /// #define LONGER_NAME 0x007f
89 /// #define EVEN_LONGER_NAME (2)
90 /// #define foo(x) (x * x)
91 /// #define bar(y, z) (y + z)
92 /// \endcode
93 bool AlignConsecutiveMacros;
94
95 /// If ``true``, aligns consecutive assignments.
96 ///
97 /// This will align the assignment operators of consecutive lines. This
98 /// will result in formattings like
99 /// \code
100 /// int aaaa = 12;
101 /// int b = 23;
102 /// int ccc = 23;
103 /// \endcode
104 bool AlignConsecutiveAssignments;
105
106 /// If ``true``, aligns consecutive declarations.
107 ///
108 /// This will align the declaration names of consecutive lines. This
109 /// will result in formattings like
110 /// \code
111 /// int aaaa = 12;
112 /// float b = 23;
113 /// std::string ccc = 23;
114 /// \endcode
115 bool AlignConsecutiveDeclarations;
116
117 /// Different styles for aligning escaped newlines.
118 enum EscapedNewlineAlignmentStyle {
119 /// Don't align escaped newlines.
120 /// \code
121 /// #define A \
122 /// int aaaa; \
123 /// int b; \
124 /// int dddddddddd;
125 /// \endcode
126 ENAS_DontAlign,
127 /// Align escaped newlines as far left as possible.
128 /// \code
129 /// true:
130 /// #define A \
131 /// int aaaa; \
132 /// int b; \
133 /// int dddddddddd;
134 ///
135 /// false:
136 /// \endcode
137 ENAS_Left,
138 /// Align escaped newlines in the right-most column.
139 /// \code
140 /// #define A \
141 /// int aaaa; \
142 /// int b; \
143 /// int dddddddddd;
144 /// \endcode
145 ENAS_Right,
146 };
147
148 /// Options for aligning backslashes in escaped newlines.
149 EscapedNewlineAlignmentStyle AlignEscapedNewlines;
150
151 /// If ``true``, horizontally align operands of binary and ternary
152 /// expressions.
153 ///
154 /// Specifically, this aligns operands of a single expression that needs to be
155 /// split over multiple lines, e.g.:
156 /// \code
157 /// int aaa = bbbbbbbbbbbbbbb +
158 /// ccccccccccccccc;
159 /// \endcode
160 bool AlignOperands;
161
162 /// If ``true``, aligns trailing comments.
163 /// \code
164 /// true: false:
165 /// int a; // My comment a vs. int a; // My comment a
166 /// int b = 2; // comment b int b = 2; // comment about b
167 /// \endcode
168 bool AlignTrailingComments;
169
170 /// \brief If a function call or braced initializer list doesn't fit on a
171 /// line, allow putting all arguments onto the next line, even if
172 /// ``BinPackArguments`` is ``false``.
173 /// \code
174 /// true:
175 /// callFunction(
176 /// a, b, c, d);
177 ///
178 /// false:
179 /// callFunction(a,
180 /// b,
181 /// c,
182 /// d);
183 /// \endcode
184 bool AllowAllArgumentsOnNextLine;
185
186 /// \brief If a constructor definition with a member initializer list doesn't
187 /// fit on a single line, allow putting all member initializers onto the next
188 /// line, if ```ConstructorInitializerAllOnOneLineOrOnePerLine``` is true.
189 /// Note that this parameter has no effect if
190 /// ```ConstructorInitializerAllOnOneLineOrOnePerLine``` is false.
191 /// \code
192 /// true:
193 /// MyClass::MyClass() :
194 /// member0(0), member1(2) {}
195 ///
196 /// false:
197 /// MyClass::MyClass() :
198 /// member0(0),
199 /// member1(2) {}
200 bool AllowAllConstructorInitializersOnNextLine;
201
202 /// If the function declaration doesn't fit on a line,
203 /// allow putting all parameters of a function declaration onto
204 /// the next line even if ``BinPackParameters`` is ``false``.
205 /// \code
206 /// true:
207 /// void myFunction(
208 /// int a, int b, int c, int d, int e);
209 ///
210 /// false:
211 /// void myFunction(int a,
212 /// int b,
213 /// int c,
214 /// int d,
215 /// int e);
216 /// \endcode
217 bool AllowAllParametersOfDeclarationOnNextLine;
218
219 /// Different styles for merging short blocks containing at most one
220 /// statement.
221 enum ShortBlockStyle {
222 /// Never merge blocks into a single line.
223 /// \code
224 /// while (true) {
225 /// }
226 /// while (true) {
227 /// continue;
228 /// }
229 /// \endcode
230 SBS_Never,
231 /// Only merge empty blocks.
232 /// \code
233 /// while (true) {}
234 /// while (true) {
235 /// continue;
236 /// }
237 /// \endcode
238 SBS_Empty,
239 /// Always merge short blocks into a single line.
240 /// \code
241 /// while (true) {}
242 /// while (true) { continue; }
243 /// \endcode
244 SBS_Always,
245 };
246
247 /// Dependent on the value, ``while (true) { continue; }`` can be put on a
248 /// single line.
249 ShortBlockStyle AllowShortBlocksOnASingleLine;
250
251 /// If ``true``, short case labels will be contracted to a single line.
252 /// \code
253 /// true: false:
254 /// switch (a) { vs. switch (a) {
255 /// case 1: x = 1; break; case 1:
256 /// case 2: return; x = 1;
257 /// } break;
258 /// case 2:
259 /// return;
260 /// }
261 /// \endcode
262 bool AllowShortCaseLabelsOnASingleLine;
263
264 /// Different styles for merging short functions containing at most one
265 /// statement.
266 enum ShortFunctionStyle {
267 /// Never merge functions into a single line.
268 SFS_None,
269 /// Only merge functions defined inside a class. Same as "inline",
270 /// except it does not implies "empty": i.e. top level empty functions
271 /// are not merged either.
272 /// \code
273 /// class Foo {
274 /// void f() { foo(); }
275 /// };
276 /// void f() {
277 /// foo();
278 /// }
279 /// void f() {
280 /// }
281 /// \endcode
282 SFS_InlineOnly,
283 /// Only merge empty functions.
284 /// \code
285 /// void f() {}
286 /// void f2() {
287 /// bar2();
288 /// }
289 /// \endcode
290 SFS_Empty,
291 /// Only merge functions defined inside a class. Implies "empty".
292 /// \code
293 /// class Foo {
294 /// void f() { foo(); }
295 /// };
296 /// void f() {
297 /// foo();
298 /// }
299 /// void f() {}
300 /// \endcode
301 SFS_Inline,
302 /// Merge all functions fitting on a single line.
303 /// \code
304 /// class Foo {
305 /// void f() { foo(); }
306 /// };
307 /// void f() { bar(); }
308 /// \endcode
309 SFS_All,
310 };
311
312 /// Dependent on the value, ``int f() { return 0; }`` can be put on a
313 /// single line.
314 ShortFunctionStyle AllowShortFunctionsOnASingleLine;
315
316 /// Different styles for handling short if lines
317 enum ShortIfStyle {
318 /// Never put short ifs on the same line.
319 /// \code
320 /// if (a)
321 /// return ;
322 /// else {
323 /// return;
324 /// }
325 /// \endcode
326 SIS_Never,
327 /// Without else put short ifs on the same line only if
328 /// the else is not a compound statement.
329 /// \code
330 /// if (a) return;
331 /// else
332 /// return;
333 /// \endcode
334 SIS_WithoutElse,
335 /// Always put short ifs on the same line if
336 /// the else is not a compound statement or not.
337 /// \code
338 /// if (a) return;
339 /// else {
340 /// return;
341 /// }
342 /// \endcode
343 SIS_Always,
344 };
345
346 /// If ``true``, ``if (a) return;`` can be put on a single line.
347 ShortIfStyle AllowShortIfStatementsOnASingleLine;
348
349 /// Different styles for merging short lambdas containing at most one
350 /// statement.
351 enum ShortLambdaStyle {
352 /// Never merge lambdas into a single line.
353 SLS_None,
354 /// Only merge empty lambdas.
355 /// \code
356 /// auto lambda = [](int a) {}
357 /// auto lambda2 = [](int a) {
358 /// return a;
359 /// };
360 /// \endcode
361 SLS_Empty,
362 /// Merge lambda into a single line if argument of a function.
363 /// \code
364 /// auto lambda = [](int a) {
365 /// return a;
366 /// };
367 /// sort(a.begin(), a.end(), ()[] { return x < y; })
368 /// \endcode
369 SLS_Inline,
370 /// Merge all lambdas fitting on a single line.
371 /// \code
372 /// auto lambda = [](int a) {}
373 /// auto lambda2 = [](int a) { return a; };
374 /// \endcode
375 SLS_All,
376 };
377
378 /// Dependent on the value, ``auto lambda []() { return 0; }`` can be put on a
379 /// single line.
380 ShortLambdaStyle AllowShortLambdasOnASingleLine;
381
382 /// If ``true``, ``while (true) continue;`` can be put on a single
383 /// line.
384 bool AllowShortLoopsOnASingleLine;
385
386 /// Different ways to break after the function definition return type.
387 /// This option is **deprecated** and is retained for backwards compatibility.
388 enum DefinitionReturnTypeBreakingStyle {
389 /// Break after return type automatically.
390 /// ``PenaltyReturnTypeOnItsOwnLine`` is taken into account.
391 DRTBS_None,
392 /// Always break after the return type.
393 DRTBS_All,
394 /// Always break after the return types of top-level functions.
395 DRTBS_TopLevel,
396 };
397
398 /// Different ways to break after the function definition or
399 /// declaration return type.
400 enum ReturnTypeBreakingStyle {
401 /// Break after return type automatically.
402 /// ``PenaltyReturnTypeOnItsOwnLine`` is taken into account.
403 /// \code
404 /// class A {
405 /// int f() { return 0; };
406 /// };
407 /// int f();
408 /// int f() { return 1; }
409 /// \endcode
410 RTBS_None,
411 /// Always break after the return type.
412 /// \code
413 /// class A {
414 /// int
415 /// f() {
416 /// return 0;
417 /// };
418 /// };
419 /// int
420 /// f();
421 /// int
422 /// f() {
423 /// return 1;
424 /// }
425 /// \endcode
426 RTBS_All,
427 /// Always break after the return types of top-level functions.
428 /// \code
429 /// class A {
430 /// int f() { return 0; };
431 /// };
432 /// int
433 /// f();
434 /// int
435 /// f() {
436 /// return 1;
437 /// }
438 /// \endcode
439 RTBS_TopLevel,
440 /// Always break after the return type of function definitions.
441 /// \code
442 /// class A {
443 /// int
444 /// f() {
445 /// return 0;
446 /// };
447 /// };
448 /// int f();
449 /// int
450 /// f() {
451 /// return 1;
452 /// }
453 /// \endcode
454 RTBS_AllDefinitions,
455 /// Always break after the return type of top-level definitions.
456 /// \code
457 /// class A {
458 /// int f() { return 0; };
459 /// };
460 /// int f();
461 /// int
462 /// f() {
463 /// return 1;
464 /// }
465 /// \endcode
466 RTBS_TopLevelDefinitions,
467 };
468
469 /// The function definition return type breaking style to use. This
470 /// option is **deprecated** and is retained for backwards compatibility.
471 DefinitionReturnTypeBreakingStyle AlwaysBreakAfterDefinitionReturnType;
472
473 /// The function declaration return type breaking style to use.
474 ReturnTypeBreakingStyle AlwaysBreakAfterReturnType;
475
476 /// If ``true``, always break before multiline string literals.
477 ///
478 /// This flag is mean to make cases where there are multiple multiline strings
479 /// in a file look more consistent. Thus, it will only take effect if wrapping
480 /// the string at that point leads to it being indented
481 /// ``ContinuationIndentWidth`` spaces from the start of the line.
482 /// \code
483 /// true: false:
484 /// aaaa = vs. aaaa = "bbbb"
485 /// "bbbb" "cccc";
486 /// "cccc";
487 /// \endcode
488 bool AlwaysBreakBeforeMultilineStrings;
489
490 /// Different ways to break after the template declaration.
491 enum BreakTemplateDeclarationsStyle {
492 /// Do not force break before declaration.
493 /// ``PenaltyBreakTemplateDeclaration`` is taken into account.
494 /// \code
495 /// template <typename T> T foo() {
496 /// }
497 /// template <typename T> T foo(int aaaaaaaaaaaaaaaaaaaaa,
498 /// int bbbbbbbbbbbbbbbbbbbbb) {
499 /// }
500 /// \endcode
501 BTDS_No,
502 /// Force break after template declaration only when the following
503 /// declaration spans multiple lines.
504 /// \code
505 /// template <typename T> T foo() {
506 /// }
507 /// template <typename T>
508 /// T foo(int aaaaaaaaaaaaaaaaaaaaa,
509 /// int bbbbbbbbbbbbbbbbbbbbb) {
510 /// }
511 /// \endcode
512 BTDS_MultiLine,
513 /// Always break after template declaration.
514 /// \code
515 /// template <typename T>
516 /// T foo() {
517 /// }
518 /// template <typename T>
519 /// T foo(int aaaaaaaaaaaaaaaaaaaaa,
520 /// int bbbbbbbbbbbbbbbbbbbbb) {
521 /// }
522 /// \endcode
523 BTDS_Yes
524 };
525
526 /// The template declaration breaking style to use.
527 BreakTemplateDeclarationsStyle AlwaysBreakTemplateDeclarations;
528
529 /// If ``false``, a function call's arguments will either be all on the
530 /// same line or will have one line each.
531 /// \code
532 /// true:
533 /// void f() {
534 /// f(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaa,
535 /// aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);
536 /// }
537 ///
538 /// false:
539 /// void f() {
540 /// f(aaaaaaaaaaaaaaaaaaaa,
541 /// aaaaaaaaaaaaaaaaaaaa,
542 /// aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);
543 /// }
544 /// \endcode
545 bool BinPackArguments;
546
547 /// If ``false``, a function declaration's or function definition's
548 /// parameters will either all be on the same line or will have one line each.
549 /// \code
550 /// true:
551 /// void f(int aaaaaaaaaaaaaaaaaaaa, int aaaaaaaaaaaaaaaaaaaa,
552 /// int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}
553 ///
554 /// false:
555 /// void f(int aaaaaaaaaaaaaaaaaaaa,
556 /// int aaaaaaaaaaaaaaaaaaaa,
557 /// int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}
558 /// \endcode
559 bool BinPackParameters;
560
561 /// The style of wrapping parameters on the same line (bin-packed) or
562 /// on one line each.
563 enum BinPackStyle {
564 /// Automatically determine parameter bin-packing behavior.
565 BPS_Auto,
566 /// Always bin-pack parameters.
567 BPS_Always,
568 /// Never bin-pack parameters.
569 BPS_Never,
570 };
571
572 /// The style of breaking before or after binary operators.
573 enum BinaryOperatorStyle {
574 /// Break after operators.
575 /// \code
576 /// LooooooooooongType loooooooooooooooooooooongVariable =
577 /// someLooooooooooooooooongFunction();
578 ///
579 /// bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +
580 /// aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==
581 /// aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa &&
582 /// aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >
583 /// ccccccccccccccccccccccccccccccccccccccccc;
584 /// \endcode
585 BOS_None,
586 /// Break before operators that aren't assignments.
587 /// \code
588 /// LooooooooooongType loooooooooooooooooooooongVariable =
589 /// someLooooooooooooooooongFunction();
590 ///
591 /// bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
592 /// + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
593 /// == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
594 /// && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
595 /// > ccccccccccccccccccccccccccccccccccccccccc;
596 /// \endcode
597 BOS_NonAssignment,
598 /// Break before operators.
599 /// \code
600 /// LooooooooooongType loooooooooooooooooooooongVariable
601 /// = someLooooooooooooooooongFunction();
602 ///
603 /// bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
604 /// + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
605 /// == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
606 /// && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
607 /// > ccccccccccccccccccccccccccccccccccccccccc;
608 /// \endcode
609 BOS_All,
610 };
611
612 /// The way to wrap binary operators.
613 BinaryOperatorStyle BreakBeforeBinaryOperators;
614
615 /// Different ways to attach braces to their surrounding context.
616 enum BraceBreakingStyle {
617 /// Always attach braces to surrounding context.
618 /// \code
619 /// try {
620 /// foo();
621 /// } catch () {
622 /// }
623 /// void foo() { bar(); }
624 /// class foo {};
625 /// if (foo()) {
626 /// } else {
627 /// }
628 /// enum X : int { A, B };
629 /// \endcode
630 BS_Attach,
631 /// Like ``Attach``, but break before braces on function, namespace and
632 /// class definitions.
633 /// \code
634 /// try {
635 /// foo();
636 /// } catch () {
637 /// }
638 /// void foo() { bar(); }
639 /// class foo
640 /// {
641 /// };
642 /// if (foo()) {
643 /// } else {
644 /// }
645 /// enum X : int { A, B };
646 /// \endcode
647 BS_Linux,
648 /// Like ``Attach``, but break before braces on enum, function, and record
649 /// definitions.
650 /// \code
651 /// try {
652 /// foo();
653 /// } catch () {
654 /// }
655 /// void foo() { bar(); }
656 /// class foo
657 /// {
658 /// };
659 /// if (foo()) {
660 /// } else {
661 /// }
662 /// enum X : int { A, B };
663 /// \endcode
664 BS_Mozilla,
665 /// Like ``Attach``, but break before function definitions, ``catch``, and
666 /// ``else``.
667 /// \code
668 /// try {
669 /// foo();
670 /// }
671 /// catch () {
672 /// }
673 /// void foo() { bar(); }
674 /// class foo {
675 /// };
676 /// if (foo()) {
677 /// }
678 /// else {
679 /// }
680 /// enum X : int { A, B };
681 /// \endcode
682 BS_Stroustrup,
683 /// Always break before braces.
684 /// \code
685 /// try
686 /// {
687 /// foo();
688 /// }
689 /// catch ()
690 /// {
691 /// }
692 /// void foo() { bar(); }
693 /// class foo
694 /// {
695 /// };
696 /// if (foo())
697 /// {
698 /// }
699 /// else
700 /// {
701 /// }
702 /// enum X : int
703 /// {
704 /// A,
705 /// B
706 /// };
707 /// \endcode
708 BS_Allman,
709 /// Like ``Allman`` but always indent braces and line up code with braces.
710 /// \code
711 /// try
712 /// {
713 /// foo();
714 /// }
715 /// catch ()
716 /// {
717 /// }
718 /// void foo() { bar(); }
719 /// class foo
720 /// {
721 /// };
722 /// if (foo())
723 /// {
724 /// }
725 /// else
726 /// {
727 /// }
728 /// enum X : int
729 /// {
730 /// A,
731 /// B
732 /// };
733 /// \endcode
734 BS_Whitesmiths,
735 /// Always break before braces and add an extra level of indentation to
736 /// braces of control statements, not to those of class, function
737 /// or other definitions.
738 /// \code
739 /// try
740 /// {
741 /// foo();
742 /// }
743 /// catch ()
744 /// {
745 /// }
746 /// void foo() { bar(); }
747 /// class foo
748 /// {
749 /// };
750 /// if (foo())
751 /// {
752 /// }
753 /// else
754 /// {
755 /// }
756 /// enum X : int
757 /// {
758 /// A,
759 /// B
760 /// };
761 /// \endcode
762 BS_GNU,
763 /// Like ``Attach``, but break before functions.
764 /// \code
765 /// try {
766 /// foo();
767 /// } catch () {
768 /// }
769 /// void foo() { bar(); }
770 /// class foo {
771 /// };
772 /// if (foo()) {
773 /// } else {
774 /// }
775 /// enum X : int { A, B };
776 /// \endcode
777 BS_WebKit,
778 /// Configure each individual brace in `BraceWrapping`.
779 BS_Custom
780 };
781
782 /// The brace breaking style to use.
783 BraceBreakingStyle BreakBeforeBraces;
784
785 /// Different ways to wrap braces after control statements.
786 enum BraceWrappingAfterControlStatementStyle {
787 /// Never wrap braces after a control statement.
788 /// \code
789 /// if (foo()) {
790 /// } else {
791 /// }
792 /// for (int i = 0; i < 10; ++i) {
793 /// }
794 /// \endcode
795 BWACS_Never,
796 /// Only wrap braces after a multi-line control statement.
797 /// \code
798 /// if (foo && bar &&
799 /// baz)
800 /// {
801 /// quux();
802 /// }
803 /// while (foo || bar) {
804 /// }
805 /// \endcode
806 BWACS_MultiLine,
807 /// Always wrap braces after a control statement.
808 /// \code
809 /// if (foo())
810 /// {
811 /// } else
812 /// {}
813 /// for (int i = 0; i < 10; ++i)
814 /// {}
815 /// \endcode
816 BWACS_Always
817 };
818
819 /// Precise control over the wrapping of braces.
820 /// \code
821 /// # Should be declared this way:
822 /// BreakBeforeBraces: Custom
823 /// BraceWrapping:
824 /// AfterClass: true
825 /// \endcode
826 struct BraceWrappingFlags {
827 /// Wrap case labels.
828 /// \code
829 /// false: true:
830 /// switch (foo) { vs. switch (foo) {
831 /// case 1: { case 1:
832 /// bar(); {
833 /// break; bar();
834 /// } break;
835 /// default: { }
836 /// plop(); default:
837 /// } {
838 /// } plop();
839 /// }
840 /// }
841 /// \endcode
842 bool AfterCaseLabel;
843 /// Wrap class definitions.
844 /// \code
845 /// true:
846 /// class foo {};
847 ///
848 /// false:
849 /// class foo
850 /// {};
851 /// \endcode
852 bool AfterClass;
853
854 /// Wrap control statements (``if``/``for``/``while``/``switch``/..).
855 BraceWrappingAfterControlStatementStyle AfterControlStatement;
856 /// Wrap enum definitions.
857 /// \code
858 /// true:
859 /// enum X : int
860 /// {
861 /// B
862 /// };
863 ///
864 /// false:
865 /// enum X : int { B };
866 /// \endcode
867 bool AfterEnum;
868 /// Wrap function definitions.
869 /// \code
870 /// true:
871 /// void foo()
872 /// {
873 /// bar();
874 /// bar2();
875 /// }
876 ///
877 /// false:
878 /// void foo() {
879 /// bar();
880 /// bar2();
881 /// }
882 /// \endcode
883 bool AfterFunction;
884 /// Wrap namespace definitions.
885 /// \code
886 /// true:
887 /// namespace
888 /// {
889 /// int foo();
890 /// int bar();
891 /// }
892 ///
893 /// false:
894 /// namespace {
895 /// int foo();
896 /// int bar();
897 /// }
898 /// \endcode
899 bool AfterNamespace;
900 /// Wrap ObjC definitions (interfaces, implementations...).
901 /// \note @autoreleasepool and @synchronized blocks are wrapped
902 /// according to `AfterControlStatement` flag.
903 bool AfterObjCDeclaration;
904 /// Wrap struct definitions.
905 /// \code
906 /// true:
907 /// struct foo
908 /// {
909 /// int x;
910 /// };
911 ///
912 /// false:
913 /// struct foo {
914 /// int x;
915 /// };
916 /// \endcode
917 bool AfterStruct;
918 /// Wrap union definitions.
919 /// \code
920 /// true:
921 /// union foo
922 /// {
923 /// int x;
924 /// }
925 ///
926 /// false:
927 /// union foo {
928 /// int x;
929 /// }
930 /// \endcode
931 bool AfterUnion;
932 /// Wrap extern blocks.
933 /// \code
934 /// true:
935 /// extern "C"
936 /// {
937 /// int foo();
938 /// }
939 ///
940 /// false:
941 /// extern "C" {
942 /// int foo();
943 /// }
944 /// \endcode
945 bool AfterExternBlock;
946 /// Wrap before ``catch``.
947 /// \code
948 /// true:
949 /// try {
950 /// foo();
951 /// }
952 /// catch () {
953 /// }
954 ///
955 /// false:
956 /// try {
957 /// foo();
958 /// } catch () {
959 /// }
960 /// \endcode
961 bool BeforeCatch;
962 /// Wrap before ``else``.
963 /// \code
964 /// true:
965 /// if (foo()) {
966 /// }
967 /// else {
968 /// }
969 ///
970 /// false:
971 /// if (foo()) {
972 /// } else {
973 /// }
974 /// \endcode
975 bool BeforeElse;
976 /// Indent the wrapped braces themselves.
977 bool IndentBraces;
978 /// If ``false``, empty function body can be put on a single line.
979 /// This option is used only if the opening brace of the function has
980 /// already been wrapped, i.e. the `AfterFunction` brace wrapping mode is
981 /// set, and the function could/should not be put on a single line (as per
982 /// `AllowShortFunctionsOnASingleLine` and constructor formatting options).
983 /// \code
984 /// int f() vs. int f()
985 /// {} {
986 /// }
987 /// \endcode
988 ///
989 bool SplitEmptyFunction;
990 /// If ``false``, empty record (e.g. class, struct or union) body
991 /// can be put on a single line. This option is used only if the opening
992 /// brace of the record has already been wrapped, i.e. the `AfterClass`
993 /// (for classes) brace wrapping mode is set.
994 /// \code
995 /// class Foo vs. class Foo
996 /// {} {
997 /// }
998 /// \endcode
999 ///
1000 bool SplitEmptyRecord;
1001 /// If ``false``, empty namespace body can be put on a single line.
1002 /// This option is used only if the opening brace of the namespace has
1003 /// already been wrapped, i.e. the `AfterNamespace` brace wrapping mode is
1004 /// set.
1005 /// \code
1006 /// namespace Foo vs. namespace Foo
1007 /// {} {
1008 /// }
1009 /// \endcode
1010 ///
1011 bool SplitEmptyNamespace;
1012 };
1013
1014 /// Control of individual brace wrapping cases.
1015 ///
1016 /// If ``BreakBeforeBraces`` is set to ``BS_Custom``, use this to specify how
1017 /// each individual brace case should be handled. Otherwise, this is ignored.
1018 /// \code{.yaml}
1019 /// # Example of usage:
1020 /// BreakBeforeBraces: Custom
1021 /// BraceWrapping:
1022 /// AfterEnum: true
1023 /// AfterStruct: false
1024 /// SplitEmptyFunction: false
1025 /// \endcode
1026 BraceWrappingFlags BraceWrapping;
1027
1028 /// If ``true``, ternary operators will be placed after line breaks.
1029 /// \code
1030 /// true:
1031 /// veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongDescription
1032 /// ? firstValue
1033 /// : SecondValueVeryVeryVeryVeryLong;
1034 ///
1035 /// false:
1036 /// veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongDescription ?
1037 /// firstValue :
1038 /// SecondValueVeryVeryVeryVeryLong;
1039 /// \endcode
1040 bool BreakBeforeTernaryOperators;
1041
1042 /// Different ways to break initializers.
1043 enum BreakConstructorInitializersStyle {
1044 /// Break constructor initializers before the colon and after the commas.
1045 /// \code
1046 /// Constructor()
1047 /// : initializer1(),
1048 /// initializer2()
1049 /// \endcode
1050 BCIS_BeforeColon,
1051 /// Break constructor initializers before the colon and commas, and align
1052 /// the commas with the colon.
1053 /// \code
1054 /// Constructor()
1055 /// : initializer1()
1056 /// , initializer2()
1057 /// \endcode
1058 BCIS_BeforeComma,
1059 /// Break constructor initializers after the colon and commas.
1060 /// \code
1061 /// Constructor() :
1062 /// initializer1(),
1063 /// initializer2()
1064 /// \endcode
1065 BCIS_AfterColon
1066 };
1067
1068 /// The constructor initializers style to use.
1069 BreakConstructorInitializersStyle BreakConstructorInitializers;
1070
1071 /// Break after each annotation on a field in Java files.
1072 /// \code{.java}
1073 /// true: false:
1074 /// @Partial vs. @Partial @Mock DataLoad loader;
1075 /// @Mock
1076 /// DataLoad loader;
1077 /// \endcode
1078 bool BreakAfterJavaFieldAnnotations;
1079
1080 /// Allow breaking string literals when formatting.
1081 /// \code
1082 /// true:
1083 /// const char* x = "veryVeryVeryVeryVeryVe"
1084 /// "ryVeryVeryVeryVeryVery"
1085 /// "VeryLongString";
1086 ///
1087 /// false:
1088 /// const char* x =
1089 /// "veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongString";
1090 /// \endcode
1091 bool BreakStringLiterals;
1092
1093 /// The column limit.
1094 ///
1095 /// A column limit of ``0`` means that there is no column limit. In this case,
1096 /// clang-format will respect the input's line breaking decisions within
1097 /// statements unless they contradict other rules.
1098 unsigned ColumnLimit;
1099
1100 /// A regular expression that describes comments with special meaning,
1101 /// which should not be split into lines or otherwise changed.
1102 /// \code
1103 /// // CommentPragmas: '^ FOOBAR pragma:'
1104 /// // Will leave the following line unaffected
1105 /// #include <vector> // FOOBAR pragma: keep
1106 /// \endcode
1107 std::string CommentPragmas;
1108
1109 /// Different ways to break inheritance list.
1110 enum BreakInheritanceListStyle {
1111 /// Break inheritance list before the colon and after the commas.
1112 /// \code
1113 /// class Foo
1114 /// : Base1,
1115 /// Base2
1116 /// {};
1117 /// \endcode
1118 BILS_BeforeColon,
1119 /// Break inheritance list before the colon and commas, and align
1120 /// the commas with the colon.
1121 /// \code
1122 /// class Foo
1123 /// : Base1
1124 /// , Base2
1125 /// {};
1126 /// \endcode
1127 BILS_BeforeComma,
1128 /// Break inheritance list after the colon and commas.
1129 /// \code
1130 /// class Foo :
1131 /// Base1,
1132 /// Base2
1133 /// {};
1134 /// \endcode
1135 BILS_AfterColon
1136 };
1137
1138 /// The inheritance list style to use.
1139 BreakInheritanceListStyle BreakInheritanceList;
1140
1141 /// If ``true``, consecutive namespace declarations will be on the same
1142 /// line. If ``false``, each namespace is declared on a new line.
1143 /// \code
1144 /// true:
1145 /// namespace Foo { namespace Bar {
1146 /// }}
1147 ///
1148 /// false:
1149 /// namespace Foo {
1150 /// namespace Bar {
1151 /// }
1152 /// }
1153 /// \endcode
1154 ///
1155 /// If it does not fit on a single line, the overflowing namespaces get
1156 /// wrapped:
1157 /// \code
1158 /// namespace Foo { namespace Bar {
1159 /// namespace Extra {
1160 /// }}}
1161 /// \endcode
1162 bool CompactNamespaces;
1163
1164 // clang-format off
1165 /// If the constructor initializers don't fit on a line, put each
1166 /// initializer on its own line.
1167 /// \code
1168 /// true:
1169 /// SomeClass::Constructor()
1170 /// : aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa) {
1171 /// return 0;
1172 /// }
1173 ///
1174 /// false:
1175 /// SomeClass::Constructor()
1176 /// : aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaa),
1177 /// aaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa) {
1178 /// return 0;
1179 /// }
1180 /// \endcode
1181 bool ConstructorInitializerAllOnOneLineOrOnePerLine;
1182 // clang-format on
1183
1184 /// The number of characters to use for indentation of constructor
1185 /// initializer lists as well as inheritance lists.
1186 unsigned ConstructorInitializerIndentWidth;
1187
1188 /// Indent width for line continuations.
1189 /// \code
1190 /// ContinuationIndentWidth: 2
1191 ///
1192 /// int i = // VeryVeryVeryVeryVeryLongComment
1193 /// longFunction( // Again a long comment
1194 /// arg);
1195 /// \endcode
1196 unsigned ContinuationIndentWidth;
1197
1198 /// If ``true``, format braced lists as best suited for C++11 braced
1199 /// lists.
1200 ///
1201 /// Important differences:
1202 /// - No spaces inside the braced list.
1203 /// - No line break before the closing brace.
1204 /// - Indentation with the continuation indent, not with the block indent.
1205 ///
1206 /// Fundamentally, C++11 braced lists are formatted exactly like function
1207 /// calls would be formatted in their place. If the braced list follows a name
1208 /// (e.g. a type or variable name), clang-format formats as if the ``{}`` were
1209 /// the parentheses of a function call with that name. If there is no name,
1210 /// a zero-length name is assumed.
1211 /// \code
1212 /// true: false:
1213 /// vector<int> x{1, 2, 3, 4}; vs. vector<int> x{ 1, 2, 3, 4 };
1214 /// vector<T> x{{}, {}, {}, {}}; vector<T> x{ {}, {}, {}, {} };
1215 /// f(MyMap[{composite, key}]); f(MyMap[{ composite, key }]);
1216 /// new int[3]{1, 2, 3}; new int[3]{ 1, 2, 3 };
1217 /// \endcode
1218 bool Cpp11BracedListStyle;
1219
1220 /// \brief Analyze the formatted file for the most used line ending (``\r\n``
1221 /// or ``\n``). ``UseCRLF`` is only used as a fallback if none can be derived.
1222 bool DeriveLineEnding;
1223
1224 /// If ``true``, analyze the formatted file for the most common
1225 /// alignment of ``&`` and ``*``.
1226 /// Pointer and reference alignment styles are going to be updated according
1227 /// to the preferences found in the file.
1228 /// ``PointerAlignment`` is then used only as fallback.
1229 bool DerivePointerAlignment;
1230
1231 /// Disables formatting completely.
1232 bool DisableFormat;
1233
1234 /// If ``true``, clang-format detects whether function calls and
1235 /// definitions are formatted with one parameter per line.
1236 ///
1237 /// Each call can be bin-packed, one-per-line or inconclusive. If it is
1238 /// inconclusive, e.g. completely on one line, but a decision needs to be
1239 /// made, clang-format analyzes whether there are other bin-packed cases in
1240 /// the input file and act accordingly.
1241 ///
1242 /// NOTE: This is an experimental flag, that might go away or be renamed. Do
1243 /// not use this in config files, etc. Use at your own risk.
1244 bool ExperimentalAutoDetectBinPacking;
1245
1246 /// If ``true``, clang-format adds missing namespace end comments and
1247 /// fixes invalid existing ones.
1248 /// \code
1249 /// true: false:
1250 /// namespace a { vs. namespace a {
1251 /// foo(); foo();
1252 /// } // namespace a }
1253 /// \endcode
1254 bool FixNamespaceComments;
1255
1256 /// A vector of macros that should be interpreted as foreach loops
1257 /// instead of as function calls.
1258 ///
1259 /// These are expected to be macros of the form:
1260 /// \code
1261 /// FOREACH(<variable-declaration>, ...)
1262 /// <loop-body>
1263 /// \endcode
1264 ///
1265 /// In the .clang-format configuration file, this can be configured like:
1266 /// \code{.yaml}
1267 /// ForEachMacros: ['RANGES_FOR', 'FOREACH']
1268 /// \endcode
1269 ///
1270 /// For example: BOOST_FOREACH.
1271 std::vector<std::string> ForEachMacros;
1272
1273 /// \brief A vector of macros that should be interpreted as type declarations
1274 /// instead of as function calls.
1275 ///
1276 /// These are expected to be macros of the form:
1277 /// \code
1278 /// STACK_OF(...)
1279 /// \endcode
1280 ///
1281 /// In the .clang-format configuration file, this can be configured like:
1282 /// \code{.yaml}
1283 /// TypenameMacros: ['STACK_OF', 'LIST']
1284 /// \endcode
1285 ///
1286 /// For example: OpenSSL STACK_OF, BSD LIST_ENTRY.
1287 std::vector<std::string> TypenameMacros;
1288
1289 /// A vector of macros that should be interpreted as complete
1290 /// statements.
1291 ///
1292 /// Typical macros are expressions, and require a semi-colon to be
1293 /// added; sometimes this is not the case, and this allows to make
1294 /// clang-format aware of such cases.
1295 ///
1296 /// For example: Q_UNUSED
1297 std::vector<std::string> StatementMacros;
1298
1299 /// A vector of macros which are used to open namespace blocks.
1300 ///
1301 /// These are expected to be macros of the form:
1302 /// \code
1303 /// NAMESPACE(<namespace-name>, ...) {
1304 /// <namespace-content>
1305 /// }
1306 /// \endcode
1307 ///
1308 /// For example: TESTSUITE
1309 std::vector<std::string> NamespaceMacros;
1310
1311 tooling::IncludeStyle IncludeStyle;
1312
1313 /// Indent case labels one level from the switch statement.
1314 ///
1315 /// When ``false``, use the same indentation level as for the switch
1316 /// statement. Switch statement body is always indented one level more than
1317 /// case labels.
1318 /// \code
1319 /// false: true:
1320 /// switch (fool) { vs. switch (fool) {
1321 /// case 1: case 1:
1322 /// bar(); bar();
1323 /// break; break;
1324 /// default: default:
1325 /// plop(); plop();
1326 /// } }
1327 /// \endcode
1328 bool IndentCaseLabels;
1329
1330 /// Indent goto labels.
1331 ///
1332 /// When ``false``, goto labels are flushed left.
1333 /// \code
1334 /// true: false:
1335 /// int f() { vs. int f() {
1336 /// if (foo()) { if (foo()) {
1337 /// label1: label1:
1338 /// bar(); bar();
1339 /// } }
1340 /// label2: label2:
1341 /// return 1; return 1;
1342 /// } }
1343 /// \endcode
1344 bool IndentGotoLabels;
1345
1346 /// Options for indenting preprocessor directives.
1347 enum PPDirectiveIndentStyle {
1348 /// Does not indent any directives.
1349 /// \code
1350 /// #if FOO
1351 /// #if BAR
1352 /// #include <foo>
1353 /// #endif
1354 /// #endif
1355 /// \endcode
1356 PPDIS_None,
1357 /// Indents directives after the hash.
1358 /// \code
1359 /// #if FOO
1360 /// # if BAR
1361 /// # include <foo>
1362 /// # endif
1363 /// #endif
1364 /// \endcode
1365 PPDIS_AfterHash,
1366 /// Indents directives before the hash.
1367 /// \code
1368 /// #if FOO
1369 /// #if BAR
1370 /// #include <foo>
1371 /// #endif
1372 /// #endif
1373 /// \endcode
1374 PPDIS_BeforeHash
1375 };
1376
1377 /// The preprocessor directive indenting style to use.
1378 PPDirectiveIndentStyle IndentPPDirectives;
1379
1380 /// The number of columns to use for indentation.
1381 /// \code
1382 /// IndentWidth: 3
1383 ///
1384 /// void f() {
1385 /// someFunction();
1386 /// if (true, false) {
1387 /// f();
1388 /// }
1389 /// }
1390 /// \endcode
1391 unsigned IndentWidth;
1392
1393 /// Indent if a function definition or declaration is wrapped after the
1394 /// type.
1395 /// \code
1396 /// true:
1397 /// LoooooooooooooooooooooooooooooooooooooooongReturnType
1398 /// LoooooooooooooooooooooooooooooooongFunctionDeclaration();
1399 ///
1400 /// false:
1401 /// LoooooooooooooooooooooooooooooooooooooooongReturnType
1402 /// LoooooooooooooooooooooooooooooooongFunctionDeclaration();
1403 /// \endcode
1404 bool IndentWrappedFunctionNames;
1405
1406 /// A vector of prefixes ordered by the desired groups for Java imports.
1407 ///
1408 /// Each group is separated by a newline. Static imports will also follow the
1409 /// same grouping convention above all non-static imports. One group's prefix
1410 /// can be a subset of another - the longest prefix is always matched. Within
1411 /// a group, the imports are ordered lexicographically.
1412 ///
1413 /// In the .clang-format configuration file, this can be configured like
1414 /// in the following yaml example. This will result in imports being
1415 /// formatted as in the Java example below.
1416 /// \code{.yaml}
1417 /// JavaImportGroups: ['com.example', 'com', 'org']
1418 /// \endcode
1419 ///
1420 /// \code{.java}
1421 /// import static com.example.function1;
1422 ///
1423 /// import static com.test.function2;
1424 ///
1425 /// import static org.example.function3;
1426 ///
1427 /// import com.example.ClassA;
1428 /// import com.example.Test;
1429 /// import com.example.a.ClassB;
1430 ///
1431 /// import com.test.ClassC;
1432 ///
1433 /// import org.example.ClassD;
1434 /// \endcode
1435 std::vector<std::string> JavaImportGroups;
1436
1437 /// Quotation styles for JavaScript strings. Does not affect template
1438 /// strings.
1439 enum JavaScriptQuoteStyle {
1440 /// Leave string quotes as they are.
1441 /// \code{.js}
1442 /// string1 = "foo";
1443 /// string2 = 'bar';
1444 /// \endcode
1445 JSQS_Leave,
1446 /// Always use single quotes.
1447 /// \code{.js}
1448 /// string1 = 'foo';
1449 /// string2 = 'bar';
1450 /// \endcode
1451 JSQS_Single,
1452 /// Always use double quotes.
1453 /// \code{.js}
1454 /// string1 = "foo";
1455 /// string2 = "bar";
1456 /// \endcode
1457 JSQS_Double
1458 };
1459
1460 /// The JavaScriptQuoteStyle to use for JavaScript strings.
1461 JavaScriptQuoteStyle JavaScriptQuotes;
1462
1463 // clang-format off
1464 /// Whether to wrap JavaScript import/export statements.
1465 /// \code{.js}
1466 /// true:
1467 /// import {
1468 /// VeryLongImportsAreAnnoying,
1469 /// VeryLongImportsAreAnnoying,
1470 /// VeryLongImportsAreAnnoying,
1471 /// } from 'some/module.js'
1472 ///
1473 /// false:
1474 /// import {VeryLongImportsAreAnnoying, VeryLongImportsAreAnnoying, VeryLongImportsAreAnnoying,} from "some/module.js"
1475 /// \endcode
1476 bool JavaScriptWrapImports;
1477 // clang-format on
1478
1479 /// If true, the empty line at the start of blocks is kept.
1480 /// \code
1481 /// true: false:
1482 /// if (foo) { vs. if (foo) {
1483 /// bar();
1484 /// bar(); }
1485 /// }
1486 /// \endcode
1487 bool KeepEmptyLinesAtTheStartOfBlocks;
1488
1489 /// Supported languages.
1490 ///
1491 /// When stored in a configuration file, specifies the language, that the
1492 /// configuration targets. When passed to the ``reformat()`` function, enables
1493 /// syntax features specific to the language.
1494 enum LanguageKind {
1495 /// Do not use.
1496 LK_None,
1497 /// Should be used for C, C++.
1498 LK_Cpp,
1499 /// Should be used for C#.
1500 LK_CSharp,
1501 /// Should be used for Java.
1502 LK_Java,
1503 /// Should be used for JavaScript.
1504 LK_JavaScript,
1505 /// Should be used for Objective-C, Objective-C++.
1506 LK_ObjC,
1507 /// Should be used for Protocol Buffers
1508 /// (https://developers.google.com/protocol-buffers/).
1509 LK_Proto,
1510 /// Should be used for TableGen code.
1511 LK_TableGen,
1512 /// Should be used for Protocol Buffer messages in text format
1513 /// (https://developers.google.com/protocol-buffers/).
1514 LK_TextProto
1515 };
isCppFormatStyle1516 bool isCpp() const { return Language == LK_Cpp || Language == LK_ObjC; }
isCSharpFormatStyle1517 bool isCSharp() const { return Language == LK_CSharp; }
1518
1519 /// Language, this format style is targeted at.
1520 LanguageKind Language;
1521
1522 /// A regular expression matching macros that start a block.
1523 /// \code
1524 /// # With:
1525 /// MacroBlockBegin: "^NS_MAP_BEGIN|\
1526 /// NS_TABLE_HEAD$"
1527 /// MacroBlockEnd: "^\
1528 /// NS_MAP_END|\
1529 /// NS_TABLE_.*_END$"
1530 ///
1531 /// NS_MAP_BEGIN
1532 /// foo();
1533 /// NS_MAP_END
1534 ///
1535 /// NS_TABLE_HEAD
1536 /// bar();
1537 /// NS_TABLE_FOO_END
1538 ///
1539 /// # Without:
1540 /// NS_MAP_BEGIN
1541 /// foo();
1542 /// NS_MAP_END
1543 ///
1544 /// NS_TABLE_HEAD
1545 /// bar();
1546 /// NS_TABLE_FOO_END
1547 /// \endcode
1548 std::string MacroBlockBegin;
1549
1550 /// A regular expression matching macros that end a block.
1551 std::string MacroBlockEnd;
1552
1553 /// The maximum number of consecutive empty lines to keep.
1554 /// \code
1555 /// MaxEmptyLinesToKeep: 1 vs. MaxEmptyLinesToKeep: 0
1556 /// int f() { int f() {
1557 /// int = 1; int i = 1;
1558 /// i = foo();
1559 /// i = foo(); return i;
1560 /// }
1561 /// return i;
1562 /// }
1563 /// \endcode
1564 unsigned MaxEmptyLinesToKeep;
1565
1566 /// Different ways to indent namespace contents.
1567 enum NamespaceIndentationKind {
1568 /// Don't indent in namespaces.
1569 /// \code
1570 /// namespace out {
1571 /// int i;
1572 /// namespace in {
1573 /// int i;
1574 /// }
1575 /// }
1576 /// \endcode
1577 NI_None,
1578 /// Indent only in inner namespaces (nested in other namespaces).
1579 /// \code
1580 /// namespace out {
1581 /// int i;
1582 /// namespace in {
1583 /// int i;
1584 /// }
1585 /// }
1586 /// \endcode
1587 NI_Inner,
1588 /// Indent in all namespaces.
1589 /// \code
1590 /// namespace out {
1591 /// int i;
1592 /// namespace in {
1593 /// int i;
1594 /// }
1595 /// }
1596 /// \endcode
1597 NI_All
1598 };
1599
1600 /// The indentation used for namespaces.
1601 NamespaceIndentationKind NamespaceIndentation;
1602
1603 /// Controls bin-packing Objective-C protocol conformance list
1604 /// items into as few lines as possible when they go over ``ColumnLimit``.
1605 ///
1606 /// If ``Auto`` (the default), delegates to the value in
1607 /// ``BinPackParameters``. If that is ``true``, bin-packs Objective-C
1608 /// protocol conformance list items into as few lines as possible
1609 /// whenever they go over ``ColumnLimit``.
1610 ///
1611 /// If ``Always``, always bin-packs Objective-C protocol conformance
1612 /// list items into as few lines as possible whenever they go over
1613 /// ``ColumnLimit``.
1614 ///
1615 /// If ``Never``, lays out Objective-C protocol conformance list items
1616 /// onto individual lines whenever they go over ``ColumnLimit``.
1617 ///
1618 /// \code{.objc}
1619 /// Always (or Auto, if BinPackParameters=true):
1620 /// @interface ccccccccccccc () <
1621 /// ccccccccccccc, ccccccccccccc,
1622 /// ccccccccccccc, ccccccccccccc> {
1623 /// }
1624 ///
1625 /// Never (or Auto, if BinPackParameters=false):
1626 /// @interface ddddddddddddd () <
1627 /// ddddddddddddd,
1628 /// ddddddddddddd,
1629 /// ddddddddddddd,
1630 /// ddddddddddddd> {
1631 /// }
1632 /// \endcode
1633 BinPackStyle ObjCBinPackProtocolList;
1634
1635 /// The number of characters to use for indentation of ObjC blocks.
1636 /// \code{.objc}
1637 /// ObjCBlockIndentWidth: 4
1638 ///
1639 /// [operation setCompletionBlock:^{
1640 /// [self onOperationDone];
1641 /// }];
1642 /// \endcode
1643 unsigned ObjCBlockIndentWidth;
1644
1645 /// Add a space after ``@property`` in Objective-C, i.e. use
1646 /// ``@property (readonly)`` instead of ``@property(readonly)``.
1647 bool ObjCSpaceAfterProperty;
1648
1649 /// Add a space in front of an Objective-C protocol list, i.e. use
1650 /// ``Foo <Protocol>`` instead of ``Foo<Protocol>``.
1651 bool ObjCSpaceBeforeProtocolList;
1652
1653 /// The penalty for breaking around an assignment operator.
1654 unsigned PenaltyBreakAssignment;
1655
1656 /// The penalty for breaking a function call after ``call(``.
1657 unsigned PenaltyBreakBeforeFirstCallParameter;
1658
1659 /// The penalty for each line break introduced inside a comment.
1660 unsigned PenaltyBreakComment;
1661
1662 /// The penalty for breaking before the first ``<<``.
1663 unsigned PenaltyBreakFirstLessLess;
1664
1665 /// The penalty for each line break introduced inside a string literal.
1666 unsigned PenaltyBreakString;
1667
1668 /// The penalty for breaking after template declaration.
1669 unsigned PenaltyBreakTemplateDeclaration;
1670
1671 /// The penalty for each character outside of the column limit.
1672 unsigned PenaltyExcessCharacter;
1673
1674 /// Penalty for putting the return type of a function onto its own
1675 /// line.
1676 unsigned PenaltyReturnTypeOnItsOwnLine;
1677
1678 /// The ``&`` and ``*`` alignment style.
1679 enum PointerAlignmentStyle {
1680 /// Align pointer to the left.
1681 /// \code
1682 /// int* a;
1683 /// \endcode
1684 PAS_Left,
1685 /// Align pointer to the right.
1686 /// \code
1687 /// int *a;
1688 /// \endcode
1689 PAS_Right,
1690 /// Align pointer in the middle.
1691 /// \code
1692 /// int * a;
1693 /// \endcode
1694 PAS_Middle
1695 };
1696
1697 /// Pointer and reference alignment style.
1698 PointerAlignmentStyle PointerAlignment;
1699
1700 /// See documentation of ``RawStringFormats``.
1701 struct RawStringFormat {
1702 /// The language of this raw string.
1703 LanguageKind Language;
1704 /// A list of raw string delimiters that match this language.
1705 std::vector<std::string> Delimiters;
1706 /// A list of enclosing function names that match this language.
1707 std::vector<std::string> EnclosingFunctions;
1708 /// The canonical delimiter for this language.
1709 std::string CanonicalDelimiter;
1710 /// The style name on which this raw string format is based on.
1711 /// If not specified, the raw string format is based on the style that this
1712 /// format is based on.
1713 std::string BasedOnStyle;
1714 bool operator==(const RawStringFormat &Other) const {
1715 return Language == Other.Language && Delimiters == Other.Delimiters &&
1716 EnclosingFunctions == Other.EnclosingFunctions &&
1717 CanonicalDelimiter == Other.CanonicalDelimiter &&
1718 BasedOnStyle == Other.BasedOnStyle;
1719 }
1720 };
1721
1722 /// Defines hints for detecting supported languages code blocks in raw
1723 /// strings.
1724 ///
1725 /// A raw string with a matching delimiter or a matching enclosing function
1726 /// name will be reformatted assuming the specified language based on the
1727 /// style for that language defined in the .clang-format file. If no style has
1728 /// been defined in the .clang-format file for the specific language, a
1729 /// predefined style given by 'BasedOnStyle' is used. If 'BasedOnStyle' is not
1730 /// found, the formatting is based on llvm style. A matching delimiter takes
1731 /// precedence over a matching enclosing function name for determining the
1732 /// language of the raw string contents.
1733 ///
1734 /// If a canonical delimiter is specified, occurrences of other delimiters for
1735 /// the same language will be updated to the canonical if possible.
1736 ///
1737 /// There should be at most one specification per language and each delimiter
1738 /// and enclosing function should not occur in multiple specifications.
1739 ///
1740 /// To configure this in the .clang-format file, use:
1741 /// \code{.yaml}
1742 /// RawStringFormats:
1743 /// - Language: TextProto
1744 /// Delimiters:
1745 /// - 'pb'
1746 /// - 'proto'
1747 /// EnclosingFunctions:
1748 /// - 'PARSE_TEXT_PROTO'
1749 /// BasedOnStyle: google
1750 /// - Language: Cpp
1751 /// Delimiters:
1752 /// - 'cc'
1753 /// - 'cpp'
1754 /// BasedOnStyle: llvm
1755 /// CanonicalDelimiter: 'cc'
1756 /// \endcode
1757 std::vector<RawStringFormat> RawStringFormats;
1758
1759 // clang-format off
1760 /// If ``true``, clang-format will attempt to re-flow comments.
1761 /// \code
1762 /// false:
1763 /// // veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongComment with plenty of information
1764 /// /* second veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongComment with plenty of information */
1765 ///
1766 /// true:
1767 /// // veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongComment with plenty of
1768 /// // information
1769 /// /* second veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongComment with plenty of
1770 /// * information */
1771 /// \endcode
1772 bool ReflowComments;
1773 // clang-format on
1774
1775 /// If ``true``, clang-format will sort ``#includes``.
1776 /// \code
1777 /// false: true:
1778 /// #include "b.h" vs. #include "a.h"
1779 /// #include "a.h" #include "b.h"
1780 /// \endcode
1781 bool SortIncludes;
1782
1783 /// If ``true``, clang-format will sort using declarations.
1784 ///
1785 /// The order of using declarations is defined as follows:
1786 /// Split the strings by "::" and discard any initial empty strings. The last
1787 /// element of each list is a non-namespace name; all others are namespace
1788 /// names. Sort the lists of names lexicographically, where the sort order of
1789 /// individual names is that all non-namespace names come before all namespace
1790 /// names, and within those groups, names are in case-insensitive
1791 /// lexicographic order.
1792 /// \code
1793 /// false: true:
1794 /// using std::cout; vs. using std::cin;
1795 /// using std::cin; using std::cout;
1796 /// \endcode
1797 bool SortUsingDeclarations;
1798
1799 /// If ``true``, a space is inserted after C style casts.
1800 /// \code
1801 /// true: false:
1802 /// (int) i; vs. (int)i;
1803 /// \endcode
1804 bool SpaceAfterCStyleCast;
1805
1806 /// If ``true``, a space is inserted after the logical not operator (``!``).
1807 /// \code
1808 /// true: false:
1809 /// ! someExpression(); vs. !someExpression();
1810 /// \endcode
1811 bool SpaceAfterLogicalNot;
1812
1813 /// If \c true, a space will be inserted after the 'template' keyword.
1814 /// \code
1815 /// true: false:
1816 /// template <int> void foo(); vs. template<int> void foo();
1817 /// \endcode
1818 bool SpaceAfterTemplateKeyword;
1819
1820 /// If ``false``, spaces will be removed before assignment operators.
1821 /// \code
1822 /// true: false:
1823 /// int a = 5; vs. int a= 5;
1824 /// a += 42; a+= 42;
1825 /// \endcode
1826 bool SpaceBeforeAssignmentOperators;
1827
1828 /// If ``true``, a space will be inserted before a C++11 braced list
1829 /// used to initialize an object (after the preceding identifier or type).
1830 /// \code
1831 /// true: false:
1832 /// Foo foo { bar }; vs. Foo foo{ bar };
1833 /// Foo {}; Foo{};
1834 /// vector<int> { 1, 2, 3 }; vector<int>{ 1, 2, 3 };
1835 /// new int[3] { 1, 2, 3 }; new int[3]{ 1, 2, 3 };
1836 /// \endcode
1837 bool SpaceBeforeCpp11BracedList;
1838
1839 /// If ``false``, spaces will be removed before constructor initializer
1840 /// colon.
1841 /// \code
1842 /// true: false:
1843 /// Foo::Foo() : a(a) {} Foo::Foo(): a(a) {}
1844 /// \endcode
1845 bool SpaceBeforeCtorInitializerColon;
1846
1847 /// If ``false``, spaces will be removed before inheritance colon.
1848 /// \code
1849 /// true: false:
1850 /// class Foo : Bar {} vs. class Foo: Bar {}
1851 /// \endcode
1852 bool SpaceBeforeInheritanceColon;
1853
1854 /// Different ways to put a space before opening parentheses.
1855 enum SpaceBeforeParensOptions {
1856 /// Never put a space before opening parentheses.
1857 /// \code
1858 /// void f() {
1859 /// if(true) {
1860 /// f();
1861 /// }
1862 /// }
1863 /// \endcode
1864 SBPO_Never,
1865 /// Put a space before opening parentheses only after control statement
1866 /// keywords (``for/if/while...``).
1867 /// \code
1868 /// void f() {
1869 /// if (true) {
1870 /// f();
1871 /// }
1872 /// }
1873 /// \endcode
1874 SBPO_ControlStatements,
1875 /// Put a space before opening parentheses only if the parentheses are not
1876 /// empty i.e. '()'
1877 /// \code
1878 /// void() {
1879 /// if (true) {
1880 /// f();
1881 /// g (x, y, z);
1882 /// }
1883 /// }
1884 /// \endcode
1885 SBPO_NonEmptyParentheses,
1886 /// Always put a space before opening parentheses, except when it's
1887 /// prohibited by the syntax rules (in function-like macro definitions) or
1888 /// when determined by other style rules (after unary operators, opening
1889 /// parentheses, etc.)
1890 /// \code
1891 /// void f () {
1892 /// if (true) {
1893 /// f ();
1894 /// }
1895 /// }
1896 /// \endcode
1897 SBPO_Always
1898 };
1899
1900 /// Defines in which cases to put a space before opening parentheses.
1901 SpaceBeforeParensOptions SpaceBeforeParens;
1902
1903 /// If ``false``, spaces will be removed before range-based for loop
1904 /// colon.
1905 /// \code
1906 /// true: false:
1907 /// for (auto v : values) {} vs. for(auto v: values) {}
1908 /// \endcode
1909 bool SpaceBeforeRangeBasedForLoopColon;
1910
1911 /// If ``true``, spaces will be inserted into ``{}``.
1912 /// \code
1913 /// true: false:
1914 /// void f() { } vs. void f() {}
1915 /// while (true) { } while (true) {}
1916 /// \endcode
1917 bool SpaceInEmptyBlock;
1918
1919 /// If ``true``, spaces may be inserted into ``()``.
1920 /// \code
1921 /// true: false:
1922 /// void f( ) { vs. void f() {
1923 /// int x[] = {foo( ), bar( )}; int x[] = {foo(), bar()};
1924 /// if (true) { if (true) {
1925 /// f( ); f();
1926 /// } }
1927 /// } }
1928 /// \endcode
1929 bool SpaceInEmptyParentheses;
1930
1931 /// The number of spaces before trailing line comments
1932 /// (``//`` - comments).
1933 ///
1934 /// This does not affect trailing block comments (``/*`` - comments) as
1935 /// those commonly have different usage patterns and a number of special
1936 /// cases.
1937 /// \code
1938 /// SpacesBeforeTrailingComments: 3
1939 /// void f() {
1940 /// if (true) { // foo1
1941 /// f(); // bar
1942 /// } // foo
1943 /// }
1944 /// \endcode
1945 unsigned SpacesBeforeTrailingComments;
1946
1947 /// If ``true``, spaces will be inserted after ``<`` and before ``>``
1948 /// in template argument lists.
1949 /// \code
1950 /// true: false:
1951 /// static_cast< int >(arg); vs. static_cast<int>(arg);
1952 /// std::function< void(int) > fct; std::function<void(int)> fct;
1953 /// \endcode
1954 bool SpacesInAngles;
1955
1956 /// If ``true``, spaces will be inserted around if/for/switch/while
1957 /// conditions.
1958 /// \code
1959 /// true: false:
1960 /// if ( a ) { ... } vs. if (a) { ... }
1961 /// while ( i < 5 ) { ... } while (i < 5) { ... }
1962 /// \endcode
1963 bool SpacesInConditionalStatement;
1964
1965 /// If ``true``, spaces are inserted inside container literals (e.g.
1966 /// ObjC and Javascript array and dict literals).
1967 /// \code{.js}
1968 /// true: false:
1969 /// var arr = [ 1, 2, 3 ]; vs. var arr = [1, 2, 3];
1970 /// f({a : 1, b : 2, c : 3}); f({a: 1, b: 2, c: 3});
1971 /// \endcode
1972 bool SpacesInContainerLiterals;
1973
1974 /// If ``true``, spaces may be inserted into C style casts.
1975 /// \code
1976 /// true: false:
1977 /// x = ( int32 )y vs. x = (int32)y
1978 /// \endcode
1979 bool SpacesInCStyleCastParentheses;
1980
1981 /// If ``true``, spaces will be inserted after ``(`` and before ``)``.
1982 /// \code
1983 /// true: false:
1984 /// t f( Deleted & ) & = delete; vs. t f(Deleted &) & = delete;
1985 /// \endcode
1986 bool SpacesInParentheses;
1987
1988 /// If ``true``, spaces will be inserted after ``[`` and before ``]``.
1989 /// Lambdas without arguments or unspecified size array declarations will not
1990 /// be affected.
1991 /// \code
1992 /// true: false:
1993 /// int a[ 5 ]; vs. int a[5];
1994 /// std::unique_ptr<int[]> foo() {} // Won't be affected
1995 /// \endcode
1996 bool SpacesInSquareBrackets;
1997
1998 /// If ``true``, spaces will be before ``[``.
1999 /// Lambdas will not be affected. Only the first ``[`` will get a space added.
2000 /// \code
2001 /// true: false:
2002 /// int a [5]; vs. int a[5];
2003 /// int a [5][5]; vs. int a[5][5];
2004 /// \endcode
2005 bool SpaceBeforeSquareBrackets;
2006
2007 /// Supported language standards for parsing and formatting C++ constructs.
2008 /// \code
2009 /// Latest: vector<set<int>>
2010 /// c++03 vs. vector<set<int> >
2011 /// \endcode
2012 ///
2013 /// The correct way to spell a specific language version is e.g. ``c++11``.
2014 /// The historical aliases ``Cpp03`` and ``Cpp11`` are deprecated.
2015 enum LanguageStandard {
2016 /// Parse and format as C++03.
2017 /// ``Cpp03`` is a deprecated alias for ``c++03``
2018 LS_Cpp03, // c++03
2019 /// Parse and format as C++11.
2020 LS_Cpp11, // c++11
2021 /// Parse and format as C++14.
2022 LS_Cpp14, // c++14
2023 /// Parse and format as C++17.
2024 LS_Cpp17, // c++17
2025 /// Parse and format as C++20.
2026 LS_Cpp20, // c++20
2027 /// Parse and format using the latest supported language version.
2028 /// ``Cpp11`` is a deprecated alias for ``Latest``
2029 LS_Latest,
2030 /// Automatic detection based on the input.
2031 LS_Auto,
2032 };
2033
2034 /// Parse and format C++ constructs compatible with this standard.
2035 /// \code
2036 /// c++03: latest:
2037 /// vector<set<int> > x; vs. vector<set<int>> x;
2038 /// \endcode
2039 LanguageStandard Standard;
2040
2041 /// The number of columns used for tab stops.
2042 unsigned TabWidth;
2043
2044 /// Different ways to use tab in formatting.
2045 enum UseTabStyle {
2046 /// Never use tab.
2047 UT_Never,
2048 /// Use tabs only for indentation.
2049 UT_ForIndentation,
2050 /// Use tabs only for line continuation and indentation.
2051 UT_ForContinuationAndIndentation,
2052 /// Use tabs whenever we need to fill whitespace that spans at least from
2053 /// one tab stop to the next one.
2054 UT_Always
2055 };
2056
2057 /// \brief Use ``\r\n`` instead of ``\n`` for line breaks.
2058 /// Also used as fallback if ``DeriveLineEnding`` is true.
2059 bool UseCRLF;
2060
2061 /// The way to use tab characters in the resulting file.
2062 UseTabStyle UseTab;
2063
2064 bool operator==(const FormatStyle &R) const {
2065 return AccessModifierOffset == R.AccessModifierOffset &&
2066 AlignAfterOpenBracket == R.AlignAfterOpenBracket &&
2067 AlignConsecutiveAssignments == R.AlignConsecutiveAssignments &&
2068 AlignConsecutiveDeclarations == R.AlignConsecutiveDeclarations &&
2069 AlignEscapedNewlines == R.AlignEscapedNewlines &&
2070 AlignOperands == R.AlignOperands &&
2071 AlignTrailingComments == R.AlignTrailingComments &&
2072 AllowAllArgumentsOnNextLine == R.AllowAllArgumentsOnNextLine &&
2073 AllowAllConstructorInitializersOnNextLine ==
2074 R.AllowAllConstructorInitializersOnNextLine &&
2075 AllowAllParametersOfDeclarationOnNextLine ==
2076 R.AllowAllParametersOfDeclarationOnNextLine &&
2077 AllowShortBlocksOnASingleLine == R.AllowShortBlocksOnASingleLine &&
2078 AllowShortCaseLabelsOnASingleLine ==
2079 R.AllowShortCaseLabelsOnASingleLine &&
2080 AllowShortFunctionsOnASingleLine ==
2081 R.AllowShortFunctionsOnASingleLine &&
2082 AllowShortIfStatementsOnASingleLine ==
2083 R.AllowShortIfStatementsOnASingleLine &&
2084 AllowShortLambdasOnASingleLine == R.AllowShortLambdasOnASingleLine &&
2085 AllowShortLoopsOnASingleLine == R.AllowShortLoopsOnASingleLine &&
2086 AlwaysBreakAfterReturnType == R.AlwaysBreakAfterReturnType &&
2087 AlwaysBreakBeforeMultilineStrings ==
2088 R.AlwaysBreakBeforeMultilineStrings &&
2089 AlwaysBreakTemplateDeclarations ==
2090 R.AlwaysBreakTemplateDeclarations &&
2091 BinPackArguments == R.BinPackArguments &&
2092 BinPackParameters == R.BinPackParameters &&
2093 BreakBeforeBinaryOperators == R.BreakBeforeBinaryOperators &&
2094 BreakBeforeBraces == R.BreakBeforeBraces &&
2095 BreakBeforeTernaryOperators == R.BreakBeforeTernaryOperators &&
2096 BreakConstructorInitializers == R.BreakConstructorInitializers &&
2097 CompactNamespaces == R.CompactNamespaces &&
2098 BreakAfterJavaFieldAnnotations == R.BreakAfterJavaFieldAnnotations &&
2099 BreakStringLiterals == R.BreakStringLiterals &&
2100 ColumnLimit == R.ColumnLimit && CommentPragmas == R.CommentPragmas &&
2101 BreakInheritanceList == R.BreakInheritanceList &&
2102 ConstructorInitializerAllOnOneLineOrOnePerLine ==
2103 R.ConstructorInitializerAllOnOneLineOrOnePerLine &&
2104 ConstructorInitializerIndentWidth ==
2105 R.ConstructorInitializerIndentWidth &&
2106 ContinuationIndentWidth == R.ContinuationIndentWidth &&
2107 Cpp11BracedListStyle == R.Cpp11BracedListStyle &&
2108 DeriveLineEnding == R.DeriveLineEnding &&
2109 DerivePointerAlignment == R.DerivePointerAlignment &&
2110 DisableFormat == R.DisableFormat &&
2111 ExperimentalAutoDetectBinPacking ==
2112 R.ExperimentalAutoDetectBinPacking &&
2113 FixNamespaceComments == R.FixNamespaceComments &&
2114 ForEachMacros == R.ForEachMacros &&
2115 IncludeStyle.IncludeBlocks == R.IncludeStyle.IncludeBlocks &&
2116 IncludeStyle.IncludeCategories == R.IncludeStyle.IncludeCategories &&
2117 IncludeStyle.IncludeIsMainRegex ==
2118 R.IncludeStyle.IncludeIsMainRegex &&
2119 IncludeStyle.IncludeIsMainSourceRegex ==
2120 R.IncludeStyle.IncludeIsMainSourceRegex &&
2121 IndentCaseLabels == R.IndentCaseLabels &&
2122 IndentGotoLabels == R.IndentGotoLabels &&
2123 IndentPPDirectives == R.IndentPPDirectives &&
2124 IndentWidth == R.IndentWidth && Language == R.Language &&
2125 IndentWrappedFunctionNames == R.IndentWrappedFunctionNames &&
2126 JavaImportGroups == R.JavaImportGroups &&
2127 JavaScriptQuotes == R.JavaScriptQuotes &&
2128 JavaScriptWrapImports == R.JavaScriptWrapImports &&
2129 KeepEmptyLinesAtTheStartOfBlocks ==
2130 R.KeepEmptyLinesAtTheStartOfBlocks &&
2131 MacroBlockBegin == R.MacroBlockBegin &&
2132 MacroBlockEnd == R.MacroBlockEnd &&
2133 MaxEmptyLinesToKeep == R.MaxEmptyLinesToKeep &&
2134 NamespaceIndentation == R.NamespaceIndentation &&
2135 NamespaceMacros == R.NamespaceMacros &&
2136 ObjCBinPackProtocolList == R.ObjCBinPackProtocolList &&
2137 ObjCBlockIndentWidth == R.ObjCBlockIndentWidth &&
2138 ObjCSpaceAfterProperty == R.ObjCSpaceAfterProperty &&
2139 ObjCSpaceBeforeProtocolList == R.ObjCSpaceBeforeProtocolList &&
2140 PenaltyBreakAssignment == R.PenaltyBreakAssignment &&
2141 PenaltyBreakBeforeFirstCallParameter ==
2142 R.PenaltyBreakBeforeFirstCallParameter &&
2143 PenaltyBreakComment == R.PenaltyBreakComment &&
2144 PenaltyBreakFirstLessLess == R.PenaltyBreakFirstLessLess &&
2145 PenaltyBreakString == R.PenaltyBreakString &&
2146 PenaltyExcessCharacter == R.PenaltyExcessCharacter &&
2147 PenaltyReturnTypeOnItsOwnLine == R.PenaltyReturnTypeOnItsOwnLine &&
2148 PenaltyBreakTemplateDeclaration ==
2149 R.PenaltyBreakTemplateDeclaration &&
2150 PointerAlignment == R.PointerAlignment &&
2151 RawStringFormats == R.RawStringFormats &&
2152 SpaceAfterCStyleCast == R.SpaceAfterCStyleCast &&
2153 SpaceAfterLogicalNot == R.SpaceAfterLogicalNot &&
2154 SpaceAfterTemplateKeyword == R.SpaceAfterTemplateKeyword &&
2155 SpaceBeforeAssignmentOperators == R.SpaceBeforeAssignmentOperators &&
2156 SpaceBeforeCpp11BracedList == R.SpaceBeforeCpp11BracedList &&
2157 SpaceBeforeCtorInitializerColon ==
2158 R.SpaceBeforeCtorInitializerColon &&
2159 SpaceBeforeInheritanceColon == R.SpaceBeforeInheritanceColon &&
2160 SpaceBeforeParens == R.SpaceBeforeParens &&
2161 SpaceBeforeRangeBasedForLoopColon ==
2162 R.SpaceBeforeRangeBasedForLoopColon &&
2163 SpaceInEmptyBlock == R.SpaceInEmptyBlock &&
2164 SpaceInEmptyParentheses == R.SpaceInEmptyParentheses &&
2165 SpacesBeforeTrailingComments == R.SpacesBeforeTrailingComments &&
2166 SpacesInAngles == R.SpacesInAngles &&
2167 SpacesInConditionalStatement == R.SpacesInConditionalStatement &&
2168 SpacesInContainerLiterals == R.SpacesInContainerLiterals &&
2169 SpacesInCStyleCastParentheses == R.SpacesInCStyleCastParentheses &&
2170 SpacesInParentheses == R.SpacesInParentheses &&
2171 SpacesInSquareBrackets == R.SpacesInSquareBrackets &&
2172 SpaceBeforeSquareBrackets == R.SpaceBeforeSquareBrackets &&
2173 Standard == R.Standard && TabWidth == R.TabWidth &&
2174 StatementMacros == R.StatementMacros && UseTab == R.UseTab &&
2175 UseCRLF == R.UseCRLF && TypenameMacros == R.TypenameMacros;
2176 }
2177
2178 llvm::Optional<FormatStyle> GetLanguageStyle(LanguageKind Language) const;
2179
2180 // Stores per-language styles. A FormatStyle instance inside has an empty
2181 // StyleSet. A FormatStyle instance returned by the Get method has its
2182 // StyleSet set to a copy of the originating StyleSet, effectively keeping the
2183 // internal representation of that StyleSet alive.
2184 //
2185 // The memory management and ownership reminds of a birds nest: chicks
2186 // leaving the nest take photos of the nest with them.
2187 struct FormatStyleSet {
2188 typedef std::map<FormatStyle::LanguageKind, FormatStyle> MapType;
2189
2190 llvm::Optional<FormatStyle> Get(FormatStyle::LanguageKind Language) const;
2191
2192 // Adds \p Style to this FormatStyleSet. Style must not have an associated
2193 // FormatStyleSet.
2194 // Style.Language should be different than LK_None. If this FormatStyleSet
2195 // already contains an entry for Style.Language, that gets replaced with the
2196 // passed Style.
2197 void Add(FormatStyle Style);
2198
2199 // Clears this FormatStyleSet.
2200 void Clear();
2201
2202 private:
2203 std::shared_ptr<MapType> Styles;
2204 };
2205
2206 static FormatStyleSet BuildStyleSetFromConfiguration(
2207 const FormatStyle &MainStyle,
2208 const std::vector<FormatStyle> &ConfigurationStyles);
2209
2210 private:
2211 FormatStyleSet StyleSet;
2212
2213 friend std::error_code parseConfiguration(StringRef Text, FormatStyle *Style);
2214 };
2215
2216 /// Returns a format style complying with the LLVM coding standards:
2217 /// http://llvm.org/docs/CodingStandards.html.
2218 FormatStyle getLLVMStyle(
2219 FormatStyle::LanguageKind Language = FormatStyle::LanguageKind::LK_Cpp);
2220
2221 /// Returns a format style complying with one of Google's style guides:
2222 /// http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml.
2223 /// http://google-styleguide.googlecode.com/svn/trunk/javascriptguide.xml.
2224 /// https://developers.google.com/protocol-buffers/docs/style.
2225 FormatStyle getGoogleStyle(FormatStyle::LanguageKind Language);
2226
2227 /// Returns a format style complying with Chromium's style guide:
2228 /// http://www.chromium.org/developers/coding-style.
2229 FormatStyle getChromiumStyle(FormatStyle::LanguageKind Language);
2230
2231 /// Returns a format style complying with Mozilla's style guide:
2232 /// https://developer.mozilla.org/en-US/docs/Developer_Guide/Coding_Style.
2233 FormatStyle getMozillaStyle();
2234
2235 /// Returns a format style complying with Webkit's style guide:
2236 /// http://www.webkit.org/coding/coding-style.html
2237 FormatStyle getWebKitStyle();
2238
2239 /// Returns a format style complying with GNU Coding Standards:
2240 /// http://www.gnu.org/prep/standards/standards.html
2241 FormatStyle getGNUStyle();
2242
2243 /// Returns a format style complying with Microsoft style guide:
2244 /// https://docs.microsoft.com/en-us/visualstudio/ide/editorconfig-code-style-settings-reference?view=vs-2017
2245 FormatStyle getMicrosoftStyle(FormatStyle::LanguageKind Language);
2246
2247 /// Returns style indicating formatting should be not applied at all.
2248 FormatStyle getNoStyle();
2249
2250 /// Gets a predefined style for the specified language by name.
2251 ///
2252 /// Currently supported names: LLVM, Google, Chromium, Mozilla. Names are
2253 /// compared case-insensitively.
2254 ///
2255 /// Returns ``true`` if the Style has been set.
2256 bool getPredefinedStyle(StringRef Name, FormatStyle::LanguageKind Language,
2257 FormatStyle *Style);
2258
2259 /// Parse configuration from YAML-formatted text.
2260 ///
2261 /// Style->Language is used to get the base style, if the ``BasedOnStyle``
2262 /// option is present.
2263 ///
2264 /// The FormatStyleSet of Style is reset.
2265 ///
2266 /// When ``BasedOnStyle`` is not present, options not present in the YAML
2267 /// document, are retained in \p Style.
2268 std::error_code parseConfiguration(StringRef Text, FormatStyle *Style);
2269
2270 /// Gets configuration in a YAML string.
2271 std::string configurationAsText(const FormatStyle &Style);
2272
2273 /// Returns the replacements necessary to sort all ``#include`` blocks
2274 /// that are affected by ``Ranges``.
2275 tooling::Replacements sortIncludes(const FormatStyle &Style, StringRef Code,
2276 ArrayRef<tooling::Range> Ranges,
2277 StringRef FileName,
2278 unsigned *Cursor = nullptr);
2279
2280 /// Returns the replacements corresponding to applying and formatting
2281 /// \p Replaces on success; otheriwse, return an llvm::Error carrying
2282 /// llvm::StringError.
2283 llvm::Expected<tooling::Replacements>
2284 formatReplacements(StringRef Code, const tooling::Replacements &Replaces,
2285 const FormatStyle &Style);
2286
2287 /// Returns the replacements corresponding to applying \p Replaces and
2288 /// cleaning up the code after that on success; otherwise, return an llvm::Error
2289 /// carrying llvm::StringError.
2290 /// This also supports inserting/deleting C++ #include directives:
2291 /// - If a replacement has offset UINT_MAX, length 0, and a replacement text
2292 /// that is an #include directive, this will insert the #include into the
2293 /// correct block in the \p Code.
2294 /// - If a replacement has offset UINT_MAX, length 1, and a replacement text
2295 /// that is the name of the header to be removed, the header will be removed
2296 /// from \p Code if it exists.
2297 /// The include manipulation is done via `tooling::HeaderInclude`, see its
2298 /// documentation for more details on how include insertion points are found and
2299 /// what edits are produced.
2300 llvm::Expected<tooling::Replacements>
2301 cleanupAroundReplacements(StringRef Code, const tooling::Replacements &Replaces,
2302 const FormatStyle &Style);
2303
2304 /// Represents the status of a formatting attempt.
2305 struct FormattingAttemptStatus {
2306 /// A value of ``false`` means that any of the affected ranges were not
2307 /// formatted due to a non-recoverable syntax error.
2308 bool FormatComplete = true;
2309
2310 /// If ``FormatComplete`` is false, ``Line`` records a one-based
2311 /// original line number at which a syntax error might have occurred. This is
2312 /// based on a best-effort analysis and could be imprecise.
2313 unsigned Line = 0;
2314 };
2315
2316 /// Reformats the given \p Ranges in \p Code.
2317 ///
2318 /// Each range is extended on either end to its next bigger logic unit, i.e.
2319 /// everything that might influence its formatting or might be influenced by its
2320 /// formatting.
2321 ///
2322 /// Returns the ``Replacements`` necessary to make all \p Ranges comply with
2323 /// \p Style.
2324 ///
2325 /// If ``Status`` is non-null, its value will be populated with the status of
2326 /// this formatting attempt. See \c FormattingAttemptStatus.
2327 tooling::Replacements reformat(const FormatStyle &Style, StringRef Code,
2328 ArrayRef<tooling::Range> Ranges,
2329 StringRef FileName = "<stdin>",
2330 FormattingAttemptStatus *Status = nullptr);
2331
2332 /// Same as above, except if ``IncompleteFormat`` is non-null, its value
2333 /// will be set to true if any of the affected ranges were not formatted due to
2334 /// a non-recoverable syntax error.
2335 tooling::Replacements reformat(const FormatStyle &Style, StringRef Code,
2336 ArrayRef<tooling::Range> Ranges,
2337 StringRef FileName, bool *IncompleteFormat);
2338
2339 /// Clean up any erroneous/redundant code in the given \p Ranges in \p
2340 /// Code.
2341 ///
2342 /// Returns the ``Replacements`` that clean up all \p Ranges in \p Code.
2343 tooling::Replacements cleanup(const FormatStyle &Style, StringRef Code,
2344 ArrayRef<tooling::Range> Ranges,
2345 StringRef FileName = "<stdin>");
2346
2347 /// Fix namespace end comments in the given \p Ranges in \p Code.
2348 ///
2349 /// Returns the ``Replacements`` that fix the namespace comments in all
2350 /// \p Ranges in \p Code.
2351 tooling::Replacements fixNamespaceEndComments(const FormatStyle &Style,
2352 StringRef Code,
2353 ArrayRef<tooling::Range> Ranges,
2354 StringRef FileName = "<stdin>");
2355
2356 /// Sort consecutive using declarations in the given \p Ranges in
2357 /// \p Code.
2358 ///
2359 /// Returns the ``Replacements`` that sort the using declarations in all
2360 /// \p Ranges in \p Code.
2361 tooling::Replacements sortUsingDeclarations(const FormatStyle &Style,
2362 StringRef Code,
2363 ArrayRef<tooling::Range> Ranges,
2364 StringRef FileName = "<stdin>");
2365
2366 /// Returns the ``LangOpts`` that the formatter expects you to set.
2367 ///
2368 /// \param Style determines specific settings for lexing mode.
2369 LangOptions getFormattingLangOpts(const FormatStyle &Style = getLLVMStyle());
2370
2371 /// Description to be used for help text for a ``llvm::cl`` option for
2372 /// specifying format style. The description is closely related to the operation
2373 /// of ``getStyle()``.
2374 extern const char *StyleOptionHelpDescription;
2375
2376 /// The suggested format style to use by default. This allows tools using
2377 /// `getStyle` to have a consistent default style.
2378 /// Different builds can modify the value to the preferred styles.
2379 extern const char *DefaultFormatStyle;
2380
2381 /// The suggested predefined style to use as the fallback style in `getStyle`.
2382 /// Different builds can modify the value to the preferred styles.
2383 extern const char *DefaultFallbackStyle;
2384
2385 /// Construct a FormatStyle based on ``StyleName``.
2386 ///
2387 /// ``StyleName`` can take several forms:
2388 /// * "{<key>: <value>, ...}" - Set specic style parameters.
2389 /// * "<style name>" - One of the style names supported by
2390 /// getPredefinedStyle().
2391 /// * "file" - Load style configuration from a file called ``.clang-format``
2392 /// located in one of the parent directories of ``FileName`` or the current
2393 /// directory if ``FileName`` is empty.
2394 ///
2395 /// \param[in] StyleName Style name to interpret according to the description
2396 /// above.
2397 /// \param[in] FileName Path to start search for .clang-format if ``StyleName``
2398 /// == "file".
2399 /// \param[in] FallbackStyle The name of a predefined style used to fallback to
2400 /// in case \p StyleName is "file" and no file can be found.
2401 /// \param[in] Code The actual code to be formatted. Used to determine the
2402 /// language if the filename isn't sufficient.
2403 /// \param[in] FS The underlying file system, in which the file resides. By
2404 /// default, the file system is the real file system.
2405 ///
2406 /// \returns FormatStyle as specified by ``StyleName``. If ``StyleName`` is
2407 /// "file" and no file is found, returns ``FallbackStyle``. If no style could be
2408 /// determined, returns an Error.
2409 llvm::Expected<FormatStyle> getStyle(StringRef StyleName, StringRef FileName,
2410 StringRef FallbackStyle,
2411 StringRef Code = "",
2412 llvm::vfs::FileSystem *FS = nullptr);
2413
2414 // Guesses the language from the ``FileName`` and ``Code`` to be formatted.
2415 // Defaults to FormatStyle::LK_Cpp.
2416 FormatStyle::LanguageKind guessLanguage(StringRef FileName, StringRef Code);
2417
2418 // Returns a string representation of ``Language``.
getLanguageName(FormatStyle::LanguageKind Language)2419 inline StringRef getLanguageName(FormatStyle::LanguageKind Language) {
2420 switch (Language) {
2421 case FormatStyle::LK_Cpp:
2422 return "C++";
2423 case FormatStyle::LK_CSharp:
2424 return "CSharp";
2425 case FormatStyle::LK_ObjC:
2426 return "Objective-C";
2427 case FormatStyle::LK_Java:
2428 return "Java";
2429 case FormatStyle::LK_JavaScript:
2430 return "JavaScript";
2431 case FormatStyle::LK_Proto:
2432 return "Proto";
2433 case FormatStyle::LK_TableGen:
2434 return "TableGen";
2435 case FormatStyle::LK_TextProto:
2436 return "TextProto";
2437 default:
2438 return "Unknown";
2439 }
2440 }
2441
2442 } // end namespace format
2443 } // end namespace clang
2444
2445 namespace std {
2446 template <>
2447 struct is_error_code_enum<clang::format::ParseError> : std::true_type {};
2448 } // namespace std
2449
2450 #endif // LLVM_CLANG_FORMAT_FORMAT_H
2451