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