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  /// Options for indenting preprocessor directives.
1269  enum PPDirectiveIndentStyle {
1270  /// Does not indent any directives.
1271  /// \code
1272  /// #if FOO
1273  /// #if BAR
1274  /// #include <foo>
1275  /// #endif
1276  /// #endif
1277  /// \endcode
1278  PPDIS_None,
1279  /// Indents directives after the hash.
1280  /// \code
1281  /// #if FOO
1282  /// # if BAR
1283  /// # include <foo>
1284  /// # endif
1285  /// #endif
1286  /// \endcode
1287  PPDIS_AfterHash,
1288  /// Indents directives before the hash.
1289  /// \code
1290  /// #if FOO
1291  /// #if BAR
1292  /// #include <foo>
1293  /// #endif
1294  /// #endif
1295  /// \endcode
1296  PPDIS_BeforeHash
1297  };
1298 
1299  /// The preprocessor directive indenting style to use.
1300  PPDirectiveIndentStyle IndentPPDirectives;
1301 
1302  /// The number of columns to use for indentation.
1303  /// \code
1304  /// IndentWidth: 3
1305  ///
1306  /// void f() {
1307  /// someFunction();
1308  /// if (true, false) {
1309  /// f();
1310  /// }
1311  /// }
1312  /// \endcode
1313  unsigned IndentWidth;
1314 
1315  /// Indent if a function definition or declaration is wrapped after the
1316  /// type.
1317  /// \code
1318  /// true:
1319  /// LoooooooooooooooooooooooooooooooooooooooongReturnType
1320  /// LoooooooooooooooooooooooooooooooongFunctionDeclaration();
1321  ///
1322  /// false:
1323  /// LoooooooooooooooooooooooooooooooooooooooongReturnType
1324  /// LoooooooooooooooooooooooooooooooongFunctionDeclaration();
1325  /// \endcode
1326  bool IndentWrappedFunctionNames;
1327 
1328  /// A vector of prefixes ordered by the desired groups for Java imports.
1329  ///
1330  /// Each group is separated by a newline. Static imports will also follow the
1331  /// same grouping convention above all non-static imports. One group's prefix
1332  /// can be a subset of another - the longest prefix is always matched. Within
1333  /// a group, the imports are ordered lexicographically.
1334  ///
1335  /// In the .clang-format configuration file, this can be configured like
1336  /// in the following yaml example. This will result in imports being
1337  /// formatted as in the Java example below.
1338  /// \code{.yaml}
1339  /// JavaImportGroups: ['com.example', 'com', 'org']
1340  /// \endcode
1341  ///
1342  /// \code{.java}
1343  /// import static com.example.function1;
1344  ///
1345  /// import static com.test.function2;
1346  ///
1347  /// import static org.example.function3;
1348  ///
1349  /// import com.example.ClassA;
1350  /// import com.example.Test;
1351  /// import com.example.a.ClassB;
1352  ///
1353  /// import com.test.ClassC;
1354  ///
1355  /// import org.example.ClassD;
1356  /// \endcode
1357  std::vector<std::string> JavaImportGroups;
1358 
1359  /// Quotation styles for JavaScript strings. Does not affect template
1360  /// strings.
1361  enum JavaScriptQuoteStyle {
1362  /// Leave string quotes as they are.
1363  /// \code{.js}
1364  /// string1 = "foo";
1365  /// string2 = 'bar';
1366  /// \endcode
1367  JSQS_Leave,
1368  /// Always use single quotes.
1369  /// \code{.js}
1370  /// string1 = 'foo';
1371  /// string2 = 'bar';
1372  /// \endcode
1373  JSQS_Single,
1374  /// Always use double quotes.
1375  /// \code{.js}
1376  /// string1 = "foo";
1377  /// string2 = "bar";
1378  /// \endcode
1379  JSQS_Double
1380  };
1381 
1382  /// The JavaScriptQuoteStyle to use for JavaScript strings.
1383  JavaScriptQuoteStyle JavaScriptQuotes;
1384 
1385  /// Whether to wrap JavaScript import/export statements.
1386  /// \code{.js}
1387  /// true:
1388  /// import {
1389  /// VeryLongImportsAreAnnoying,
1390  /// VeryLongImportsAreAnnoying,
1391  /// VeryLongImportsAreAnnoying,
1392  /// } from 'some/module.js'
1393  ///
1394  /// false:
1395  /// import {VeryLongImportsAreAnnoying, VeryLongImportsAreAnnoying, VeryLongImportsAreAnnoying,} from "some/module.js"
1396  /// \endcode
1397  bool JavaScriptWrapImports;
1398 
1399  /// If true, the empty line at the start of blocks is kept.
1400  /// \code
1401  /// true: false:
1402  /// if (foo) { vs. if (foo) {
1403  /// bar();
1404  /// bar(); }
1405  /// }
1406  /// \endcode
1407  bool KeepEmptyLinesAtTheStartOfBlocks;
1408 
1409  /// Supported languages.
1410  ///
1411  /// When stored in a configuration file, specifies the language, that the
1412  /// configuration targets. When passed to the ``reformat()`` function, enables
1413  /// syntax features specific to the language.
1414  enum LanguageKind {
1415  /// Do not use.
1416  LK_None,
1417  /// Should be used for C, C++.
1418  LK_Cpp,
1419  /// Should be used for C#.
1420  LK_CSharp,
1421  /// Should be used for Java.
1422  LK_Java,
1423  /// Should be used for JavaScript.
1424  LK_JavaScript,
1425  /// Should be used for Objective-C, Objective-C++.
1426  LK_ObjC,
1427  /// Should be used for Protocol Buffers
1428  /// (https://developers.google.com/protocol-buffers/).
1429  LK_Proto,
1430  /// Should be used for TableGen code.
1431  LK_TableGen,
1432  /// Should be used for Protocol Buffer messages in text format
1433  /// (https://developers.google.com/protocol-buffers/).
1434  LK_TextProto
1435  };
1436  bool isCpp() const { return Language == LK_Cpp || Language == LK_ObjC; }
1437  bool isCSharp() const { return Language == LK_CSharp; }
1438 
1439  /// Language, this format style is targeted at.
1440  LanguageKind Language;
1441 
1442  /// A regular expression matching macros that start a block.
1443  /// \code
1444  /// # With:
1445  /// MacroBlockBegin: "^NS_MAP_BEGIN|\
1446  /// NS_TABLE_HEAD$"
1447  /// MacroBlockEnd: "^\
1448  /// NS_MAP_END|\
1449  /// NS_TABLE_.*_END$"
1450  ///
1451  /// NS_MAP_BEGIN
1452  /// foo();
1453  /// NS_MAP_END
1454  ///
1455  /// NS_TABLE_HEAD
1456  /// bar();
1457  /// NS_TABLE_FOO_END
1458  ///
1459  /// # Without:
1460  /// NS_MAP_BEGIN
1461  /// foo();
1462  /// NS_MAP_END
1463  ///
1464  /// NS_TABLE_HEAD
1465  /// bar();
1466  /// NS_TABLE_FOO_END
1467  /// \endcode
1468  std::string MacroBlockBegin;
1469 
1470  /// A regular expression matching macros that end a block.
1471  std::string MacroBlockEnd;
1472 
1473  /// The maximum number of consecutive empty lines to keep.
1474  /// \code
1475  /// MaxEmptyLinesToKeep: 1 vs. MaxEmptyLinesToKeep: 0
1476  /// int f() { int f() {
1477  /// int = 1; int i = 1;
1478  /// i = foo();
1479  /// i = foo(); return i;
1480  /// }
1481  /// return i;
1482  /// }
1483  /// \endcode
1484  unsigned MaxEmptyLinesToKeep;
1485 
1486  /// Different ways to indent namespace contents.
1487  enum NamespaceIndentationKind {
1488  /// Don't indent in namespaces.
1489  /// \code
1490  /// namespace out {
1491  /// int i;
1492  /// namespace in {
1493  /// int i;
1494  /// }
1495  /// }
1496  /// \endcode
1497  NI_None,
1498  /// Indent only in inner namespaces (nested in other namespaces).
1499  /// \code
1500  /// namespace out {
1501  /// int i;
1502  /// namespace in {
1503  /// int i;
1504  /// }
1505  /// }
1506  /// \endcode
1507  NI_Inner,
1508  /// Indent in all namespaces.
1509  /// \code
1510  /// namespace out {
1511  /// int i;
1512  /// namespace in {
1513  /// int i;
1514  /// }
1515  /// }
1516  /// \endcode
1517  NI_All
1518  };
1519 
1520  /// The indentation used for namespaces.
1521  NamespaceIndentationKind NamespaceIndentation;
1522 
1523  /// Controls bin-packing Objective-C protocol conformance list
1524  /// items into as few lines as possible when they go over ``ColumnLimit``.
1525  ///
1526  /// If ``Auto`` (the default), delegates to the value in
1527  /// ``BinPackParameters``. If that is ``true``, bin-packs Objective-C
1528  /// protocol conformance list items into as few lines as possible
1529  /// whenever they go over ``ColumnLimit``.
1530  ///
1531  /// If ``Always``, always bin-packs Objective-C protocol conformance
1532  /// list items into as few lines as possible whenever they go over
1533  /// ``ColumnLimit``.
1534  ///
1535  /// If ``Never``, lays out Objective-C protocol conformance list items
1536  /// onto individual lines whenever they go over ``ColumnLimit``.
1537  ///
1538  /// \code{.objc}
1539  /// Always (or Auto, if BinPackParameters=true):
1540  /// @interface ccccccccccccc () <
1541  /// ccccccccccccc, ccccccccccccc,
1542  /// ccccccccccccc, ccccccccccccc> {
1543  /// }
1544  ///
1545  /// Never (or Auto, if BinPackParameters=false):
1546  /// @interface ddddddddddddd () <
1547  /// ddddddddddddd,
1548  /// ddddddddddddd,
1549  /// ddddddddddddd,
1550  /// ddddddddddddd> {
1551  /// }
1552  /// \endcode
1553  BinPackStyle ObjCBinPackProtocolList;
1554 
1555  /// The number of characters to use for indentation of ObjC blocks.
1556  /// \code{.objc}
1557  /// ObjCBlockIndentWidth: 4
1558  ///
1559  /// [operation setCompletionBlock:^{
1560  /// [self onOperationDone];
1561  /// }];
1562  /// \endcode
1563  unsigned ObjCBlockIndentWidth;
1564 
1565  /// Add a space after ``@property`` in Objective-C, i.e. use
1566  /// ``@property (readonly)`` instead of ``@property(readonly)``.
1567  bool ObjCSpaceAfterProperty;
1568 
1569  /// Add a space in front of an Objective-C protocol list, i.e. use
1570  /// ``Foo <Protocol>`` instead of ``Foo<Protocol>``.
1571  bool ObjCSpaceBeforeProtocolList;
1572 
1573  /// The penalty for breaking around an assignment operator.
1574  unsigned PenaltyBreakAssignment;
1575 
1576  /// The penalty for breaking a function call after ``call(``.
1577  unsigned PenaltyBreakBeforeFirstCallParameter;
1578 
1579  /// The penalty for each line break introduced inside a comment.
1580  unsigned PenaltyBreakComment;
1581 
1582  /// The penalty for breaking before the first ``<<``.
1583  unsigned PenaltyBreakFirstLessLess;
1584 
1585  /// The penalty for each line break introduced inside a string literal.
1586  unsigned PenaltyBreakString;
1587 
1588  /// The penalty for breaking after template declaration.
1589  unsigned PenaltyBreakTemplateDeclaration;
1590 
1591  /// The penalty for each character outside of the column limit.
1592  unsigned PenaltyExcessCharacter;
1593 
1594  /// Penalty for putting the return type of a function onto its own
1595  /// line.
1596  unsigned PenaltyReturnTypeOnItsOwnLine;
1597 
1598  /// The ``&`` and ``*`` alignment style.
1599  enum PointerAlignmentStyle {
1600  /// Align pointer to the left.
1601  /// \code
1602  /// int* a;
1603  /// \endcode
1604  PAS_Left,
1605  /// Align pointer to the right.
1606  /// \code
1607  /// int *a;
1608  /// \endcode
1609  PAS_Right,
1610  /// Align pointer in the middle.
1611  /// \code
1612  /// int * a;
1613  /// \endcode
1614  PAS_Middle
1615  };
1616 
1617  /// Pointer and reference alignment style.
1618  PointerAlignmentStyle PointerAlignment;
1619 
1620  /// See documentation of ``RawStringFormats``.
1621  struct RawStringFormat {
1622  /// The language of this raw string.
1623  LanguageKind Language;
1624  /// A list of raw string delimiters that match this language.
1625  std::vector<std::string> Delimiters;
1626  /// A list of enclosing function names that match this language.
1627  std::vector<std::string> EnclosingFunctions;
1628  /// The canonical delimiter for this language.
1629  std::string CanonicalDelimiter;
1630  /// The style name on which this raw string format is based on.
1631  /// If not specified, the raw string format is based on the style that this
1632  /// format is based on.
1633  std::string BasedOnStyle;
1634  bool operator==(const RawStringFormat &Other) const {
1635  return Language == Other.Language && Delimiters == Other.Delimiters &&
1636  EnclosingFunctions == Other.EnclosingFunctions &&
1637  CanonicalDelimiter == Other.CanonicalDelimiter &&
1638  BasedOnStyle == Other.BasedOnStyle;
1639  }
1640  };
1641 
1642  /// Defines hints for detecting supported languages code blocks in raw
1643  /// strings.
1644  ///
1645  /// A raw string with a matching delimiter or a matching enclosing function
1646  /// name will be reformatted assuming the specified language based on the
1647  /// style for that language defined in the .clang-format file. If no style has
1648  /// been defined in the .clang-format file for the specific language, a
1649  /// predefined style given by 'BasedOnStyle' is used. If 'BasedOnStyle' is not
1650  /// found, the formatting is based on llvm style. A matching delimiter takes
1651  /// precedence over a matching enclosing function name for determining the
1652  /// language of the raw string contents.
1653  ///
1654  /// If a canonical delimiter is specified, occurrences of other delimiters for
1655  /// the same language will be updated to the canonical if possible.
1656  ///
1657  /// There should be at most one specification per language and each delimiter
1658  /// and enclosing function should not occur in multiple specifications.
1659  ///
1660  /// To configure this in the .clang-format file, use:
1661  /// \code{.yaml}
1662  /// RawStringFormats:
1663  /// - Language: TextProto
1664  /// Delimiters:
1665  /// - 'pb'
1666  /// - 'proto'
1667  /// EnclosingFunctions:
1668  /// - 'PARSE_TEXT_PROTO'
1669  /// BasedOnStyle: google
1670  /// - Language: Cpp
1671  /// Delimiters:
1672  /// - 'cc'
1673  /// - 'cpp'
1674  /// BasedOnStyle: llvm
1675  /// CanonicalDelimiter: 'cc'
1676  /// \endcode
1677  std::vector<RawStringFormat> RawStringFormats;
1678 
1679  /// If ``true``, clang-format will attempt to re-flow comments.
1680  /// \code
1681  /// false:
1682  /// // veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongComment with plenty of information
1683  /// /* second veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongComment with plenty of information */
1684  ///
1685  /// true:
1686  /// // veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongComment with plenty of
1687  /// // information
1688  /// /* second veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongComment with plenty of
1689  /// * information */
1690  /// \endcode
1691  bool ReflowComments;
1692 
1693  /// If ``true``, clang-format will sort ``#includes``.
1694  /// \code
1695  /// false: true:
1696  /// #include "b.h" vs. #include "a.h"
1697  /// #include "a.h" #include "b.h"
1698  /// \endcode
1699  bool SortIncludes;
1700 
1701  /// If ``true``, clang-format will sort using declarations.
1702  ///
1703  /// The order of using declarations is defined as follows:
1704  /// Split the strings by "::" and discard any initial empty strings. The last
1705  /// element of each list is a non-namespace name; all others are namespace
1706  /// names. Sort the lists of names lexicographically, where the sort order of
1707  /// individual names is that all non-namespace names come before all namespace
1708  /// names, and within those groups, names are in case-insensitive
1709  /// lexicographic order.
1710  /// \code
1711  /// false: true:
1712  /// using std::cout; vs. using std::cin;
1713  /// using std::cin; using std::cout;
1714  /// \endcode
1715  bool SortUsingDeclarations;
1716 
1717  /// If ``true``, a space is inserted after C style casts.
1718  /// \code
1719  /// true: false:
1720  /// (int) i; vs. (int)i;
1721  /// \endcode
1722  bool SpaceAfterCStyleCast;
1723 
1724  /// If ``true``, a space is inserted after the logical not operator (``!``).
1725  /// \code
1726  /// true: false:
1727  /// ! someExpression(); vs. !someExpression();
1728  /// \endcode
1729  bool SpaceAfterLogicalNot;
1730 
1731  /// If \c true, a space will be inserted after the 'template' keyword.
1732  /// \code
1733  /// true: false:
1734  /// template <int> void foo(); vs. template<int> void foo();
1735  /// \endcode
1736  bool SpaceAfterTemplateKeyword;
1737 
1738  /// If ``false``, spaces will be removed before assignment operators.
1739  /// \code
1740  /// true: false:
1741  /// int a = 5; vs. int a= 5;
1742  /// a += 42; a+= 42;
1743  /// \endcode
1744  bool SpaceBeforeAssignmentOperators;
1745 
1746  /// If ``true``, a space will be inserted before a C++11 braced list
1747  /// used to initialize an object (after the preceding identifier or type).
1748  /// \code
1749  /// true: false:
1750  /// Foo foo { bar }; vs. Foo foo{ bar };
1751  /// Foo {}; Foo{};
1752  /// vector<int> { 1, 2, 3 }; vector<int>{ 1, 2, 3 };
1753  /// new int[3] { 1, 2, 3 }; new int[3]{ 1, 2, 3 };
1754  /// \endcode
1755  bool SpaceBeforeCpp11BracedList;
1756 
1757  /// If ``false``, spaces will be removed before constructor initializer
1758  /// colon.
1759  /// \code
1760  /// true: false:
1761  /// Foo::Foo() : a(a) {} Foo::Foo(): a(a) {}
1762  /// \endcode
1763  bool SpaceBeforeCtorInitializerColon;
1764 
1765  /// If ``false``, spaces will be removed before inheritance colon.
1766  /// \code
1767  /// true: false:
1768  /// class Foo : Bar {} vs. class Foo: Bar {}
1769  /// \endcode
1770  bool SpaceBeforeInheritanceColon;
1771 
1772  /// Different ways to put a space before opening parentheses.
1773  enum SpaceBeforeParensOptions {
1774  /// Never put a space before opening parentheses.
1775  /// \code
1776  /// void f() {
1777  /// if(true) {
1778  /// f();
1779  /// }
1780  /// }
1781  /// \endcode
1782  SBPO_Never,
1783  /// Put a space before opening parentheses only after control statement
1784  /// keywords (``for/if/while...``).
1785  /// \code
1786  /// void f() {
1787  /// if (true) {
1788  /// f();
1789  /// }
1790  /// }
1791  /// \endcode
1792  SBPO_ControlStatements,
1793  /// Put a space before opening parentheses only if the parentheses are not
1794  /// empty i.e. '()'
1795  /// \code
1796  /// void() {
1797  /// if (true) {
1798  /// f();
1799  /// g (x, y, z);
1800  /// }
1801  /// }
1802  /// \endcode
1803  SBPO_NonEmptyParentheses,
1804  /// Always put a space before opening parentheses, except when it's
1805  /// prohibited by the syntax rules (in function-like macro definitions) or
1806  /// when determined by other style rules (after unary operators, opening
1807  /// parentheses, etc.)
1808  /// \code
1809  /// void f () {
1810  /// if (true) {
1811  /// f ();
1812  /// }
1813  /// }
1814  /// \endcode
1815  SBPO_Always
1816  };
1817 
1818  /// Defines in which cases to put a space before opening parentheses.
1819  SpaceBeforeParensOptions SpaceBeforeParens;
1820 
1821  /// If ``false``, spaces will be removed before range-based for loop
1822  /// colon.
1823  /// \code
1824  /// true: false:
1825  /// for (auto v : values) {} vs. for(auto v: values) {}
1826  /// \endcode
1827  bool SpaceBeforeRangeBasedForLoopColon;
1828 
1829  /// If ``true``, spaces will be inserted into ``{}``.
1830  /// \code
1831  /// true: false:
1832  /// void f() { } vs. void f() {}
1833  /// while (true) { } while (true) {}
1834  /// \endcode
1835  bool SpaceInEmptyBlock;
1836 
1837  /// If ``true``, spaces may be inserted into ``()``.
1838  /// \code
1839  /// true: false:
1840  /// void f( ) { vs. void f() {
1841  /// int x[] = {foo( ), bar( )}; int x[] = {foo(), bar()};
1842  /// if (true) { if (true) {
1843  /// f( ); f();
1844  /// } }
1845  /// } }
1846  /// \endcode
1847  bool SpaceInEmptyParentheses;
1848 
1849  /// The number of spaces before trailing line comments
1850  /// (``//`` - comments).
1851  ///
1852  /// This does not affect trailing block comments (``/*`` - comments) as
1853  /// those commonly have different usage patterns and a number of special
1854  /// cases.
1855  /// \code
1856  /// SpacesBeforeTrailingComments: 3
1857  /// void f() {
1858  /// if (true) { // foo1
1859  /// f(); // bar
1860  /// } // foo
1861  /// }
1862  /// \endcode
1863  unsigned SpacesBeforeTrailingComments;
1864 
1865  /// If ``true``, spaces will be inserted after ``<`` and before ``>``
1866  /// in template argument lists.
1867  /// \code
1868  /// true: false:
1869  /// static_cast< int >(arg); vs. static_cast<int>(arg);
1870  /// std::function< void(int) > fct; std::function<void(int)> fct;
1871  /// \endcode
1872  bool SpacesInAngles;
1873 
1874  /// If ``true``, spaces are inserted inside container literals (e.g.
1875  /// ObjC and Javascript array and dict literals).
1876  /// \code{.js}
1877  /// true: false:
1878  /// var arr = [ 1, 2, 3 ]; vs. var arr = [1, 2, 3];
1879  /// f({a : 1, b : 2, c : 3}); f({a: 1, b: 2, c: 3});
1880  /// \endcode
1881  bool SpacesInContainerLiterals;
1882 
1883  /// If ``true``, spaces may be inserted into C style casts.
1884  /// \code
1885  /// true: false:
1886  /// x = ( int32 )y vs. x = (int32)y
1887  /// \endcode
1888  bool SpacesInCStyleCastParentheses;
1889 
1890  /// If ``true``, spaces will be inserted after ``(`` and before ``)``.
1891  /// \code
1892  /// true: false:
1893  /// t f( Deleted & ) & = delete; vs. t f(Deleted &) & = delete;
1894  /// \endcode
1895  bool SpacesInParentheses;
1896 
1897  /// If ``true``, spaces will be inserted after ``[`` and before ``]``.
1898  /// Lambdas or unspecified size array declarations will not be affected.
1899  /// \code
1900  /// true: false:
1901  /// int a[ 5 ]; vs. int a[5];
1902  /// std::unique_ptr<int[]> foo() {} // Won't be affected
1903  /// \endcode
1904  bool SpacesInSquareBrackets;
1905 
1906  /// Supported language standards.
1907  enum LanguageStandard {
1908  /// Use C++03-compatible syntax.
1909  LS_Cpp03,
1910  /// Use features of C++11, C++14 and C++1z (e.g. ``A<A<int>>`` instead of
1911  /// ``A<A<int> >``).
1912  LS_Cpp11,
1913  /// Automatic detection based on the input.
1914  LS_Auto
1915  };
1916 
1917  /// Format compatible with this standard, e.g. use ``A<A<int> >``
1918  /// instead of ``A<A<int>>`` for ``LS_Cpp03``.
1919  LanguageStandard Standard;
1920 
1921  /// The number of columns used for tab stops.
1922  unsigned TabWidth;
1923 
1924  /// Different ways to use tab in formatting.
1925  enum UseTabStyle {
1926  /// Never use tab.
1927  UT_Never,
1928  /// Use tabs only for indentation.
1929  UT_ForIndentation,
1930  /// Use tabs only for line continuation and indentation.
1931  UT_ForContinuationAndIndentation,
1932  /// Use tabs whenever we need to fill whitespace that spans at least from
1933  /// one tab stop to the next one.
1934  UT_Always
1935  };
1936 
1937  /// The way to use tab characters in the resulting file.
1938  UseTabStyle UseTab;
1939 
1940  bool operator==(const FormatStyle &R) const {
1941  return AccessModifierOffset == R.AccessModifierOffset &&
1942  AlignAfterOpenBracket == R.AlignAfterOpenBracket &&
1943  AlignConsecutiveAssignments == R.AlignConsecutiveAssignments &&
1944  AlignConsecutiveDeclarations == R.AlignConsecutiveDeclarations &&
1945  AlignEscapedNewlines == R.AlignEscapedNewlines &&
1946  AlignOperands == R.AlignOperands &&
1947  AlignTrailingComments == R.AlignTrailingComments &&
1948  AllowAllArgumentsOnNextLine == R.AllowAllArgumentsOnNextLine &&
1949  AllowAllConstructorInitializersOnNextLine ==
1950  R.AllowAllConstructorInitializersOnNextLine &&
1951  AllowAllParametersOfDeclarationOnNextLine ==
1952  R.AllowAllParametersOfDeclarationOnNextLine &&
1953  AllowShortBlocksOnASingleLine == R.AllowShortBlocksOnASingleLine &&
1954  AllowShortCaseLabelsOnASingleLine ==
1955  R.AllowShortCaseLabelsOnASingleLine &&
1956  AllowShortFunctionsOnASingleLine ==
1957  R.AllowShortFunctionsOnASingleLine &&
1958  AllowShortIfStatementsOnASingleLine ==
1959  R.AllowShortIfStatementsOnASingleLine &&
1960  AllowShortLambdasOnASingleLine == R.AllowShortLambdasOnASingleLine &&
1961  AllowShortLoopsOnASingleLine == R.AllowShortLoopsOnASingleLine &&
1962  AlwaysBreakAfterReturnType == R.AlwaysBreakAfterReturnType &&
1963  AlwaysBreakBeforeMultilineStrings ==
1964  R.AlwaysBreakBeforeMultilineStrings &&
1965  AlwaysBreakTemplateDeclarations ==
1966  R.AlwaysBreakTemplateDeclarations &&
1967  BinPackArguments == R.BinPackArguments &&
1968  BinPackParameters == R.BinPackParameters &&
1969  BreakBeforeBinaryOperators == R.BreakBeforeBinaryOperators &&
1970  BreakBeforeBraces == R.BreakBeforeBraces &&
1971  BreakBeforeTernaryOperators == R.BreakBeforeTernaryOperators &&
1972  BreakConstructorInitializers == R.BreakConstructorInitializers &&
1973  CompactNamespaces == R.CompactNamespaces &&
1974  BreakAfterJavaFieldAnnotations == R.BreakAfterJavaFieldAnnotations &&
1975  BreakStringLiterals == R.BreakStringLiterals &&
1976  ColumnLimit == R.ColumnLimit && CommentPragmas == R.CommentPragmas &&
1977  BreakInheritanceList == R.BreakInheritanceList &&
1978  ConstructorInitializerAllOnOneLineOrOnePerLine ==
1979  R.ConstructorInitializerAllOnOneLineOrOnePerLine &&
1980  ConstructorInitializerIndentWidth ==
1981  R.ConstructorInitializerIndentWidth &&
1982  ContinuationIndentWidth == R.ContinuationIndentWidth &&
1983  Cpp11BracedListStyle == R.Cpp11BracedListStyle &&
1984  DerivePointerAlignment == R.DerivePointerAlignment &&
1985  DisableFormat == R.DisableFormat &&
1986  ExperimentalAutoDetectBinPacking ==
1987  R.ExperimentalAutoDetectBinPacking &&
1988  FixNamespaceComments == R.FixNamespaceComments &&
1989  ForEachMacros == R.ForEachMacros &&
1990  IncludeStyle.IncludeBlocks == R.IncludeStyle.IncludeBlocks &&
1991  IncludeStyle.IncludeCategories == R.IncludeStyle.IncludeCategories &&
1992  IndentCaseLabels == R.IndentCaseLabels &&
1993  IndentPPDirectives == R.IndentPPDirectives &&
1994  IndentWidth == R.IndentWidth && Language == R.Language &&
1995  IndentWrappedFunctionNames == R.IndentWrappedFunctionNames &&
1996  JavaImportGroups == R.JavaImportGroups &&
1997  JavaScriptQuotes == R.JavaScriptQuotes &&
1998  JavaScriptWrapImports == R.JavaScriptWrapImports &&
1999  KeepEmptyLinesAtTheStartOfBlocks ==
2000  R.KeepEmptyLinesAtTheStartOfBlocks &&
2001  MacroBlockBegin == R.MacroBlockBegin &&
2002  MacroBlockEnd == R.MacroBlockEnd &&
2003  MaxEmptyLinesToKeep == R.MaxEmptyLinesToKeep &&
2004  NamespaceIndentation == R.NamespaceIndentation &&
2005  NamespaceMacros == R.NamespaceMacros &&
2006  ObjCBinPackProtocolList == R.ObjCBinPackProtocolList &&
2007  ObjCBlockIndentWidth == R.ObjCBlockIndentWidth &&
2008  ObjCSpaceAfterProperty == R.ObjCSpaceAfterProperty &&
2009  ObjCSpaceBeforeProtocolList == R.ObjCSpaceBeforeProtocolList &&
2010  PenaltyBreakAssignment == R.PenaltyBreakAssignment &&
2011  PenaltyBreakBeforeFirstCallParameter ==
2012  R.PenaltyBreakBeforeFirstCallParameter &&
2013  PenaltyBreakComment == R.PenaltyBreakComment &&
2014  PenaltyBreakFirstLessLess == R.PenaltyBreakFirstLessLess &&
2015  PenaltyBreakString == R.PenaltyBreakString &&
2016  PenaltyExcessCharacter == R.PenaltyExcessCharacter &&
2017  PenaltyReturnTypeOnItsOwnLine == R.PenaltyReturnTypeOnItsOwnLine &&
2018  PenaltyBreakTemplateDeclaration ==
2019  R.PenaltyBreakTemplateDeclaration &&
2020  PointerAlignment == R.PointerAlignment &&
2021  RawStringFormats == R.RawStringFormats &&
2022  SpaceAfterCStyleCast == R.SpaceAfterCStyleCast &&
2023  SpaceAfterLogicalNot == R.SpaceAfterLogicalNot &&
2024  SpaceAfterTemplateKeyword == R.SpaceAfterTemplateKeyword &&
2025  SpaceBeforeAssignmentOperators == R.SpaceBeforeAssignmentOperators &&
2026  SpaceBeforeCpp11BracedList == R.SpaceBeforeCpp11BracedList &&
2027  SpaceBeforeCtorInitializerColon ==
2028  R.SpaceBeforeCtorInitializerColon &&
2029  SpaceBeforeInheritanceColon == R.SpaceBeforeInheritanceColon &&
2030  SpaceBeforeParens == R.SpaceBeforeParens &&
2031  SpaceBeforeRangeBasedForLoopColon ==
2032  R.SpaceBeforeRangeBasedForLoopColon &&
2033  SpaceInEmptyBlock == R.SpaceInEmptyBlock &&
2034  SpaceInEmptyParentheses == R.SpaceInEmptyParentheses &&
2035  SpacesBeforeTrailingComments == R.SpacesBeforeTrailingComments &&
2036  SpacesInAngles == R.SpacesInAngles &&
2037  SpacesInContainerLiterals == R.SpacesInContainerLiterals &&
2038  SpacesInCStyleCastParentheses == R.SpacesInCStyleCastParentheses &&
2039  SpacesInParentheses == R.SpacesInParentheses &&
2040  SpacesInSquareBrackets == R.SpacesInSquareBrackets &&
2041  Standard == R.Standard && TabWidth == R.TabWidth &&
2042  StatementMacros == R.StatementMacros && UseTab == R.UseTab &&
2043  TypenameMacros == R.TypenameMacros;
2044  }
2045 
2046  llvm::Optional<FormatStyle> GetLanguageStyle(LanguageKind Language) const;
2047 
2048  // Stores per-language styles. A FormatStyle instance inside has an empty
2049  // StyleSet. A FormatStyle instance returned by the Get method has its
2050  // StyleSet set to a copy of the originating StyleSet, effectively keeping the
2051  // internal representation of that StyleSet alive.
2052  //
2053  // The memory management and ownership reminds of a birds nest: chicks
2054  // leaving the nest take photos of the nest with them.
2055  struct FormatStyleSet {
2056  typedef std::map<FormatStyle::LanguageKind, FormatStyle> MapType;
2057 
2058  llvm::Optional<FormatStyle> Get(FormatStyle::LanguageKind Language) const;
2059 
2060  // Adds \p Style to this FormatStyleSet. Style must not have an associated
2061  // FormatStyleSet.
2062  // Style.Language should be different than LK_None. If this FormatStyleSet
2063  // already contains an entry for Style.Language, that gets replaced with the
2064  // passed Style.
2065  void Add(FormatStyle Style);
2066 
2067  // Clears this FormatStyleSet.
2068  void Clear();
2069 
2070  private:
2071  std::shared_ptr<MapType> Styles;
2072  };
2073 
2074  static FormatStyleSet BuildStyleSetFromConfiguration(
2075  const FormatStyle &MainStyle,
2076  const std::vector<FormatStyle> &ConfigurationStyles);
2077 
2078 private:
2079  FormatStyleSet StyleSet;
2080 
2081  friend std::error_code parseConfiguration(StringRef Text, FormatStyle *Style);
2082 };
2083 
2084 /// Returns a format style complying with the LLVM coding standards:
2085 /// http://llvm.org/docs/CodingStandards.html.
2087  FormatStyle::LanguageKind Language = FormatStyle::LanguageKind::LK_Cpp);
2088 
2089 /// Returns a format style complying with one of Google's style guides:
2090 /// http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml.
2091 /// http://google-styleguide.googlecode.com/svn/trunk/javascriptguide.xml.
2092 /// https://developers.google.com/protocol-buffers/docs/style.
2093 FormatStyle getGoogleStyle(FormatStyle::LanguageKind Language);
2094 
2095 /// Returns a format style complying with Chromium's style guide:
2096 /// http://www.chromium.org/developers/coding-style.
2097 FormatStyle getChromiumStyle(FormatStyle::LanguageKind Language);
2098 
2099 /// Returns a format style complying with Mozilla's style guide:
2100 /// https://developer.mozilla.org/en-US/docs/Developer_Guide/Coding_Style.
2102 
2103 /// Returns a format style complying with Webkit's style guide:
2104 /// http://www.webkit.org/coding/coding-style.html
2106 
2107 /// Returns a format style complying with GNU Coding Standards:
2108 /// http://www.gnu.org/prep/standards/standards.html
2110 
2111 /// Returns style indicating formatting should be not applied at all.
2113 
2114 /// Gets a predefined style for the specified language by name.
2115 ///
2116 /// Currently supported names: LLVM, Google, Chromium, Mozilla. Names are
2117 /// compared case-insensitively.
2118 ///
2119 /// Returns ``true`` if the Style has been set.
2120 bool getPredefinedStyle(StringRef Name, FormatStyle::LanguageKind Language,
2121  FormatStyle *Style);
2122 
2123 /// Parse configuration from YAML-formatted text.
2124 ///
2125 /// Style->Language is used to get the base style, if the ``BasedOnStyle``
2126 /// option is present.
2127 ///
2128 /// The FormatStyleSet of Style is reset.
2129 ///
2130 /// When ``BasedOnStyle`` is not present, options not present in the YAML
2131 /// document, are retained in \p Style.
2132 std::error_code parseConfiguration(StringRef Text, FormatStyle *Style);
2133 
2134 /// Gets configuration in a YAML string.
2135 std::string configurationAsText(const FormatStyle &Style);
2136 
2137 /// Returns the replacements necessary to sort all ``#include`` blocks
2138 /// that are affected by ``Ranges``.
2139 tooling::Replacements sortIncludes(const FormatStyle &Style, StringRef Code,
2140  ArrayRef<tooling::Range> Ranges,
2141  StringRef FileName,
2142  unsigned *Cursor = nullptr);
2143 
2144 /// Returns the replacements corresponding to applying and formatting
2145 /// \p Replaces on success; otheriwse, return an llvm::Error carrying
2146 /// llvm::StringError.
2148 formatReplacements(StringRef Code, const tooling::Replacements &Replaces,
2149  const FormatStyle &Style);
2150 
2151 /// Returns the replacements corresponding to applying \p Replaces and
2152 /// cleaning up the code after that on success; otherwise, return an llvm::Error
2153 /// carrying llvm::StringError.
2154 /// This also supports inserting/deleting C++ #include directives:
2155 /// - If a replacement has offset UINT_MAX, length 0, and a replacement text
2156 /// that is an #include directive, this will insert the #include into the
2157 /// correct block in the \p Code.
2158 /// - If a replacement has offset UINT_MAX, length 1, and a replacement text
2159 /// that is the name of the header to be removed, the header will be removed
2160 /// from \p Code if it exists.
2161 /// The include manipulation is done via `tooling::HeaderInclude`, see its
2162 /// documentation for more details on how include insertion points are found and
2163 /// what edits are produced.
2165 cleanupAroundReplacements(StringRef Code, const tooling::Replacements &Replaces,
2166  const FormatStyle &Style);
2167 
2168 /// Represents the status of a formatting attempt.
2170  /// A value of ``false`` means that any of the affected ranges were not
2171  /// formatted due to a non-recoverable syntax error.
2172  bool FormatComplete = true;
2173 
2174  /// If ``FormatComplete`` is false, ``Line`` records a one-based
2175  /// original line number at which a syntax error might have occurred. This is
2176  /// based on a best-effort analysis and could be imprecise.
2177  unsigned Line = 0;
2178 };
2179 
2180 /// Reformats the given \p Ranges in \p Code.
2181 ///
2182 /// Each range is extended on either end to its next bigger logic unit, i.e.
2183 /// everything that might influence its formatting or might be influenced by its
2184 /// formatting.
2185 ///
2186 /// Returns the ``Replacements`` necessary to make all \p Ranges comply with
2187 /// \p Style.
2188 ///
2189 /// If ``Status`` is non-null, its value will be populated with the status of
2190 /// this formatting attempt. See \c FormattingAttemptStatus.
2191 tooling::Replacements reformat(const FormatStyle &Style, StringRef Code,
2192  ArrayRef<tooling::Range> Ranges,
2193  StringRef FileName = "<stdin>",
2194  FormattingAttemptStatus *Status = nullptr);
2195 
2196 /// Same as above, except if ``IncompleteFormat`` is non-null, its value
2197 /// will be set to true if any of the affected ranges were not formatted due to
2198 /// a non-recoverable syntax error.
2199 tooling::Replacements reformat(const FormatStyle &Style, StringRef Code,
2200  ArrayRef<tooling::Range> Ranges,
2201  StringRef FileName,
2202  bool *IncompleteFormat);
2203 
2204 /// Clean up any erroneous/redundant code in the given \p Ranges in \p
2205 /// Code.
2206 ///
2207 /// Returns the ``Replacements`` that clean up all \p Ranges in \p Code.
2208 tooling::Replacements cleanup(const FormatStyle &Style, StringRef Code,
2209  ArrayRef<tooling::Range> Ranges,
2210  StringRef FileName = "<stdin>");
2211 
2212 /// Fix namespace end comments in the given \p Ranges in \p Code.
2213 ///
2214 /// Returns the ``Replacements`` that fix the namespace comments in all
2215 /// \p Ranges in \p Code.
2217  StringRef Code,
2218  ArrayRef<tooling::Range> Ranges,
2219  StringRef FileName = "<stdin>");
2220 
2221 /// Sort consecutive using declarations in the given \p Ranges in
2222 /// \p Code.
2223 ///
2224 /// Returns the ``Replacements`` that sort the using declarations in all
2225 /// \p Ranges in \p Code.
2227  StringRef Code,
2228  ArrayRef<tooling::Range> Ranges,
2229  StringRef FileName = "<stdin>");
2230 
2231 /// Returns the ``LangOpts`` that the formatter expects you to set.
2232 ///
2233 /// \param Style determines specific settings for lexing mode.
2235 
2236 /// Description to be used for help text for a ``llvm::cl`` option for
2237 /// specifying format style. The description is closely related to the operation
2238 /// of ``getStyle()``.
2239 extern const char *StyleOptionHelpDescription;
2240 
2241 /// The suggested format style to use by default. This allows tools using
2242 /// `getStyle` to have a consistent default style.
2243 /// Different builds can modify the value to the preferred styles.
2244 extern const char *DefaultFormatStyle;
2245 
2246 /// The suggested predefined style to use as the fallback style in `getStyle`.
2247 /// Different builds can modify the value to the preferred styles.
2248 extern const char *DefaultFallbackStyle;
2249 
2250 /// Construct a FormatStyle based on ``StyleName``.
2251 ///
2252 /// ``StyleName`` can take several forms:
2253 /// * "{<key>: <value>, ...}" - Set specic style parameters.
2254 /// * "<style name>" - One of the style names supported by
2255 /// getPredefinedStyle().
2256 /// * "file" - Load style configuration from a file called ``.clang-format``
2257 /// located in one of the parent directories of ``FileName`` or the current
2258 /// directory if ``FileName`` is empty.
2259 ///
2260 /// \param[in] StyleName Style name to interpret according to the description
2261 /// above.
2262 /// \param[in] FileName Path to start search for .clang-format if ``StyleName``
2263 /// == "file".
2264 /// \param[in] FallbackStyle The name of a predefined style used to fallback to
2265 /// in case \p StyleName is "file" and no file can be found.
2266 /// \param[in] Code The actual code to be formatted. Used to determine the
2267 /// language if the filename isn't sufficient.
2268 /// \param[in] FS The underlying file system, in which the file resides. By
2269 /// default, the file system is the real file system.
2270 ///
2271 /// \returns FormatStyle as specified by ``StyleName``. If ``StyleName`` is
2272 /// "file" and no file is found, returns ``FallbackStyle``. If no style could be
2273 /// determined, returns an Error.
2274 llvm::Expected<FormatStyle> getStyle(StringRef StyleName, StringRef FileName,
2275  StringRef FallbackStyle,
2276  StringRef Code = "",
2277  llvm::vfs::FileSystem *FS = nullptr);
2278 
2279 // Guesses the language from the ``FileName`` and ``Code`` to be formatted.
2280 // Defaults to FormatStyle::LK_Cpp.
2281 FormatStyle::LanguageKind guessLanguage(StringRef FileName, StringRef Code);
2282 
2283 // Returns a string representation of ``Language``.
2284 inline StringRef getLanguageName(FormatStyle::LanguageKind Language) {
2285  switch (Language) {
2286  case FormatStyle::LK_Cpp:
2287  return "C++";
2288  case FormatStyle::LK_CSharp:
2289  return "CSharp";
2290  case FormatStyle::LK_ObjC:
2291  return "Objective-C";
2292  case FormatStyle::LK_Java:
2293  return "Java";
2294  case FormatStyle::LK_JavaScript:
2295  return "JavaScript";
2296  case FormatStyle::LK_Proto:
2297  return "Proto";
2298  case FormatStyle::LK_TableGen:
2299  return "TableGen";
2300  case FormatStyle::LK_TextProto:
2301  return "TextProto";
2302  default:
2303  return "Unknown";
2304  }
2305 }
2306 
2307 } // end namespace format
2308 } // end namespace clang
2309 
2310 namespace std {
2311 template <>
2312 struct is_error_code_enum<clang::format::ParseError> : std::true_type {};
2313 }
2314 
2315 #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:2352
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:2099
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:2343
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:950
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:592
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:2362
FormatStyle getWebKitStyle()
Returns a format style complying with Webkit&#39;s style guide: http://www.webkit.org/coding/coding-style...
Definition: Format.cpp:976
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:672
EscapedNewlineAlignmentStyle AlignEscapedNewlines
Options for aligning backslashes in escaped newlines.
Definition: Format.h:149
Definition: Format.h:2310
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:2433
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:911
FormatStyle getGNUStyle()
Returns a format style complying with GNU Coding Standards: http://www.gnu.org/prep/standards/standar...
Definition: Format.cpp:999
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:2139
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:2371
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:2380
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:786
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:2453
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:2249
StringRef getLanguageName(FormatStyle::LanguageKind Language)
Definition: Format.h:2284
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:2451
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:1127
const char * StyleOptionHelpDescription
Description to be used for help text for a llvm::cl option for specifying format style.
Definition: Format.cpp:2400
Represents the status of a formatting attempt.
Definition: Format.h:2169
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:1047
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:1039
Align parameters on the open bracket, e.g.
Definition: Format.h:60
const std::error_category & getParseCategory()
Definition: Format.cpp:588
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:2455
bool AlignTrailingComments
If true, aligns trailing comments.
Definition: Format.h:168
StringRef Text
Definition: Format.cpp:1727
std::error_code parseConfiguration(StringRef Text, FormatStyle *Style)
Parse configuration from YAML-formatted text.
Definition: Format.cpp:1073
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