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