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