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