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