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