]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/clang/include/clang/Format/Format.h
Merge ^/head r312201 through r312206.
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / clang / include / clang / Format / Format.h
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
18 #include "clang/Basic/LangOptions.h"
19 #include "clang/Tooling/Core/Replacement.h"
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:``.
48   int AccessModifierOffset;
49
50   /// \brief Different styles for aligning after open brackets.
51   enum BracketAlignmentStyle {
52     /// \brief Align parameters on the open bracket, e.g.:
53     /// \code
54     ///   someLongFunction(argument1,
55     ///                    argument2);
56     /// \endcode
57     BAS_Align,
58     /// \brief Don't align, instead use ``ContinuationIndentWidth``, e.g.:
59     /// \code
60     ///   someLongFunction(argument1,
61     ///       argument2);
62     /// \endcode
63     BAS_DontAlign,
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
70     BAS_AlwaysBreak,
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.
77   BracketAlignmentStyle AlignAfterOpenBracket;
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
88   bool AlignConsecutiveAssignments;
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
99   bool AlignConsecutiveDeclarations;
100
101   /// \brief If ``true``, aligns escaped newlines as far left as possible.
102   /// Otherwise puts them into the right-most column.
103   bool AlignEscapedNewlinesLeft;
104
105   /// \brief If ``true``, horizontally align operands of binary and ternary
106   /// expressions.
107   ///
108   /// Specifically, this aligns operands of a single expression that needs to be
109   /// split over multiple lines, e.g.:
110   /// \code
111   ///   int aaa = bbbbbbbbbbbbbbb +
112   ///             ccccccccccccccc;
113   /// \endcode
114   bool AlignOperands;
115
116   /// \brief If ``true``, aligns trailing comments.
117   bool AlignTrailingComments;
118
119   /// \brief Allow putting all parameters of a function declaration onto
120   /// the next line even if ``BinPackParameters`` is ``false``.
121   bool AllowAllParametersOfDeclarationOnNextLine;
122
123   /// \brief Allows contracting simple braced statements to a single line.
124   ///
125   /// E.g., this allows ``if (a) { return; }`` to be put on a single line.
126   bool AllowShortBlocksOnASingleLine;
127
128   /// \brief If ``true``, short case labels will be contracted to a single line.
129   bool AllowShortCaseLabelsOnASingleLine;
130
131   /// \brief Different styles for merging short functions containing at most one
132   /// statement.
133   enum ShortFunctionStyle {
134     /// \brief Never merge functions into a single line.
135     SFS_None,
136     /// \brief Only merge empty functions.
137     SFS_Empty,
138     /// \brief Only merge functions defined inside a class. Implies "empty".
139     SFS_Inline,
140     /// \brief Merge all functions fitting on a single line.
141     SFS_All,
142   };
143
144   /// \brief Dependent on the value, ``int f() { return 0; }`` can be put on a
145   /// single line.
146   ShortFunctionStyle AllowShortFunctionsOnASingleLine;
147
148   /// \brief If ``true``, ``if (a) return;`` can be put on a single line.
149   bool AllowShortIfStatementsOnASingleLine;
150
151   /// \brief If ``true``, ``while (true) continue;`` can be put on a single
152   /// line.
153   bool AllowShortLoopsOnASingleLine;
154
155   /// \brief Different ways to break after the function definition return type.
156   enum DefinitionReturnTypeBreakingStyle {
157     /// Break after return type automatically.
158     /// ``PenaltyReturnTypeOnItsOwnLine`` is taken into account.
159     DRTBS_None,
160     /// Always break after the return type.
161     DRTBS_All,
162     /// Always break after the return types of top-level functions.
163     DRTBS_TopLevel,
164   };
165
166   /// \brief Different ways to break after the function definition or
167   /// declaration return type.
168   enum ReturnTypeBreakingStyle {
169     /// Break after return type automatically.
170     /// ``PenaltyReturnTypeOnItsOwnLine`` is taken into account.
171     RTBS_None,
172     /// Always break after the return type.
173     RTBS_All,
174     /// Always break after the return types of top-level functions.
175     RTBS_TopLevel,
176     /// Always break after the return type of function definitions.
177     RTBS_AllDefinitions,
178     /// Always break after the return type of top-level definitions.
179     RTBS_TopLevelDefinitions,
180   };
181
182   /// \brief The function definition return type breaking style to use.  This
183   /// option is deprecated and is retained for backwards compatibility.
184   DefinitionReturnTypeBreakingStyle AlwaysBreakAfterDefinitionReturnType;
185
186   /// \brief The function declaration return type breaking style to use.
187   ReturnTypeBreakingStyle AlwaysBreakAfterReturnType;
188
189   /// \brief If ``true``, always break before multiline string literals.
190   ///
191   /// This flag is mean to make cases where there are multiple multiline strings
192   /// in a file look more consistent. Thus, it will only take effect if wrapping
193   /// the string at that point leads to it being indented
194   /// ``ContinuationIndentWidth`` spaces from the start of the line.
195   bool AlwaysBreakBeforeMultilineStrings;
196
197   /// \brief If ``true``, always break after the ``template<...>`` of a template
198   /// declaration.
199   bool AlwaysBreakTemplateDeclarations;
200
201   /// \brief If ``false``, a function call's arguments will either be all on the
202   /// same line or will have one line each.
203   bool BinPackArguments;
204
205   /// \brief If ``false``, a function declaration's or function definition's
206   /// parameters will either all be on the same line or will have one line each.
207   bool BinPackParameters;
208
209   /// \brief The style of breaking before or after binary operators.
210   enum BinaryOperatorStyle {
211     /// Break after operators.
212     BOS_None,
213     /// Break before operators that aren't assignments.
214     BOS_NonAssignment,
215     /// Break before operators.
216     BOS_All,
217   };
218
219   /// \brief The way to wrap binary operators.
220   BinaryOperatorStyle BreakBeforeBinaryOperators;
221
222   /// \brief Different ways to attach braces to their surrounding context.
223   enum BraceBreakingStyle {
224     /// Always attach braces to surrounding context.
225     BS_Attach,
226     /// Like ``Attach``, but break before braces on function, namespace and
227     /// class definitions.
228     BS_Linux,
229     /// Like ``Attach``, but break before braces on enum, function, and record
230     /// definitions.
231     BS_Mozilla,
232     /// Like ``Attach``, but break before function definitions, ``catch``, and
233     /// ``else``.
234     BS_Stroustrup,
235     /// Always break before braces.
236     BS_Allman,
237     /// Always break before braces and add an extra level of indentation to
238     /// braces of control statements, not to those of class, function
239     /// or other definitions.
240     BS_GNU,
241     /// Like ``Attach``, but break before functions.
242     BS_WebKit,
243     /// Configure each individual brace in `BraceWrapping`.
244     BS_Custom
245   };
246
247   /// \brief The brace breaking style to use.
248   BraceBreakingStyle BreakBeforeBraces;
249
250   /// \brief Precise control over the wrapping of braces.
251   struct BraceWrappingFlags {
252     /// \brief Wrap class definitions.
253     bool AfterClass;
254     /// \brief Wrap control statements (``if``/``for``/``while``/``switch``/..).
255     bool AfterControlStatement;
256     /// \brief Wrap enum definitions.
257     bool AfterEnum;
258     /// \brief Wrap function definitions.
259     bool AfterFunction;
260     /// \brief Wrap namespace definitions.
261     bool AfterNamespace;
262     /// \brief Wrap ObjC definitions (``@autoreleasepool``, interfaces, ..).
263     bool AfterObjCDeclaration;
264     /// \brief Wrap struct definitions.
265     bool AfterStruct;
266     /// \brief Wrap union definitions.
267     bool AfterUnion;
268     /// \brief Wrap before ``catch``.
269     bool BeforeCatch;
270     /// \brief Wrap before ``else``.
271     bool BeforeElse;
272     /// \brief Indent the wrapped braces themselves.
273     bool IndentBraces;
274   };
275
276   /// \brief Control of individual brace wrapping cases.
277   ///
278   /// If ``BreakBeforeBraces`` is set to ``BS_Custom``, use this to specify how
279   /// each individual brace case should be handled. Otherwise, this is ignored.
280   BraceWrappingFlags BraceWrapping;
281
282   /// \brief If ``true``, ternary operators will be placed after line breaks.
283   bool BreakBeforeTernaryOperators;
284
285   /// \brief Always break constructor initializers before commas and align
286   /// the commas with the colon.
287   bool BreakConstructorInitializersBeforeComma;
288
289   /// \brief Break after each annotation on a field in Java files.
290   bool BreakAfterJavaFieldAnnotations;
291
292   /// \brief Allow breaking string literals when formatting.
293   bool BreakStringLiterals;
294
295   /// \brief The column limit.
296   ///
297   /// A column limit of ``0`` means that there is no column limit. In this case,
298   /// clang-format will respect the input's line breaking decisions within
299   /// statements unless they contradict other rules.
300   unsigned ColumnLimit;
301
302   /// \brief A regular expression that describes comments with special meaning,
303   /// which should not be split into lines or otherwise changed.
304   std::string CommentPragmas;
305
306   /// \brief If the constructor initializers don't fit on a line, put each
307   /// initializer on its own line.
308   bool ConstructorInitializerAllOnOneLineOrOnePerLine;
309
310   /// \brief The number of characters to use for indentation of constructor
311   /// initializer lists.
312   unsigned ConstructorInitializerIndentWidth;
313
314   /// \brief Indent width for line continuations.
315   unsigned ContinuationIndentWidth;
316
317   /// \brief If ``true``, format braced lists as best suited for C++11 braced
318   /// lists.
319   ///
320   /// Important differences:
321   /// - No spaces inside the braced list.
322   /// - No line break before the closing brace.
323   /// - Indentation with the continuation indent, not with the block indent.
324   ///
325   /// Fundamentally, C++11 braced lists are formatted exactly like function
326   /// calls would be formatted in their place. If the braced list follows a name
327   /// (e.g. a type or variable name), clang-format formats as if the ``{}`` were
328   /// the parentheses of a function call with that name. If there is no name,
329   /// a zero-length name is assumed.
330   bool Cpp11BracedListStyle;
331
332   /// \brief If ``true``, analyze the formatted file for the most common
333   /// alignment of ``&`` and ``*``. ``PointerAlignment`` is then used only as
334   /// fallback.
335   bool DerivePointerAlignment;
336
337   /// \brief Disables formatting completely.
338   bool DisableFormat;
339
340   /// \brief If ``true``, clang-format detects whether function calls and
341   /// definitions are formatted with one parameter per line.
342   ///
343   /// Each call can be bin-packed, one-per-line or inconclusive. If it is
344   /// inconclusive, e.g. completely on one line, but a decision needs to be
345   /// made, clang-format analyzes whether there are other bin-packed cases in
346   /// the input file and act accordingly.
347   ///
348   /// NOTE: This is an experimental flag, that might go away or be renamed. Do
349   /// not use this in config files, etc. Use at your own risk.
350   bool ExperimentalAutoDetectBinPacking;
351
352   /// \brief A vector of macros that should be interpreted as foreach loops
353   /// instead of as function calls.
354   ///
355   /// These are expected to be macros of the form:
356   /// \code
357   ///   FOREACH(<variable-declaration>, ...)
358   ///     <loop-body>
359   /// \endcode
360   ///
361   /// In the .clang-format configuration file, this can be configured like:
362   /// \code{.yaml}
363   ///   ForEachMacros: ['RANGES_FOR', 'FOREACH']
364   /// \endcode
365   ///
366   /// For example: BOOST_FOREACH.
367   std::vector<std::string> ForEachMacros;
368
369   /// \brief See documentation of ``IncludeCategories``.
370   struct IncludeCategory {
371     /// \brief The regular expression that this category matches.
372     std::string Regex;
373     /// \brief The priority to assign to this category.
374     int Priority;
375     bool operator==(const IncludeCategory &Other) const {
376       return Regex == Other.Regex && Priority == Other.Priority;
377     }
378   };
379
380   /// \brief Regular expressions denoting the different ``#include`` categories
381   /// used for ordering ``#includes``.
382   ///
383   /// These regular expressions are matched against the filename of an include
384   /// (including the <> or "") in order. The value belonging to the first
385   /// matching regular expression is assigned and ``#includes`` are sorted first
386   /// according to increasing category number and then alphabetically within
387   /// each category.
388   ///
389   /// If none of the regular expressions match, INT_MAX is assigned as
390   /// category. The main header for a source file automatically gets category 0.
391   /// so that it is generally kept at the beginning of the ``#includes``
392   /// (http://llvm.org/docs/CodingStandards.html#include-style). However, you
393   /// can also assign negative priorities if you have certain headers that
394   /// always need to be first.
395   ///
396   /// To configure this in the .clang-format file, use:
397   /// \code{.yaml}
398   ///   IncludeCategories:
399   ///     - Regex:           '^"(llvm|llvm-c|clang|clang-c)/'
400   ///       Priority:        2
401   ///     - Regex:           '^(<|"(gtest|isl|json)/)'
402   ///       Priority:        3
403   ///     - Regex:           '.*'
404   ///       Priority:        1
405   /// \endcode
406   std::vector<IncludeCategory> IncludeCategories;
407
408   /// \brief Specify a regular expression of suffixes that are allowed in the
409   /// file-to-main-include mapping.
410   ///
411   /// When guessing whether a #include is the "main" include (to assign
412   /// category 0, see above), use this regex of allowed suffixes to the header
413   /// stem. A partial match is done, so that:
414   /// - "" means "arbitrary suffix"
415   /// - "$" means "no suffix"
416   ///
417   /// For example, if configured to "(_test)?$", then a header a.h would be seen
418   /// as the "main" include in both a.cc and a_test.cc.
419   std::string IncludeIsMainRegex;
420
421   /// \brief Indent case labels one level from the switch statement.
422   ///
423   /// When ``false``, use the same indentation level as for the switch statement.
424   /// Switch statement body is always indented one level more than case labels.
425   bool IndentCaseLabels;
426
427   /// \brief The number of columns to use for indentation.
428   unsigned IndentWidth;
429
430   /// \brief Indent if a function definition or declaration is wrapped after the
431   /// type.
432   bool IndentWrappedFunctionNames;
433
434   /// \brief Quotation styles for JavaScript strings. Does not affect template
435   /// strings.
436   enum JavaScriptQuoteStyle {
437     /// Leave string quotes as they are.
438     JSQS_Leave,
439     /// Always use single quotes.
440     JSQS_Single,
441     /// Always use double quotes.
442     JSQS_Double
443   };
444
445   /// \brief The JavaScriptQuoteStyle to use for JavaScript strings.
446   JavaScriptQuoteStyle JavaScriptQuotes;
447
448   /// \brief Whether to wrap JavaScript import/export statements.
449   bool JavaScriptWrapImports;
450
451   /// \brief If true, empty lines at the start of blocks are kept.
452   bool KeepEmptyLinesAtTheStartOfBlocks;
453
454   /// \brief Supported languages.
455   ///
456   /// When stored in a configuration file, specifies the language, that the
457   /// configuration targets. When passed to the ``reformat()`` function, enables
458   /// syntax features specific to the language.
459   enum LanguageKind {
460     /// Do not use.
461     LK_None,
462     /// Should be used for C, C++, ObjectiveC, ObjectiveC++.
463     LK_Cpp,
464     /// Should be used for Java.
465     LK_Java,
466     /// Should be used for JavaScript.
467     LK_JavaScript,
468     /// Should be used for ObjC code.
469     LK_ObjC,
470     /// Should be used for Protocol Buffers
471     /// (https://developers.google.com/protocol-buffers/).
472     LK_Proto,
473     /// Should be used for TableGen code.
474     LK_TableGen
475   };
476
477   /// \brief Language, this format style is targeted at.
478   LanguageKind Language;
479
480   /// \brief A regular expression matching macros that start a block.
481   std::string MacroBlockBegin;
482
483   /// \brief A regular expression matching macros that end a block.
484   std::string MacroBlockEnd;
485
486   /// \brief The maximum number of consecutive empty lines to keep.
487   unsigned MaxEmptyLinesToKeep;
488
489   /// \brief Different ways to indent namespace contents.
490   enum NamespaceIndentationKind {
491     /// Don't indent in namespaces.
492     NI_None,
493     /// Indent only in inner namespaces (nested in other namespaces).
494     NI_Inner,
495     /// Indent in all namespaces.
496     NI_All
497   };
498
499   /// \brief The indentation used for namespaces.
500   NamespaceIndentationKind NamespaceIndentation;
501
502   /// \brief The number of characters to use for indentation of ObjC blocks.
503   unsigned ObjCBlockIndentWidth;
504
505   /// \brief Add a space after ``@property`` in Objective-C, i.e. use
506   /// ``@property (readonly)`` instead of ``@property(readonly)``.
507   bool ObjCSpaceAfterProperty;
508
509   /// \brief Add a space in front of an Objective-C protocol list, i.e. use
510   /// ``Foo <Protocol>`` instead of ``Foo<Protocol>``.
511   bool ObjCSpaceBeforeProtocolList;
512
513   /// \brief The penalty for breaking a function call after ``call(``.
514   unsigned PenaltyBreakBeforeFirstCallParameter;
515
516   /// \brief The penalty for each line break introduced inside a comment.
517   unsigned PenaltyBreakComment;
518
519   /// \brief The penalty for breaking before the first ``<<``.
520   unsigned PenaltyBreakFirstLessLess;
521
522   /// \brief The penalty for each line break introduced inside a string literal.
523   unsigned PenaltyBreakString;
524
525   /// \brief The penalty for each character outside of the column limit.
526   unsigned PenaltyExcessCharacter;
527
528   /// \brief Penalty for putting the return type of a function onto its own
529   /// line.
530   unsigned PenaltyReturnTypeOnItsOwnLine;
531
532   /// \brief The ``&`` and ``*`` alignment style.
533   enum PointerAlignmentStyle {
534     /// Align pointer to the left.
535     PAS_Left,
536     /// Align pointer to the right.
537     PAS_Right,
538     /// Align pointer in the middle.
539     PAS_Middle
540   };
541
542   /// \brief Pointer and reference alignment style.
543   PointerAlignmentStyle PointerAlignment;
544
545   /// \brief If ``true``, clang-format will attempt to re-flow comments.
546   bool ReflowComments;
547
548   /// \brief If ``true``, clang-format will sort ``#includes``.
549   bool SortIncludes;
550
551   /// \brief If ``true``, a space may be inserted after C style casts.
552   bool SpaceAfterCStyleCast;
553
554   /// \brief If \c true, a space will be inserted after the 'template' keyword.
555   bool SpaceAfterTemplateKeyword;
556
557   /// \brief If ``false``, spaces will be removed before assignment operators.
558   bool SpaceBeforeAssignmentOperators;
559
560   /// \brief Different ways to put a space before opening parentheses.
561   enum SpaceBeforeParensOptions {
562     /// Never put a space before opening parentheses.
563     SBPO_Never,
564     /// Put a space before opening parentheses only after control statement
565     /// keywords (``for/if/while...``).
566     SBPO_ControlStatements,
567     /// Always put a space before opening parentheses, except when it's
568     /// prohibited by the syntax rules (in function-like macro definitions) or
569     /// when determined by other style rules (after unary operators, opening
570     /// parentheses, etc.)
571     SBPO_Always
572   };
573
574   /// \brief Defines in which cases to put a space before opening parentheses.
575   SpaceBeforeParensOptions SpaceBeforeParens;
576
577   /// \brief If ``true``, spaces may be inserted into ``()``.
578   bool SpaceInEmptyParentheses;
579
580   /// \brief The number of spaces before trailing line comments
581   /// (``//`` - comments).
582   ///
583   /// This does not affect trailing block comments (``/*`` - comments) as
584   /// those commonly have different usage patterns and a number of special
585   /// cases.
586   unsigned SpacesBeforeTrailingComments;
587
588   /// \brief If ``true``, spaces will be inserted after ``<`` and before ``>``
589   /// in template argument lists.
590   bool SpacesInAngles;
591
592   /// \brief If ``true``, spaces are inserted inside container literals (e.g.
593   /// ObjC and Javascript array and dict literals).
594   bool SpacesInContainerLiterals;
595
596   /// \brief If ``true``, spaces may be inserted into C style casts.
597   bool SpacesInCStyleCastParentheses;
598
599   /// \brief If ``true``, spaces will be inserted after ``(`` and before ``)``.
600   bool SpacesInParentheses;
601
602   /// \brief If ``true``, spaces will be inserted after ``[`` and before ``]``.
603   bool SpacesInSquareBrackets;
604
605   /// \brief Supported language standards.
606   enum LanguageStandard {
607     /// Use C++03-compatible syntax.
608     LS_Cpp03,
609     /// Use features of C++11 (e.g. ``A<A<int>>`` instead of ``A<A<int> >``).
610     LS_Cpp11,
611     /// Automatic detection based on the input.
612     LS_Auto
613   };
614
615   /// \brief Format compatible with this standard, e.g. use ``A<A<int> >``
616   /// instead of ``A<A<int>>`` for ``LS_Cpp03``.
617   LanguageStandard Standard;
618
619   /// \brief The number of columns used for tab stops.
620   unsigned TabWidth;
621
622   /// \brief Different ways to use tab in formatting.
623   enum UseTabStyle {
624     /// Never use tab.
625     UT_Never,
626     /// Use tabs only for indentation.
627     UT_ForIndentation,
628     /// Use tabs only for line continuation and indentation.
629     UT_ForContinuationAndIndentation,
630     /// Use tabs whenever we need to fill whitespace that spans at least from
631     /// one tab stop to the next one.
632     UT_Always
633   };
634
635   /// \brief The way to use tab characters in the resulting file.
636   UseTabStyle UseTab;
637
638   bool operator==(const FormatStyle &R) const {
639     return AccessModifierOffset == R.AccessModifierOffset &&
640            AlignAfterOpenBracket == R.AlignAfterOpenBracket &&
641            AlignConsecutiveAssignments == R.AlignConsecutiveAssignments &&
642            AlignConsecutiveDeclarations == R.AlignConsecutiveDeclarations &&
643            AlignEscapedNewlinesLeft == R.AlignEscapedNewlinesLeft &&
644            AlignOperands == R.AlignOperands &&
645            AlignTrailingComments == R.AlignTrailingComments &&
646            AllowAllParametersOfDeclarationOnNextLine ==
647                R.AllowAllParametersOfDeclarationOnNextLine &&
648            AllowShortBlocksOnASingleLine == R.AllowShortBlocksOnASingleLine &&
649            AllowShortCaseLabelsOnASingleLine ==
650                R.AllowShortCaseLabelsOnASingleLine &&
651            AllowShortFunctionsOnASingleLine ==
652                R.AllowShortFunctionsOnASingleLine &&
653            AllowShortIfStatementsOnASingleLine ==
654                R.AllowShortIfStatementsOnASingleLine &&
655            AllowShortLoopsOnASingleLine == R.AllowShortLoopsOnASingleLine &&
656            AlwaysBreakAfterReturnType == R.AlwaysBreakAfterReturnType &&
657            AlwaysBreakBeforeMultilineStrings ==
658                R.AlwaysBreakBeforeMultilineStrings &&
659            AlwaysBreakTemplateDeclarations ==
660                R.AlwaysBreakTemplateDeclarations &&
661            BinPackArguments == R.BinPackArguments &&
662            BinPackParameters == R.BinPackParameters &&
663            BreakBeforeBinaryOperators == R.BreakBeforeBinaryOperators &&
664            BreakBeforeBraces == R.BreakBeforeBraces &&
665            BreakBeforeTernaryOperators == R.BreakBeforeTernaryOperators &&
666            BreakConstructorInitializersBeforeComma ==
667                R.BreakConstructorInitializersBeforeComma &&
668            BreakAfterJavaFieldAnnotations == R.BreakAfterJavaFieldAnnotations &&
669            BreakStringLiterals == R.BreakStringLiterals &&
670            ColumnLimit == R.ColumnLimit && CommentPragmas == R.CommentPragmas &&
671            ConstructorInitializerAllOnOneLineOrOnePerLine ==
672                R.ConstructorInitializerAllOnOneLineOrOnePerLine &&
673            ConstructorInitializerIndentWidth ==
674                R.ConstructorInitializerIndentWidth &&
675            ContinuationIndentWidth == R.ContinuationIndentWidth &&
676            Cpp11BracedListStyle == R.Cpp11BracedListStyle &&
677            DerivePointerAlignment == R.DerivePointerAlignment &&
678            DisableFormat == R.DisableFormat &&
679            ExperimentalAutoDetectBinPacking ==
680                R.ExperimentalAutoDetectBinPacking &&
681            ForEachMacros == R.ForEachMacros &&
682            IncludeCategories == R.IncludeCategories &&
683            IndentCaseLabels == R.IndentCaseLabels &&
684            IndentWidth == R.IndentWidth && Language == R.Language &&
685            IndentWrappedFunctionNames == R.IndentWrappedFunctionNames &&
686            JavaScriptQuotes == R.JavaScriptQuotes &&
687            JavaScriptWrapImports == R.JavaScriptWrapImports &&
688            KeepEmptyLinesAtTheStartOfBlocks ==
689                R.KeepEmptyLinesAtTheStartOfBlocks &&
690            MacroBlockBegin == R.MacroBlockBegin &&
691            MacroBlockEnd == R.MacroBlockEnd &&
692            MaxEmptyLinesToKeep == R.MaxEmptyLinesToKeep &&
693            NamespaceIndentation == R.NamespaceIndentation &&
694            ObjCBlockIndentWidth == R.ObjCBlockIndentWidth &&
695            ObjCSpaceAfterProperty == R.ObjCSpaceAfterProperty &&
696            ObjCSpaceBeforeProtocolList == R.ObjCSpaceBeforeProtocolList &&
697            PenaltyBreakBeforeFirstCallParameter ==
698                R.PenaltyBreakBeforeFirstCallParameter &&
699            PenaltyBreakComment == R.PenaltyBreakComment &&
700            PenaltyBreakFirstLessLess == R.PenaltyBreakFirstLessLess &&
701            PenaltyBreakString == R.PenaltyBreakString &&
702            PenaltyExcessCharacter == R.PenaltyExcessCharacter &&
703            PenaltyReturnTypeOnItsOwnLine == R.PenaltyReturnTypeOnItsOwnLine &&
704            PointerAlignment == R.PointerAlignment &&
705            SpaceAfterCStyleCast == R.SpaceAfterCStyleCast &&
706            SpaceAfterTemplateKeyword == R.SpaceAfterTemplateKeyword &&
707            SpaceBeforeAssignmentOperators == R.SpaceBeforeAssignmentOperators &&
708            SpaceBeforeParens == R.SpaceBeforeParens &&
709            SpaceInEmptyParentheses == R.SpaceInEmptyParentheses &&
710            SpacesBeforeTrailingComments == R.SpacesBeforeTrailingComments &&
711            SpacesInAngles == R.SpacesInAngles &&
712            SpacesInContainerLiterals == R.SpacesInContainerLiterals &&
713            SpacesInCStyleCastParentheses == R.SpacesInCStyleCastParentheses &&
714            SpacesInParentheses == R.SpacesInParentheses &&
715            SpacesInSquareBrackets == R.SpacesInSquareBrackets &&
716            Standard == R.Standard && TabWidth == R.TabWidth &&
717            UseTab == R.UseTab;
718   }
719 };
720
721 /// \brief Returns a format style complying with the LLVM coding standards:
722 /// http://llvm.org/docs/CodingStandards.html.
723 FormatStyle getLLVMStyle();
724
725 /// \brief Returns a format style complying with one of Google's style guides:
726 /// http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml.
727 /// http://google-styleguide.googlecode.com/svn/trunk/javascriptguide.xml.
728 /// https://developers.google.com/protocol-buffers/docs/style.
729 FormatStyle getGoogleStyle(FormatStyle::LanguageKind Language);
730
731 /// \brief Returns a format style complying with Chromium's style guide:
732 /// http://www.chromium.org/developers/coding-style.
733 FormatStyle getChromiumStyle(FormatStyle::LanguageKind Language);
734
735 /// \brief Returns a format style complying with Mozilla's style guide:
736 /// https://developer.mozilla.org/en-US/docs/Developer_Guide/Coding_Style.
737 FormatStyle getMozillaStyle();
738
739 /// \brief Returns a format style complying with Webkit's style guide:
740 /// http://www.webkit.org/coding/coding-style.html
741 FormatStyle getWebKitStyle();
742
743 /// \brief Returns a format style complying with GNU Coding Standards:
744 /// http://www.gnu.org/prep/standards/standards.html
745 FormatStyle getGNUStyle();
746
747 /// \brief Returns style indicating formatting should be not applied at all.
748 FormatStyle getNoStyle();
749
750 /// \brief Gets a predefined style for the specified language by name.
751 ///
752 /// Currently supported names: LLVM, Google, Chromium, Mozilla. Names are
753 /// compared case-insensitively.
754 ///
755 /// Returns ``true`` if the Style has been set.
756 bool getPredefinedStyle(StringRef Name, FormatStyle::LanguageKind Language,
757                         FormatStyle *Style);
758
759 /// \brief Parse configuration from YAML-formatted text.
760 ///
761 /// Style->Language is used to get the base style, if the ``BasedOnStyle``
762 /// option is present.
763 ///
764 /// When ``BasedOnStyle`` is not present, options not present in the YAML
765 /// document, are retained in \p Style.
766 std::error_code parseConfiguration(StringRef Text, FormatStyle *Style);
767
768 /// \brief Gets configuration in a YAML string.
769 std::string configurationAsText(const FormatStyle &Style);
770
771 /// \brief Returns the replacements necessary to sort all ``#include`` blocks
772 /// that are affected by ``Ranges``.
773 tooling::Replacements sortIncludes(const FormatStyle &Style, StringRef Code,
774                                    ArrayRef<tooling::Range> Ranges,
775                                    StringRef FileName,
776                                    unsigned *Cursor = nullptr);
777
778 /// \brief Returns the replacements corresponding to applying and formatting
779 /// \p Replaces on success; otheriwse, return an llvm::Error carrying
780 /// llvm::StringError.
781 llvm::Expected<tooling::Replacements>
782 formatReplacements(StringRef Code, const tooling::Replacements &Replaces,
783                    const FormatStyle &Style);
784
785 /// \brief Returns the replacements corresponding to applying \p Replaces and
786 /// cleaning up the code after that on success; otherwise, return an llvm::Error
787 /// carrying llvm::StringError.
788 /// This also supports inserting/deleting C++ #include directives:
789 /// - If a replacement has offset UINT_MAX, length 0, and a replacement text
790 ///   that is an #include directive, this will insert the #include into the
791 ///   correct block in the \p Code. When searching for points to insert new
792 ///   header, this ignores #include's after the #include block(s) in the
793 ///   beginning of a file to avoid inserting headers into code sections where
794 ///   new #include's should not be added by default. These code sections
795 ///   include:
796 ///     - raw string literals (containing #include).
797 ///     - #if blocks.
798 ///     - Special #include's among declarations (e.g. functions).
799 /// - If a replacement has offset UINT_MAX, length 1, and a replacement text
800 ///   that is the name of the header to be removed, the header will be removed
801 ///   from \p Code if it exists.
802 llvm::Expected<tooling::Replacements>
803 cleanupAroundReplacements(StringRef Code, const tooling::Replacements &Replaces,
804                           const FormatStyle &Style);
805
806 /// \brief Reformats the given \p Ranges in \p Code.
807 ///
808 /// Each range is extended on either end to its next bigger logic unit, i.e.
809 /// everything that might influence its formatting or might be influenced by its
810 /// formatting.
811 ///
812 /// Returns the ``Replacements`` necessary to make all \p Ranges comply with
813 /// \p Style.
814 ///
815 /// If ``IncompleteFormat`` is non-null, its value will be set to true if any
816 /// of the affected ranges were not formatted due to a non-recoverable syntax
817 /// error.
818 tooling::Replacements reformat(const FormatStyle &Style, StringRef Code,
819                                ArrayRef<tooling::Range> Ranges,
820                                StringRef FileName = "<stdin>",
821                                bool *IncompleteFormat = nullptr);
822
823 /// \brief Clean up any erroneous/redundant code in the given \p Ranges in \p
824 /// Code.
825 ///
826 /// Returns the ``Replacements`` that clean up all \p Ranges in \p Code.
827 tooling::Replacements cleanup(const FormatStyle &Style, StringRef Code,
828                               ArrayRef<tooling::Range> Ranges,
829                               StringRef FileName = "<stdin>");
830
831 /// \brief Returns the ``LangOpts`` that the formatter expects you to set.
832 ///
833 /// \param Style determines specific settings for lexing mode.
834 LangOptions getFormattingLangOpts(const FormatStyle &Style = getLLVMStyle());
835
836 /// \brief Description to be used for help text for a ``llvm::cl`` option for
837 /// specifying format style. The description is closely related to the operation
838 /// of ``getStyle()``.
839 extern const char *StyleOptionHelpDescription;
840
841 /// \brief Construct a FormatStyle based on ``StyleName``.
842 ///
843 /// ``StyleName`` can take several forms:
844 /// * "{<key>: <value>, ...}" - Set specic style parameters.
845 /// * "<style name>" - One of the style names supported by
846 /// getPredefinedStyle().
847 /// * "file" - Load style configuration from a file called ``.clang-format``
848 /// located in one of the parent directories of ``FileName`` or the current
849 /// directory if ``FileName`` is empty.
850 ///
851 /// \param[in] StyleName Style name to interpret according to the description
852 /// above.
853 /// \param[in] FileName Path to start search for .clang-format if ``StyleName``
854 /// == "file".
855 /// \param[in] FallbackStyle The name of a predefined style used to fallback to
856 /// in case the style can't be determined from \p StyleName.
857 /// \param[in] Code The actual code to be formatted. Used to determine the
858 /// language if the filename isn't sufficient.
859 /// \param[in] FS The underlying file system, in which the file resides. By
860 /// default, the file system is the real file system.
861 ///
862 /// \returns FormatStyle as specified by ``StyleName``. If no style could be
863 /// determined, the default is LLVM Style (see ``getLLVMStyle()``).
864 FormatStyle getStyle(StringRef StyleName, StringRef FileName,
865                      StringRef FallbackStyle, StringRef Code = "",
866                      vfs::FileSystem *FS = nullptr);
867
868 // \brief Returns a string representation of ``Language``.
869 inline StringRef getLanguageName(FormatStyle::LanguageKind Language) {
870   switch (Language) {
871   case FormatStyle::LK_Cpp:
872     return "C++";
873   case FormatStyle::LK_Java:
874     return "Java";
875   case FormatStyle::LK_JavaScript:
876     return "JavaScript";
877   case FormatStyle::LK_Proto:
878     return "Proto";
879   default:
880     return "Unknown";
881   }
882 }
883
884 } // end namespace format
885 } // end namespace clang
886
887 namespace std {
888 template <>
889 struct is_error_code_enum<clang::format::ParseError> : std::true_type {};
890 }
891
892 #endif // LLVM_CLANG_FORMAT_FORMAT_H