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