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 {
181  /// void f() { foo(); }
182  /// };
183  /// \endcode
185  /// \brief Merge all functions fitting on a single line.
186  /// \code
187  /// class {
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.
709 
710  /// \brief Allow breaking string literals when formatting.
712 
713  /// \brief The column limit.
714  ///
715  /// A column limit of ``0`` means that there is no column limit. In this case,
716  /// clang-format will respect the input's line breaking decisions within
717  /// statements unless they contradict other rules.
718  unsigned ColumnLimit;
719 
720  /// \brief A regular expression that describes comments with special meaning,
721  /// which should not be split into lines or otherwise changed.
722  /// \code
723  /// CommentPragmas: '^ FOOBAR pragma:'
724  /// // Will leave the following line unaffected
725  /// #include <vector> // FOOBAR pragma: keep
726  /// \endcode
727  std::string CommentPragmas;
728 
729  /// \brief If ``true``, in the class inheritance expression clang-format will
730  /// break before ``:`` and ``,`` if there is multiple inheritance.
731  /// \code
732  /// true: false:
733  /// class MyClass vs. class MyClass : public X, public Y {
734  /// : public X };
735  /// , public Y {
736  /// };
737  /// \endcode
739 
740  /// \brief If the constructor initializers don't fit on a line, put each
741  /// initializer on its own line.
742  /// \code
743  /// true:
744  /// SomeClass::Constructor()
745  /// : aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa) {
746  /// return 0;
747  /// }
748  ///
749  /// false:
750  /// SomeClass::Constructor()
751  /// : aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaa),
752  /// aaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa) {
753  /// return 0;
754  /// }
755  /// \endcode
757 
758  /// \brief The number of characters to use for indentation of constructor
759  /// initializer lists.
761 
762  /// \brief Indent width for line continuations.
764 
765  /// \brief If ``true``, format braced lists as best suited for C++11 braced
766  /// lists.
767  ///
768  /// Important differences:
769  /// - No spaces inside the braced list.
770  /// - No line break before the closing brace.
771  /// - Indentation with the continuation indent, not with the block indent.
772  ///
773  /// Fundamentally, C++11 braced lists are formatted exactly like function
774  /// calls would be formatted in their place. If the braced list follows a name
775  /// (e.g. a type or variable name), clang-format formats as if the ``{}`` were
776  /// the parentheses of a function call with that name. If there is no name,
777  /// a zero-length name is assumed.
779 
780  /// \brief If ``true``, analyze the formatted file for the most common
781  /// alignment of ``&`` and ``*``. ``PointerAlignment`` is then used only as
782  /// fallback.
784 
785  /// \brief Disables formatting completely.
787 
788  /// \brief If ``true``, clang-format detects whether function calls and
789  /// definitions are formatted with one parameter per line.
790  ///
791  /// Each call can be bin-packed, one-per-line or inconclusive. If it is
792  /// inconclusive, e.g. completely on one line, but a decision needs to be
793  /// made, clang-format analyzes whether there are other bin-packed cases in
794  /// the input file and act accordingly.
795  ///
796  /// NOTE: This is an experimental flag, that might go away or be renamed. Do
797  /// not use this in config files, etc. Use at your own risk.
799 
800  /// \brief If ``true``, clang-format adds missing namespace end comments and
801  /// fixes invalid existing ones.
802  /// \code
803  /// true: false:
804  /// namespace a { vs. namespace a {
805  /// foo(); foo();
806  /// } // namespace a; }
807  /// \endcode
809 
810  /// \brief A vector of macros that should be interpreted as foreach loops
811  /// instead of as function calls.
812  ///
813  /// These are expected to be macros of the form:
814  /// \code
815  /// FOREACH(<variable-declaration>, ...)
816  /// <loop-body>
817  /// \endcode
818  ///
819  /// In the .clang-format configuration file, this can be configured like:
820  /// \code{.yaml}
821  /// ForEachMacros: ['RANGES_FOR', 'FOREACH']
822  /// \endcode
823  ///
824  /// For example: BOOST_FOREACH.
825  std::vector<std::string> ForEachMacros;
826 
827  /// \brief See documentation of ``IncludeCategories``.
829  /// \brief The regular expression that this category matches.
830  std::string Regex;
831  /// \brief The priority to assign to this category.
832  int Priority;
833  bool operator==(const IncludeCategory &Other) const {
834  return Regex == Other.Regex && Priority == Other.Priority;
835  }
836  };
837 
838  /// \brief Regular expressions denoting the different ``#include`` categories
839  /// used for ordering ``#includes``.
840  ///
841  /// These regular expressions are matched against the filename of an include
842  /// (including the <> or "") in order. The value belonging to the first
843  /// matching regular expression is assigned and ``#includes`` are sorted first
844  /// according to increasing category number and then alphabetically within
845  /// each category.
846  ///
847  /// If none of the regular expressions match, INT_MAX is assigned as
848  /// category. The main header for a source file automatically gets category 0.
849  /// so that it is generally kept at the beginning of the ``#includes``
850  /// (http://llvm.org/docs/CodingStandards.html#include-style). However, you
851  /// can also assign negative priorities if you have certain headers that
852  /// always need to be first.
853  ///
854  /// To configure this in the .clang-format file, use:
855  /// \code{.yaml}
856  /// IncludeCategories:
857  /// - Regex: '^"(llvm|llvm-c|clang|clang-c)/'
858  /// Priority: 2
859  /// - Regex: '^(<|"(gtest|isl|json)/)'
860  /// Priority: 3
861  /// - Regex: '.*'
862  /// Priority: 1
863  /// \endcode
864  std::vector<IncludeCategory> IncludeCategories;
865 
866  /// \brief Specify a regular expression of suffixes that are allowed in the
867  /// file-to-main-include mapping.
868  ///
869  /// When guessing whether a #include is the "main" include (to assign
870  /// category 0, see above), use this regex of allowed suffixes to the header
871  /// stem. A partial match is done, so that:
872  /// - "" means "arbitrary suffix"
873  /// - "$" means "no suffix"
874  ///
875  /// For example, if configured to "(_test)?$", then a header a.h would be seen
876  /// as the "main" include in both a.cc and a_test.cc.
877  std::string IncludeIsMainRegex;
878 
879  /// \brief Indent case labels one level from the switch statement.
880  ///
881  /// When ``false``, use the same indentation level as for the switch statement.
882  /// Switch statement body is always indented one level more than case labels.
884 
885  /// \brief The number of columns to use for indentation.
886  /// \code
887  /// IndentWidth: 3
888  /// void f() {
889  /// someFunction();
890  /// if (true, false) {
891  /// f();
892  /// }
893  /// }
894  /// \endcode
895  unsigned IndentWidth;
896 
897  /// \brief Indent if a function definition or declaration is wrapped after the
898  /// type.
900 
901  /// \brief Quotation styles for JavaScript strings. Does not affect template
902  /// strings.
904  /// Leave string quotes as they are.
905  /// \code{.js}
906  /// string1 = "foo";
907  /// string2 = 'bar';
908  /// \endcode
910  /// Always use single quotes.
911  /// \code{.js}
912  /// string1 = 'foo';
913  /// string2 = 'bar';
914  /// \endcode
916  /// Always use double quotes.
917  /// \code{.js}
918  /// string1 = "foo";
919  /// string2 = "bar";
920  /// \endcode
921  JSQS_Double
922  };
923 
924  /// \brief The JavaScriptQuoteStyle to use for JavaScript strings.
926 
927  /// \brief Whether to wrap JavaScript import/export statements.
928  /// \code{.js}
929  /// true:
930  /// import {
931  /// VeryLongImportsAreAnnoying,
932  /// VeryLongImportsAreAnnoying,
933  /// VeryLongImportsAreAnnoying,
934  /// } from 'some/module.js'
935  ///
936  /// false:
937  /// import {VeryLongImportsAreAnnoying, VeryLongImportsAreAnnoying, VeryLongImportsAreAnnoying,} from "some/module.js"
938  /// \endcode
940 
941  /// \brief If true, empty lines at the start of blocks are kept.
943 
944  /// \brief Supported languages.
945  ///
946  /// When stored in a configuration file, specifies the language, that the
947  /// configuration targets. When passed to the ``reformat()`` function, enables
948  /// syntax features specific to the language.
950  /// Do not use.
952  /// Should be used for C, C++.
954  /// Should be used for Java.
956  /// Should be used for JavaScript.
958  /// Should be used for Objective-C, Objective-C++.
960  /// Should be used for Protocol Buffers
961  /// (https://developers.google.com/protocol-buffers/).
963  /// Should be used for TableGen code.
964  LK_TableGen
965  };
966  bool IsCpp() const { return Language == LK_Cpp || Language == LK_ObjC; }
967 
968  /// \brief Language, this format style is targeted at.
970 
971  /// \brief A regular expression matching macros that start a block.
972  /// \code
973  /// # With:
974  /// MacroBlockBegin: "^NS_MAP_BEGIN|\
975  /// NS_TABLE_HEAD$"
976  /// MacroBlockEnd: "^\
977  /// NS_MAP_END|\
978  /// NS_TABLE_.*_END$"
979  ///
980  /// NS_MAP_BEGIN
981  /// foo();
982  /// NS_MAP_END
983  ///
984  /// NS_TABLE_HEAD
985  /// bar();
986  /// NS_TABLE_FOO_END
987  ///
988  /// # Without:
989  /// NS_MAP_BEGIN
990  /// foo();
991  /// NS_MAP_END
992  ///
993  /// NS_TABLE_HEAD
994  /// bar();
995  /// NS_TABLE_FOO_END
996  /// \endcode
997  std::string MacroBlockBegin;
998 
999  /// \brief A regular expression matching macros that end a block.
1000  std::string MacroBlockEnd;
1001 
1002  /// \brief The maximum number of consecutive empty lines to keep.
1003  /// \code
1004  /// MaxEmptyLinesToKeep: 1 vs. MaxEmptyLinesToKeep: 0
1005  /// int f() { int f() {
1006  /// int = 1; int i = 1;
1007  /// i = foo();
1008  /// i = foo(); return i;
1009  /// }
1010  /// return i;
1011  /// }
1012  /// \endcode
1014 
1015  /// \brief Different ways to indent namespace contents.
1017  /// Don't indent in namespaces.
1018  /// \code
1019  /// namespace out {
1020  /// int i;
1021  /// namespace in {
1022  /// int i;
1023  /// }
1024  /// }
1025  /// \endcode
1027  /// Indent only in inner namespaces (nested in other namespaces).
1028  /// \code
1029  /// namespace out {
1030  /// int i;
1031  /// namespace in {
1032  /// int i;
1033  /// }
1034  /// }
1035  /// \endcode
1037  /// Indent in all namespaces.
1038  /// \code
1039  /// namespace out {
1040  /// int i;
1041  /// namespace in {
1042  /// int i;
1043  /// }
1044  /// }
1045  /// \endcode
1046  NI_All
1047  };
1048 
1049  /// \brief The indentation used for namespaces.
1051 
1052  /// \brief The number of characters to use for indentation of ObjC blocks.
1054 
1055  /// \brief Add a space after ``@property`` in Objective-C, i.e. use
1056  /// ``@property (readonly)`` instead of ``@property(readonly)``.
1058 
1059  /// \brief Add a space in front of an Objective-C protocol list, i.e. use
1060  /// ``Foo <Protocol>`` instead of ``Foo<Protocol>``.
1062 
1063  /// \brief The penalty for breaking a function call after ``call(``.
1065 
1066  /// \brief The penalty for each line break introduced inside a comment.
1068 
1069  /// \brief The penalty for breaking before the first ``<<``.
1071 
1072  /// \brief The penalty for each line break introduced inside a string literal.
1074 
1075  /// \brief The penalty for each character outside of the column limit.
1077 
1078  /// \brief Penalty for putting the return type of a function onto its own
1079  /// line.
1081 
1082  /// \brief The ``&`` and ``*`` alignment style.
1084  /// Align pointer to the left.
1085  /// \code
1086  /// int* a;
1087  /// \endcode
1089  /// Align pointer to the right.
1090  /// \code
1091  /// int *a;
1092  /// \endcode
1094  /// Align pointer in the middle.
1095  /// \code
1096  /// int * a;
1097  /// \endcode
1098  PAS_Middle
1099  };
1100 
1101  /// \brief Pointer and reference alignment style.
1103 
1104  /// \brief If ``true``, clang-format will attempt to re-flow comments.
1105  /// \code
1106  /// false:
1107  /// // veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongComment with plenty of information
1108  /// /* second veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongComment with plenty of information */
1109  ///
1110  /// true:
1111  /// // veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongComment with plenty of
1112  /// // information
1113  /// /* second veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongComment with plenty of
1114  /// * information */
1115  /// \endcode
1117 
1118  /// \brief If ``true``, clang-format will sort ``#includes``.
1119  /// \code
1120  /// false: true:
1121  /// #include "b.h" vs. #include "a.h"
1122  /// #include "a.h" #include "b.h"
1123  /// \endcode
1125 
1126  /// \brief If ``true``, a space is inserted after C style casts.
1127  /// \code
1128  /// true: false:
1129  /// (int)i; vs. (int) i;
1130  /// \endcode
1132 
1133  /// \brief If \c true, a space will be inserted after the 'template' keyword.
1134  /// \code
1135  /// true: false:
1136  /// template <int> void foo(); vs. template<int> void foo();
1137  /// \endcode
1139 
1140  /// \brief If ``false``, spaces will be removed before assignment operators.
1141  /// \code
1142  /// true: false:
1143  /// int a = 5; vs. int a=5;
1144  /// a += 42 a+=42;
1145  /// \endcode
1147 
1148  /// \brief Different ways to put a space before opening parentheses.
1150  /// Never put a space before opening parentheses.
1151  /// \code
1152  /// void f() {
1153  /// if(true) {
1154  /// f();
1155  /// }
1156  /// }
1157  /// \endcode
1159  /// Put a space before opening parentheses only after control statement
1160  /// keywords (``for/if/while...``).
1161  /// \code
1162  /// void f() {
1163  /// if (true) {
1164  /// f();
1165  /// }
1166  /// }
1167  /// \endcode
1169  /// Always put a space before opening parentheses, except when it's
1170  /// prohibited by the syntax rules (in function-like macro definitions) or
1171  /// when determined by other style rules (after unary operators, opening
1172  /// parentheses, etc.)
1173  /// \code
1174  /// void f () {
1175  /// if (true) {
1176  /// f ();
1177  /// }
1178  /// }
1179  /// \endcode
1180  SBPO_Always
1181  };
1182 
1183  /// \brief Defines in which cases to put a space before opening parentheses.
1185 
1186  /// \brief If ``true``, spaces may be inserted into ``()``.
1187  /// \code
1188  /// true: false:
1189  /// void f( ) { vs. void f() {
1190  /// int x[] = {foo( ), bar( )}; int x[] = {foo(), bar()};
1191  /// if (true) { if (true) {
1192  /// f( ); f();
1193  /// } }
1194  /// } }
1195  /// \endcode
1197 
1198  /// \brief The number of spaces before trailing line comments
1199  /// (``//`` - comments).
1200  ///
1201  /// This does not affect trailing block comments (``/*`` - comments) as
1202  /// those commonly have different usage patterns and a number of special
1203  /// cases.
1204  /// \code
1205  /// SpacesBeforeTrailingComments: 3
1206  /// void f() {
1207  /// if (true) { // foo1
1208  /// f(); // bar
1209  /// } // foo
1210  /// }
1211  /// \endcode
1213 
1214  /// \brief If ``true``, spaces will be inserted after ``<`` and before ``>``
1215  /// in template argument lists.
1216  /// \code
1217  /// true: false:
1218  /// static_cast< int >(arg); vs. static_cast<int>(arg);
1219  /// std::function< void(int) > fct; std::function<void(int)> fct;
1220  /// \endcode
1222 
1223  /// \brief If ``true``, spaces are inserted inside container literals (e.g.
1224  /// ObjC and Javascript array and dict literals).
1225  /// \code{.js}
1226  /// true: false:
1227  /// var arr = [ 1, 2, 3 ]; vs. var arr = [1, 2, 3];
1228  /// f({a : 1, b : 2, c : 3}); f({a: 1, b: 2, c: 3});
1229  /// \endcode
1231 
1232  /// \brief If ``true``, spaces may be inserted into C style casts.
1233  /// \code
1234  /// true: false:
1235  /// x = ( int32 )y vs. x = (int32)y
1236  /// \endcode
1238 
1239  /// \brief If ``true``, spaces will be inserted after ``(`` and before ``)``.
1240  /// \code
1241  /// true: false:
1242  /// t f( Deleted & ) & = delete; vs. t f(Deleted &) & = delete;
1243  /// \endcode
1245 
1246  /// \brief If ``true``, spaces will be inserted after ``[`` and before ``]``.
1247  /// Lambdas or unspecified size array declarations will not be affected.
1248  /// \code
1249  /// true: false:
1250  /// int a[ 5 ]; vs. int a[5];
1251  /// std::unique_ptr<int[]> foo() {} // Won't be affected
1252  /// \endcode
1254 
1255  /// \brief Supported language standards.
1257  /// Use C++03-compatible syntax.
1259  /// Use features of C++11 (e.g. ``A<A<int>>`` instead of ``A<A<int> >``).
1261  /// Automatic detection based on the input.
1262  LS_Auto
1263  };
1264 
1265  /// \brief Format compatible with this standard, e.g. use ``A<A<int> >``
1266  /// instead of ``A<A<int>>`` for ``LS_Cpp03``.
1268 
1269  /// \brief The number of columns used for tab stops.
1270  unsigned TabWidth;
1271 
1272  /// \brief Different ways to use tab in formatting.
1274  /// Never use tab.
1276  /// Use tabs only for indentation.
1278  /// Use tabs only for line continuation and indentation.
1280  /// Use tabs whenever we need to fill whitespace that spans at least from
1281  /// one tab stop to the next one.
1282  UT_Always
1283  };
1284 
1285  /// \brief The way to use tab characters in the resulting file.
1287 
1288  bool operator==(const FormatStyle &R) const {
1289  return AccessModifierOffset == R.AccessModifierOffset &&
1290  AlignAfterOpenBracket == R.AlignAfterOpenBracket &&
1291  AlignConsecutiveAssignments == R.AlignConsecutiveAssignments &&
1292  AlignConsecutiveDeclarations == R.AlignConsecutiveDeclarations &&
1293  AlignEscapedNewlinesLeft == R.AlignEscapedNewlinesLeft &&
1294  AlignOperands == R.AlignOperands &&
1295  AlignTrailingComments == R.AlignTrailingComments &&
1296  AllowAllParametersOfDeclarationOnNextLine ==
1298  AllowShortBlocksOnASingleLine == R.AllowShortBlocksOnASingleLine &&
1299  AllowShortCaseLabelsOnASingleLine ==
1301  AllowShortFunctionsOnASingleLine ==
1303  AllowShortIfStatementsOnASingleLine ==
1305  AllowShortLoopsOnASingleLine == R.AllowShortLoopsOnASingleLine &&
1306  AlwaysBreakAfterReturnType == R.AlwaysBreakAfterReturnType &&
1307  AlwaysBreakBeforeMultilineStrings ==
1309  AlwaysBreakTemplateDeclarations ==
1311  BinPackArguments == R.BinPackArguments &&
1312  BinPackParameters == R.BinPackParameters &&
1313  BreakBeforeBinaryOperators == R.BreakBeforeBinaryOperators &&
1314  BreakBeforeBraces == R.BreakBeforeBraces &&
1315  BreakBeforeTernaryOperators == R.BreakBeforeTernaryOperators &&
1316  BreakConstructorInitializersBeforeComma ==
1318  BreakAfterJavaFieldAnnotations == R.BreakAfterJavaFieldAnnotations &&
1319  BreakStringLiterals == R.BreakStringLiterals &&
1320  ColumnLimit == R.ColumnLimit && CommentPragmas == R.CommentPragmas &&
1321  BreakBeforeInheritanceComma == R.BreakBeforeInheritanceComma &&
1322  ConstructorInitializerAllOnOneLineOrOnePerLine ==
1324  ConstructorInitializerIndentWidth ==
1326  ContinuationIndentWidth == R.ContinuationIndentWidth &&
1327  Cpp11BracedListStyle == R.Cpp11BracedListStyle &&
1328  DerivePointerAlignment == R.DerivePointerAlignment &&
1329  DisableFormat == R.DisableFormat &&
1330  ExperimentalAutoDetectBinPacking ==
1332  FixNamespaceComments == R.FixNamespaceComments &&
1333  ForEachMacros == R.ForEachMacros &&
1334  IncludeCategories == R.IncludeCategories &&
1335  IndentCaseLabels == R.IndentCaseLabels &&
1336  IndentWidth == R.IndentWidth && Language == R.Language &&
1337  IndentWrappedFunctionNames == R.IndentWrappedFunctionNames &&
1338  JavaScriptQuotes == R.JavaScriptQuotes &&
1339  JavaScriptWrapImports == R.JavaScriptWrapImports &&
1340  KeepEmptyLinesAtTheStartOfBlocks ==
1342  MacroBlockBegin == R.MacroBlockBegin &&
1343  MacroBlockEnd == R.MacroBlockEnd &&
1344  MaxEmptyLinesToKeep == R.MaxEmptyLinesToKeep &&
1345  NamespaceIndentation == R.NamespaceIndentation &&
1346  ObjCBlockIndentWidth == R.ObjCBlockIndentWidth &&
1347  ObjCSpaceAfterProperty == R.ObjCSpaceAfterProperty &&
1348  ObjCSpaceBeforeProtocolList == R.ObjCSpaceBeforeProtocolList &&
1349  PenaltyBreakBeforeFirstCallParameter ==
1351  PenaltyBreakComment == R.PenaltyBreakComment &&
1352  PenaltyBreakFirstLessLess == R.PenaltyBreakFirstLessLess &&
1353  PenaltyBreakString == R.PenaltyBreakString &&
1354  PenaltyExcessCharacter == R.PenaltyExcessCharacter &&
1355  PenaltyReturnTypeOnItsOwnLine == R.PenaltyReturnTypeOnItsOwnLine &&
1356  PointerAlignment == R.PointerAlignment &&
1357  SpaceAfterCStyleCast == R.SpaceAfterCStyleCast &&
1358  SpaceAfterTemplateKeyword == R.SpaceAfterTemplateKeyword &&
1359  SpaceBeforeAssignmentOperators == R.SpaceBeforeAssignmentOperators &&
1360  SpaceBeforeParens == R.SpaceBeforeParens &&
1361  SpaceInEmptyParentheses == R.SpaceInEmptyParentheses &&
1362  SpacesBeforeTrailingComments == R.SpacesBeforeTrailingComments &&
1363  SpacesInAngles == R.SpacesInAngles &&
1364  SpacesInContainerLiterals == R.SpacesInContainerLiterals &&
1365  SpacesInCStyleCastParentheses == R.SpacesInCStyleCastParentheses &&
1366  SpacesInParentheses == R.SpacesInParentheses &&
1367  SpacesInSquareBrackets == R.SpacesInSquareBrackets &&
1368  Standard == R.Standard && TabWidth == R.TabWidth &&
1369  UseTab == R.UseTab;
1370  }
1371 };
1372 
1373 /// \brief Returns a format style complying with the LLVM coding standards:
1374 /// http://llvm.org/docs/CodingStandards.html.
1376 
1377 /// \brief Returns a format style complying with one of Google's style guides:
1378 /// http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml.
1379 /// http://google-styleguide.googlecode.com/svn/trunk/javascriptguide.xml.
1380 /// https://developers.google.com/protocol-buffers/docs/style.
1382 
1383 /// \brief Returns a format style complying with Chromium's style guide:
1384 /// http://www.chromium.org/developers/coding-style.
1386 
1387 /// \brief Returns a format style complying with Mozilla's style guide:
1388 /// https://developer.mozilla.org/en-US/docs/Developer_Guide/Coding_Style.
1390 
1391 /// \brief Returns a format style complying with Webkit's style guide:
1392 /// http://www.webkit.org/coding/coding-style.html
1394 
1395 /// \brief Returns a format style complying with GNU Coding Standards:
1396 /// http://www.gnu.org/prep/standards/standards.html
1398 
1399 /// \brief Returns style indicating formatting should be not applied at all.
1401 
1402 /// \brief Gets a predefined style for the specified language by name.
1403 ///
1404 /// Currently supported names: LLVM, Google, Chromium, Mozilla. Names are
1405 /// compared case-insensitively.
1406 ///
1407 /// Returns ``true`` if the Style has been set.
1408 bool getPredefinedStyle(StringRef Name, FormatStyle::LanguageKind Language,
1409  FormatStyle *Style);
1410 
1411 /// \brief Parse configuration from YAML-formatted text.
1412 ///
1413 /// Style->Language is used to get the base style, if the ``BasedOnStyle``
1414 /// option is present.
1415 ///
1416 /// When ``BasedOnStyle`` is not present, options not present in the YAML
1417 /// document, are retained in \p Style.
1418 std::error_code parseConfiguration(StringRef Text, FormatStyle *Style);
1419 
1420 /// \brief Gets configuration in a YAML string.
1421 std::string configurationAsText(const FormatStyle &Style);
1422 
1423 /// \brief Returns the replacements necessary to sort all ``#include`` blocks
1424 /// that are affected by ``Ranges``.
1425 tooling::Replacements sortIncludes(const FormatStyle &Style, StringRef Code,
1426  ArrayRef<tooling::Range> Ranges,
1427  StringRef FileName,
1428  unsigned *Cursor = nullptr);
1429 
1430 /// \brief Returns the replacements corresponding to applying and formatting
1431 /// \p Replaces on success; otheriwse, return an llvm::Error carrying
1432 /// llvm::StringError.
1434 formatReplacements(StringRef Code, const tooling::Replacements &Replaces,
1435  const FormatStyle &Style);
1436 
1437 /// \brief Returns the replacements corresponding to applying \p Replaces and
1438 /// cleaning up the code after that on success; otherwise, return an llvm::Error
1439 /// carrying llvm::StringError.
1440 /// This also supports inserting/deleting C++ #include directives:
1441 /// - If a replacement has offset UINT_MAX, length 0, and a replacement text
1442 /// that is an #include directive, this will insert the #include into the
1443 /// correct block in the \p Code. When searching for points to insert new
1444 /// header, this ignores #include's after the #include block(s) in the
1445 /// beginning of a file to avoid inserting headers into code sections where
1446 /// new #include's should not be added by default. These code sections
1447 /// include:
1448 /// - raw string literals (containing #include).
1449 /// - #if blocks.
1450 /// - Special #include's among declarations (e.g. functions).
1451 /// - If a replacement has offset UINT_MAX, length 1, and a replacement text
1452 /// that is the name of the header to be removed, the header will be removed
1453 /// from \p Code if it exists.
1455 cleanupAroundReplacements(StringRef Code, const tooling::Replacements &Replaces,
1456  const FormatStyle &Style);
1457 
1458 /// \brief Reformats the given \p Ranges in \p Code.
1459 ///
1460 /// Each range is extended on either end to its next bigger logic unit, i.e.
1461 /// everything that might influence its formatting or might be influenced by its
1462 /// formatting.
1463 ///
1464 /// Returns the ``Replacements`` necessary to make all \p Ranges comply with
1465 /// \p Style.
1466 ///
1467 /// If ``IncompleteFormat`` is non-null, its value will be set to true if any
1468 /// of the affected ranges were not formatted due to a non-recoverable syntax
1469 /// error.
1470 tooling::Replacements reformat(const FormatStyle &Style, StringRef Code,
1471  ArrayRef<tooling::Range> Ranges,
1472  StringRef FileName = "<stdin>",
1473  bool *IncompleteFormat = nullptr);
1474 
1475 /// \brief Clean up any erroneous/redundant code in the given \p Ranges in \p
1476 /// Code.
1477 ///
1478 /// Returns the ``Replacements`` that clean up all \p Ranges in \p Code.
1479 tooling::Replacements cleanup(const FormatStyle &Style, StringRef Code,
1480  ArrayRef<tooling::Range> Ranges,
1481  StringRef FileName = "<stdin>");
1482 
1483 /// \brief Fix namespace end comments in the given \p Ranges in \p Code.
1484 ///
1485 /// Returns the ``Replacements`` that fix the namespace comments in all
1486 /// \p Ranges in \p Code.
1488  StringRef Code,
1489  ArrayRef<tooling::Range> Ranges,
1490  StringRef FileName = "<stdin>");
1491 
1492 /// \brief Returns the ``LangOpts`` that the formatter expects you to set.
1493 ///
1494 /// \param Style determines specific settings for lexing mode.
1496 
1497 /// \brief Description to be used for help text for a ``llvm::cl`` option for
1498 /// specifying format style. The description is closely related to the operation
1499 /// of ``getStyle()``.
1500 extern const char *StyleOptionHelpDescription;
1501 
1502 /// \brief Construct a FormatStyle based on ``StyleName``.
1503 ///
1504 /// ``StyleName`` can take several forms:
1505 /// * "{<key>: <value>, ...}" - Set specic style parameters.
1506 /// * "<style name>" - One of the style names supported by
1507 /// getPredefinedStyle().
1508 /// * "file" - Load style configuration from a file called ``.clang-format``
1509 /// located in one of the parent directories of ``FileName`` or the current
1510 /// directory if ``FileName`` is empty.
1511 ///
1512 /// \param[in] StyleName Style name to interpret according to the description
1513 /// above.
1514 /// \param[in] FileName Path to start search for .clang-format if ``StyleName``
1515 /// == "file".
1516 /// \param[in] FallbackStyle The name of a predefined style used to fallback to
1517 /// in case \p StyleName is "file" and no file can be found.
1518 /// \param[in] Code The actual code to be formatted. Used to determine the
1519 /// language if the filename isn't sufficient.
1520 /// \param[in] FS The underlying file system, in which the file resides. By
1521 /// default, the file system is the real file system.
1522 ///
1523 /// \returns FormatStyle as specified by ``StyleName``. If ``StyleName`` is
1524 /// "file" and no file is found, returns ``FallbackStyle``. If no style could be
1525 /// determined, returns an Error.
1526 llvm::Expected<FormatStyle> getStyle(StringRef StyleName, StringRef FileName,
1527  StringRef FallbackStyle,
1528  StringRef Code = "",
1529  vfs::FileSystem *FS = nullptr);
1530 
1531 // \brief Returns a string representation of ``Language``.
1532 inline StringRef getLanguageName(FormatStyle::LanguageKind Language) {
1533  switch (Language) {
1534  case FormatStyle::LK_Cpp:
1535  return "C++";
1536  case FormatStyle::LK_ObjC:
1537  return "Objective-C";
1538  case FormatStyle::LK_Java:
1539  return "Java";
1540  case FormatStyle::LK_JavaScript:
1541  return "JavaScript";
1542  case FormatStyle::LK_Proto:
1543  return "Proto";
1544  default:
1545  return "Unknown";
1546  }
1547 }
1548 
1549 } // end namespace format
1550 } // end namespace clang
1551 
1552 namespace std {
1553 template <>
1554 struct is_error_code_enum<clang::format::ParseError> : std::true_type {};
1555 }
1556 
1557 #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:1277
See documentation of IncludeCategories.
Definition: Format.h:828
tooling::Replacements reformat(const FormatStyle &Style, StringRef Code, ArrayRef< tooling::Range > Ranges, StringRef FileName="<stdin>", bool *IncompleteFormat=nullptr)
Reformats the given Ranges in Code.
Definition: Format.cpp:1831
PointerAlignmentStyle
The & and * alignment style.
Definition: Format.h:1083
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:877
bool AlwaysBreakBeforeMultilineStrings
If true, always break before multiline string literals.
Definition: Format.h:308
unsigned PenaltyBreakBeforeFirstCallParameter
The penalty for breaking a function call after call(.
Definition: Format.h:1064
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:1873
Should be used for Protocol Buffers (https://developers.google.com/protocol-buffers/).
Definition: Format.h:962
bool IndentCaseLabels
Indent case labels one level from the switch statement.
Definition: Format.h:883
unsigned IndentWidth
The number of columns to use for indentation.
Definition: Format.h:895
bool DisableFormat
Disables formatting completely.
Definition: Format.h:786
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:1138
PointerAlignmentStyle PointerAlignment
Pointer and reference alignment style.
Definition: Format.h:1102
std::error_code make_error_code(ParseError e)
Definition: Format.cpp:424
Align pointer to the left.
Definition: Format.h:1088
Maintains a set of replacements that are conflict-free.
Definition: Replacement.h:205
Should be used for C, C++.
Definition: Format.h:953
unsigned PenaltyBreakFirstLessLess
The penalty for breaking before the first <<.
Definition: Format.h:1070
LanguageKind
Supported languages.
Definition: Format.h:949
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:1882
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:939
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:783
bool ExperimentalAutoDetectBinPacking
If true, clang-format detects whether function calls and definitions are formatted with one parameter...
Definition: Format.h:798
bool SpaceInEmptyParentheses
If true, spaces may be inserted into ().
Definition: Format.h:1196
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:1934
Definition: Format.h:1552
Should be used for Java.
Definition: Format.h:955
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:864
NamespaceIndentationKind
Different ways to indent namespace contents.
Definition: Format.h:1016
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:708
Use tabs only for line continuation and indentation.
Definition: Format.h:1279
bool ConstructorInitializerAllOnOneLineOrOnePerLine
If the constructor initializers don&#39;t fit on a line, put each initializer on its own line...
Definition: Format.h:756
unsigned PenaltyBreakComment
The penalty for each line break introduced inside a comment.
Definition: Format.h:1067
bool IndentWrappedFunctionNames
Indent if a function definition or declaration is wrapped after the type.
Definition: Format.h:899
std::string Regex
The regular expression that this category matches.
Definition: Format.h:830
bool SpacesInParentheses
If true, spaces will be inserted after ( and before ).
Definition: Format.h:1244
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:1050
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:1053
bool SpaceBeforeAssignmentOperators
If false, spaces will be removed before assignment operators.
Definition: Format.h:1146
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:1184
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:903
bool AlignConsecutiveAssignments
If true, aligns consecutive assignments.
Definition: Format.h:88
unsigned ColumnLimit
The column limit.
Definition: Format.h:718
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:832
BracketAlignmentStyle AlignAfterOpenBracket
If true, horizontally aligns arguments after an open bracket.
Definition: Format.h:77
bool KeepEmptyLinesAtTheStartOfBlocks
If true, empty lines at the start of blocks are kept.
Definition: Format.h:942
std::vector< std::string > ForEachMacros
A vector of macros that should be interpreted as foreach loops instead of as function calls...
Definition: Format.h:825
SpaceBeforeParensOptions
Different ways to put a space before opening parentheses.
Definition: Format.h:1149
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:1286
std::string MacroBlockEnd
A regular expression matching macros that end a block.
Definition: Format.h:1000
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:727
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:997
Should be used for JavaScript.
Definition: Format.h:957
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:1892
bool SpacesInContainerLiterals
If true, spaces are inserted inside container literals (e.g.
Definition: Format.h:1230
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:1221
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:915
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:1026
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:1532
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:1073
LanguageStandard
Supported language standards.
Definition: Format.h:1256
Always attach braces to surrounding context.
Definition: Format.h:409
bool operator==(const FormatStyle &R) const
Definition: Format.h:1288
unsigned PenaltyExcessCharacter
The penalty for each character outside of the column limit.
Definition: Format.h:1076
bool ReflowComments
If true, clang-format will attempt to re-flow comments.
Definition: Format.h:1116
Put a space before opening parentheses only after control statement keywords (for/if/while...).
Definition: Format.h:1168
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:763
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:1237
bool SpacesInSquareBrackets
If true, spaces will be inserted after [ and before ].
Definition: Format.h:1253
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:1158
unsigned PenaltyReturnTypeOnItsOwnLine
Penalty for putting the return type of a function onto its own line.
Definition: Format.h:1080
Indent only in inner namespaces (nested in other namespaces).
Definition: Format.h:1036
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:969
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:1908
/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 IsCpp() const
Definition: Format.h:966
bool SortIncludes
If true, clang-format will sort #includes.
Definition: Format.h:1124
Leave string quotes as they are.
Definition: Format.h:909
bool FixNamespaceComments
If true, clang-format adds missing namespace end comments and fixes invalid existing ones...
Definition: Format.h:808
Use C++03-compatible syntax.
Definition: Format.h:1258
Always break after the return types of top-level functions.
Definition: Format.h:259
Use features of C++11 (e.g. A<A<int>> instead of A<A<int> >).
Definition: Format.h:1260
bool Cpp11BracedListStyle
If true, format braced lists as best suited for C++11 braced lists.
Definition: Format.h:778
BraceBreakingStyle
Different ways to attach braces to their surrounding context.
Definition: Format.h:395
bool operator==(const IncludeCategory &Other) const
Definition: Format.h:833
bool BreakStringLiterals
Allow breaking string literals when formatting.
Definition: Format.h:711
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:1270
UseTabStyle
Different ways to use tab in formatting.
Definition: Format.h:1273
bool SpaceAfterCStyleCast
If true, a space is inserted after C style casts.
Definition: Format.h:1131
JavaScriptQuoteStyle JavaScriptQuotes
The JavaScriptQuoteStyle to use for JavaScript strings.
Definition: Format.h:925
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:738
Should be used for Objective-C, Objective-C++.
Definition: Format.h:959
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:1267
unsigned ConstructorInitializerIndentWidth
The number of characters to use for indentation of constructor initializer lists. ...
Definition: Format.h:760
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:1061
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:1212
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:1093
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:1013
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