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