clang  3.9.0
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 LLVM_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.
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
115 
116  /// \brief If ``true``, aligns trailing comments.
118 
119  /// \brief Allow putting all parameters of a function declaration onto
120  /// the next line even if ``BinPackParameters`` is ``false``.
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.
127 
128  /// \brief If ``true``, short case labels will be contracted to a single line.
130 
131  /// \brief Different styles for merging short functions containing at most one
132  /// statement.
134  /// \brief Never merge functions into a single line.
136  /// \brief Only merge empty functions.
138  /// \brief Only merge functions defined inside a class. Implies "empty".
140  /// \brief Merge all functions fitting on a single line.
142  };
143 
144  /// \brief Dependent on the value, ``int f() { return 0; }`` can be put on a
145  /// single line.
147 
148  /// \brief If ``true``, ``if (a) return;`` can be put on a single line.
150 
151  /// \brief If ``true``, ``while (true) continue;`` can be put on a single
152  /// line.
154 
155  /// \brief Different ways to break after the function definition return type.
157  /// Break after return type automatically.
158  /// ``PenaltyReturnTypeOnItsOwnLine`` is taken into account.
160  /// Always break after the return type.
162  /// Always break after the return types of top-level functions.
164  };
165 
166  /// \brief Different ways to break after the function definition or
167  /// declaration return type.
169  /// Break after return type automatically.
170  /// ``PenaltyReturnTypeOnItsOwnLine`` is taken into account.
172  /// Always break after the return type.
174  /// Always break after the return types of top-level functions.
176  /// Always break after the return type of function definitions.
178  /// Always break after the return type of top-level definitions.
180  };
181 
182  /// \brief The function definition return type breaking style to use. This
183  /// option is deprecated and is retained for backwards compatibility.
185 
186  /// \brief The function declaration return type breaking style to use.
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.
196 
197  /// \brief If ``true``, always break after the ``template<...>`` of a template
198  /// declaration.
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.
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.
208 
209  /// \brief The style of breaking before or after binary operators.
211  /// Break after operators.
213  /// Break before operators that aren't assignments.
215  /// Break before operators.
217  };
218 
219  /// \brief The way to wrap binary operators.
221 
222  /// \brief Different ways to attach braces to their surrounding context.
224  /// Always attach braces to surrounding context.
226  /// Like ``Attach``, but break before braces on function, namespace and
227  /// class definitions.
229  /// Like ``Attach``, but break before braces on enum, function, and record
230  /// definitions.
232  /// Like ``Attach``, but break before function definitions, ``catch``, and
233  /// ``else``.
235  /// Always break before braces.
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.
241  /// Like ``Attach``, but break before functions.
243  /// Configure each individual brace in `BraceWrapping`.
245  };
246 
247  /// \brief The brace breaking style to use.
249 
250  /// \brief Precise control over the wrapping of braces.
252  /// \brief Wrap class definitions.
254  /// \brief Wrap control statements (``if``/``for``/``while``/``switch``/..).
256  /// \brief Wrap enum definitions.
257  bool AfterEnum;
258  /// \brief Wrap function definitions.
260  /// \brief Wrap namespace definitions.
262  /// \brief Wrap ObjC definitions (``@autoreleasepool``, interfaces, ..).
264  /// \brief Wrap struct definitions.
266  /// \brief Wrap union definitions.
268  /// \brief Wrap before ``catch``.
270  /// \brief Wrap before ``else``.
272  /// \brief Indent the wrapped braces themselves.
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.
281 
282  /// \brief If ``true``, ternary operators will be placed after line breaks.
284 
285  /// \brief Always break constructor initializers before commas and align
286  /// the commas with the colon.
288 
289  /// \brief Break after each annotation on a field in Java files.
291 
292  /// \brief Allow breaking string literals when formatting.
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.
309 
310  /// \brief The number of characters to use for indentation of constructor
311  /// initializer lists.
313 
314  /// \brief Indent width for line continuations.
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.
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.
336 
337  /// \brief Disables formatting completely.
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.
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``.
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.
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.
433 
434  /// \brief Quotation styles for JavaScript strings. Does not affect template
435  /// strings.
437  /// Leave string quotes as they are.
439  /// Always use single quotes.
441  /// Always use double quotes.
443  };
444 
445  /// \brief The JavaScriptQuoteStyle to use for JavaScript strings.
447 
448  /// \brief Whether to wrap JavaScript import/export statements.
450 
451  /// \brief If true, empty lines at the start of blocks are kept.
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.
460  /// Do not use.
462  /// Should be used for C, C++, ObjectiveC, ObjectiveC++.
464  /// Should be used for Java.
466  /// Should be used for JavaScript.
468  /// Should be used for Protocol Buffers
469  /// (https://developers.google.com/protocol-buffers/).
471  /// Should be used for TableGen code.
473  };
474 
475  /// \brief Language, this format style is targeted at.
477 
478  /// \brief A regular expression matching macros that start a block.
479  std::string MacroBlockBegin;
480 
481  /// \brief A regular expression matching macros that end a block.
482  std::string MacroBlockEnd;
483 
484  /// \brief The maximum number of consecutive empty lines to keep.
486 
487  /// \brief Different ways to indent namespace contents.
489  /// Don't indent in namespaces.
491  /// Indent only in inner namespaces (nested in other namespaces).
493  /// Indent in all namespaces.
495  };
496 
497  /// \brief The indentation used for namespaces.
499 
500  /// \brief The number of characters to use for indentation of ObjC blocks.
502 
503  /// \brief Add a space after ``@property`` in Objective-C, i.e. use
504  /// ``@property (readonly)`` instead of ``@property(readonly)``.
506 
507  /// \brief Add a space in front of an Objective-C protocol list, i.e. use
508  /// ``Foo <Protocol>`` instead of ``Foo<Protocol>``.
510 
511  /// \brief The penalty for breaking a function call after ``call(``.
513 
514  /// \brief The penalty for each line break introduced inside a comment.
516 
517  /// \brief The penalty for breaking before the first ``<<``.
519 
520  /// \brief The penalty for each line break introduced inside a string literal.
522 
523  /// \brief The penalty for each character outside of the column limit.
525 
526  /// \brief Penalty for putting the return type of a function onto its own
527  /// line.
529 
530  /// \brief The ``&`` and ``*`` alignment style.
532  /// Align pointer to the left.
534  /// Align pointer to the right.
536  /// Align pointer in the middle.
538  };
539 
540  /// \brief Pointer and reference alignment style.
542 
543  /// \brief If ``true``, clang-format will attempt to re-flow comments.
545 
546  /// \brief If ``true``, clang-format will sort ``#includes``.
548 
549  /// \brief If ``true``, a space may be inserted after C style casts.
551 
552  /// \brief If ``false``, spaces will be removed before assignment operators.
554 
555  /// \brief Different ways to put a space before opening parentheses.
557  /// Never put a space before opening parentheses.
559  /// Put a space before opening parentheses only after control statement
560  /// keywords (``for/if/while...``).
562  /// Always put a space before opening parentheses, except when it's
563  /// prohibited by the syntax rules (in function-like macro definitions) or
564  /// when determined by other style rules (after unary operators, opening
565  /// parentheses, etc.)
567  };
568 
569  /// \brief Defines in which cases to put a space before opening parentheses.
571 
572  /// \brief If ``true``, spaces may be inserted into ``()``.
574 
575  /// \brief The number of spaces before trailing line comments
576  /// (``//`` - comments).
577  ///
578  /// This does not affect trailing block comments (``/*`` - comments) as
579  /// those commonly have different usage patterns and a number of special
580  /// cases.
582 
583  /// \brief If ``true``, spaces will be inserted after ``<`` and before ``>``
584  /// in template argument lists.
586 
587  /// \brief If ``true``, spaces are inserted inside container literals (e.g.
588  /// ObjC and Javascript array and dict literals).
590 
591  /// \brief If ``true``, spaces may be inserted into C style casts.
593 
594  /// \brief If ``true``, spaces will be inserted after ``(`` and before ``)``.
596 
597  /// \brief If ``true``, spaces will be inserted after ``[`` and before ``]``.
599 
600  /// \brief Supported language standards.
602  /// Use C++03-compatible syntax.
604  /// Use features of C++11 (e.g. ``A<A<int>>`` instead of ``A<A<int> >``).
606  /// Automatic detection based on the input.
608  };
609 
610  /// \brief Format compatible with this standard, e.g. use ``A<A<int> >``
611  /// instead of ``A<A<int>>`` for ``LS_Cpp03``.
613 
614  /// \brief The number of columns used for tab stops.
615  unsigned TabWidth;
616 
617  /// \brief Different ways to use tab in formatting.
618  enum UseTabStyle {
619  /// Never use tab.
621  /// Use tabs only for indentation.
623  /// Use tabs only for line continuation and indentation.
625  /// Use tabs whenever we need to fill whitespace that spans at least from
626  /// one tab stop to the next one.
628  };
629 
630  /// \brief The way to use tab characters in the resulting file.
632 
633  bool operator==(const FormatStyle &R) const {
679  IndentWidth == R.IndentWidth && Language == R.Language &&
710  Standard == R.Standard && TabWidth == R.TabWidth &&
711  UseTab == R.UseTab;
712  }
713 };
714 
715 /// \brief Returns a format style complying with the LLVM coding standards:
716 /// http://llvm.org/docs/CodingStandards.html.
717 FormatStyle getLLVMStyle();
718 
719 /// \brief Returns a format style complying with one of Google's style guides:
720 /// http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml.
721 /// http://google-styleguide.googlecode.com/svn/trunk/javascriptguide.xml.
722 /// https://developers.google.com/protocol-buffers/docs/style.
723 FormatStyle getGoogleStyle(FormatStyle::LanguageKind Language);
724 
725 /// \brief Returns a format style complying with Chromium's style guide:
726 /// http://www.chromium.org/developers/coding-style.
727 FormatStyle getChromiumStyle(FormatStyle::LanguageKind Language);
728 
729 /// \brief Returns a format style complying with Mozilla's style guide:
730 /// https://developer.mozilla.org/en-US/docs/Developer_Guide/Coding_Style.
731 FormatStyle getMozillaStyle();
732 
733 /// \brief Returns a format style complying with Webkit's style guide:
734 /// http://www.webkit.org/coding/coding-style.html
735 FormatStyle getWebKitStyle();
736 
737 /// \brief Returns a format style complying with GNU Coding Standards:
738 /// http://www.gnu.org/prep/standards/standards.html
739 FormatStyle getGNUStyle();
740 
741 /// \brief Returns style indicating formatting should be not applied at all.
742 FormatStyle getNoStyle();
743 
744 /// \brief Gets a predefined style for the specified language by name.
745 ///
746 /// Currently supported names: LLVM, Google, Chromium, Mozilla. Names are
747 /// compared case-insensitively.
748 ///
749 /// Returns ``true`` if the Style has been set.
750 bool getPredefinedStyle(StringRef Name, FormatStyle::LanguageKind Language,
751  FormatStyle *Style);
752 
753 /// \brief Parse configuration from YAML-formatted text.
754 ///
755 /// Style->Language is used to get the base style, if the ``BasedOnStyle``
756 /// option is present.
757 ///
758 /// When ``BasedOnStyle`` is not present, options not present in the YAML
759 /// document, are retained in \p Style.
760 std::error_code parseConfiguration(StringRef Text, FormatStyle *Style);
761 
762 /// \brief Gets configuration in a YAML string.
763 std::string configurationAsText(const FormatStyle &Style);
764 
765 /// \brief Returns the replacements necessary to sort all ``#include`` blocks
766 /// that are affected by ``Ranges``.
767 tooling::Replacements sortIncludes(const FormatStyle &Style, StringRef Code,
769  StringRef FileName,
770  unsigned *Cursor = nullptr);
771 
772 /// \brief Returns the replacements corresponding to applying and formatting
773 /// \p Replaces on success; otheriwse, return an llvm::Error carrying
774 /// llvm::StringError.
775 llvm::Expected<tooling::Replacements>
776 formatReplacements(StringRef Code, const tooling::Replacements &Replaces,
777  const FormatStyle &Style);
778 
779 /// \brief Returns the replacements corresponding to applying \p Replaces and
780 /// cleaning up the code after that on success; otherwise, return an llvm::Error
781 /// carrying llvm::StringError.
782 /// This also inserts a C++ #include directive into the correct block if the
783 /// replacement corresponding to the header insertion has offset UINT_MAX.
784 llvm::Expected<tooling::Replacements>
785 cleanupAroundReplacements(StringRef Code, const tooling::Replacements &Replaces,
786  const FormatStyle &Style);
787 
788 /// \brief Reformats the given \p Ranges in the file \p ID.
789 ///
790 /// Each range is extended on either end to its next bigger logic unit, i.e.
791 /// everything that might influence its formatting or might be influenced by its
792 /// formatting.
793 ///
794 /// Returns the ``Replacements`` necessary to make all \p Ranges comply with
795 /// \p Style.
796 ///
797 /// If ``IncompleteFormat`` is non-null, its value will be set to true if any
798 /// of the affected ranges were not formatted due to a non-recoverable syntax
799 /// error.
800 tooling::Replacements reformat(const FormatStyle &Style,
801  SourceManager &SourceMgr, FileID ID,
803  bool *IncompleteFormat = nullptr);
804 
805 /// \brief Reformats the given \p Ranges in \p Code.
806 ///
807 /// Otherwise identical to the reformat() function using a file ID.
808 tooling::Replacements reformat(const FormatStyle &Style, StringRef Code,
810  StringRef FileName = "<stdin>",
811  bool *IncompleteFormat = nullptr);
812 
813 /// \brief Clean up any erroneous/redundant code in the given \p Ranges in the
814 /// file \p ID.
815 ///
816 /// Returns the ``Replacements`` that clean up all \p Ranges in the file \p ID.
817 tooling::Replacements cleanup(const FormatStyle &Style,
818  SourceManager &SourceMgr, FileID ID,
820 
821 /// \brief Clean up any erroneous/redundant code in the given \p Ranges in \p
822 /// Code.
823 ///
824 /// Otherwise identical to the cleanup() function using a file ID.
825 tooling::Replacements cleanup(const FormatStyle &Style, StringRef Code,
827  StringRef FileName = "<stdin>");
828 
829 /// \brief Returns the ``LangOpts`` that the formatter expects you to set.
830 ///
831 /// \param Style determines specific settings for lexing mode.
832 LangOptions getFormattingLangOpts(const FormatStyle &Style = getLLVMStyle());
833 
834 /// \brief Description to be used for help text for a ``llvm::cl`` option for
835 /// specifying format style. The description is closely related to the operation
836 /// of ``getStyle()``.
837 extern const char *StyleOptionHelpDescription;
838 
839 /// \brief Construct a FormatStyle based on ``StyleName``.
840 ///
841 /// ``StyleName`` can take several forms:
842 /// * "{<key>: <value>, ...}" - Set specic style parameters.
843 /// * "<style name>" - One of the style names supported by
844 /// getPredefinedStyle().
845 /// * "file" - Load style configuration from a file called ``.clang-format``
846 /// located in one of the parent directories of ``FileName`` or the current
847 /// directory if ``FileName`` is empty.
848 ///
849 /// \param[in] StyleName Style name to interpret according to the description
850 /// above.
851 /// \param[in] FileName Path to start search for .clang-format if ``StyleName``
852 /// == "file".
853 /// \param[in] FallbackStyle The name of a predefined style used to fallback to
854 /// in case the style can't be determined from \p StyleName.
855 /// \param[in] FS The underlying file system, in which the file resides. By
856 /// default, the file system is the real file system.
857 ///
858 /// \returns FormatStyle as specified by ``StyleName``. If no style could be
859 /// determined, the default is LLVM Style (see ``getLLVMStyle()``).
860 FormatStyle getStyle(StringRef StyleName, StringRef FileName,
861  StringRef FallbackStyle, vfs::FileSystem *FS = nullptr);
862 
863 // \brief Returns a string representation of ``Language``.
864 inline StringRef getLanguageName(FormatStyle::LanguageKind Language) {
865  switch (Language) {
866  case FormatStyle::LK_Cpp:
867  return "C++";
869  return "Java";
871  return "JavaScript";
873  return "Proto";
874  default:
875  return "Unknown";
876  }
877 }
878 
879 } // end namespace format
880 } // end namespace clang
881 
882 namespace std {
883 template <>
884 struct is_error_code_enum<clang::format::ParseError> : std::true_type {};
885 }
886 
887 #endif // LLVM_CLANG_FORMAT_FORMAT_H
FormatStyle getStyle(StringRef StyleName, StringRef FileName, StringRef FallbackStyle, vfs::FileSystem *FS=nullptr)
Construct a FormatStyle based on StyleName.
Definition: Format.cpp:1695
Always break after the return type of top-level definitions.
Definition: Format.h:179
tooling::Replacements cleanup(const FormatStyle &Style, SourceManager &SourceMgr, FileID ID, ArrayRef< CharSourceRange > Ranges)
Clean up any erroneous/redundant code in the given Ranges in the file ID.
Definition: Format.cpp:1639
Use tabs only for indentation.
Definition: Format.h:622
See documentation of IncludeCategories.
Definition: Format.h:370
PointerAlignmentStyle
The & and * alignment style.
Definition: Format.h:531
bool AfterUnion
Wrap union definitions.
Definition: Format.h:267
Indent in all namespaces.
Definition: Format.h:494
std::string IncludeIsMainRegex
Specify a regular expression of suffixes that are allowed in the file-to-main-include mapping...
Definition: Format.h:419
bool AlwaysBreakBeforeMultilineStrings
If true, always break before multiline string literals.
Definition: Format.h:195
unsigned PenaltyBreakBeforeFirstCallParameter
The penalty for breaking a function call after call(.
Definition: Format.h:512
bool AlignEscapedNewlinesLeft
If true, aligns escaped newlines as far left as possible.
Definition: Format.h:103
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:1383
Should be used for Protocol Buffers (https://developers.google.com/protocol-buffers/).
Definition: Format.h:470
std::set< Replacement > Replacements
A set of Replacements.
Definition: Replacement.h:148
bool IndentCaseLabels
Indent case labels one level from the switch statement.
Definition: Format.h:425
unsigned IndentWidth
The number of columns to use for indentation.
Definition: Format.h:428
bool DisableFormat
Disables formatting completely.
Definition: Format.h:338
bool AlignConsecutiveDeclarations
If true, aligns consecutive declarations.
Definition: Format.h:99
FormatStyle getMozillaStyle()
Returns a format style complying with Mozilla's style guide: https://developer.mozilla.org/en-US/docs/Developer_Guide/Coding_Style.
Definition: Format.cpp:648
DefinitionReturnTypeBreakingStyle AlwaysBreakAfterDefinitionReturnType
The function definition return type breaking style to use.
Definition: Format.h:184
PointerAlignmentStyle PointerAlignment
Pointer and reference alignment style.
Definition: Format.h:541
std::error_code make_error_code(ParseError e)
Definition: Format.cpp:419
Align pointer to the left.
Definition: Format.h:533
Should be used for C, C++, ObjectiveC, ObjectiveC++.
Definition: Format.h:463
unsigned PenaltyBreakFirstLessLess
The penalty for breaking before the first <<.
Definition: Format.h:518
LanguageKind
Supported languages.
Definition: Format.h:459
bool * IncompleteFormat
Definition: Format.cpp:979
bool AfterEnum
Wrap enum definitions.
Definition: Format.h:257
Break after operators.
Definition: Format.h:212
FormatStyle getWebKitStyle()
Returns a format style complying with Webkit's style guide: http://www.webkit.org/coding/coding-style...
Definition: Format.cpp:670
Use tabs whenever we need to fill whitespace that spans at least from one tab stop to the next one...
Definition: Format.h:627
bool operator==(const IncludeCategory &Other) const
Definition: Format.h:375
const char * name() const LLVM_NOEXCEPT override
Definition: Format.cpp:423
bool JavaScriptWrapImports
Whether to wrap JavaScript import/export statements.
Definition: Format.h:449
Like Attach, but break before braces on enum, function, and record definitions.
Definition: Format.h:231
Always break after the return type.
Definition: Format.h:173
The virtual file system interface.
bool AfterObjCDeclaration
Wrap ObjC definitions (@autoreleasepool, interfaces, ..).
Definition: Format.h:263
bool DerivePointerAlignment
If true, analyze the formatted file for the most common alignment of & and *.
Definition: Format.h:335
class LLVM_ALIGNAS(8) DependentTemplateSpecializationType const IdentifierInfo * Name
Represents a template specialization type whose template cannot be resolved, e.g. ...
Definition: Type.h:4549
bool ExperimentalAutoDetectBinPacking
If true, clang-format detects whether function calls and definitions are formatted with one parameter...
Definition: Format.h:350
bool SpaceInEmptyParentheses
If true, spaces may be inserted into ().
Definition: Format.h:573
bool IndentBraces
Indent the wrapped braces themselves.
Definition: Format.h:273
std::string message(int EV) const override
Definition: Format.cpp:427
Should be used for Java.
Definition: Format.h:465
Always break after the return type of function definitions.
Definition: Format.h:177
std::vector< IncludeCategory > IncludeCategories
Regular expressions denoting the different #include categories used for ordering #includes.
Definition: Format.h:406
NamespaceIndentationKind
Different ways to indent namespace contents.
Definition: Format.h:488
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:163
bool BreakAfterJavaFieldAnnotations
Break after each annotation on a field in Java files.
Definition: Format.h:290
Use tabs only for line continuation and indentation.
Definition: Format.h:624
Always use double quotes.
Definition: Format.h:442
bool ConstructorInitializerAllOnOneLineOrOnePerLine
If the constructor initializers don't fit on a line, put each initializer on its own line...
Definition: Format.h:308
unsigned PenaltyBreakComment
The penalty for each line break introduced inside a comment.
Definition: Format.h:515
bool IndentWrappedFunctionNames
Indent if a function definition or declaration is wrapped after the type.
Definition: Format.h:432
std::string Regex
The regular expression that this category matches.
Definition: Format.h:372
bool SpacesInParentheses
If true, spaces will be inserted after ( and before ).
Definition: Format.h:595
Always break after an open bracket, if the parameters don't fit on a single line, e...
Definition: Format.h:70
NamespaceIndentationKind NamespaceIndentation
The indentation used for namespaces.
Definition: Format.h:498
ReturnTypeBreakingStyle AlwaysBreakAfterReturnType
The function declaration return type breaking style to use.
Definition: Format.h:187
bool BreakConstructorInitializersBeforeComma
Always break constructor initializers before commas and align the commas with the colon...
Definition: Format.h:287
bool BinPackArguments
If false, a function call's arguments will either be all on the same line or will have one line each...
Definition: Format.h:203
unsigned ObjCBlockIndentWidth
The number of characters to use for indentation of ObjC blocks.
Definition: Format.h:501
bool SpaceBeforeAssignmentOperators
If false, spaces will be removed before assignment operators.
Definition: Format.h:553
FormatStyle getChromiumStyle(FormatStyle::LanguageKind Language)
Returns a format style complying with Chromium's style guide: http://www.chromium.org/developers/coding-style.
Definition: Format.cpp:629
SpaceBeforeParensOptions SpaceBeforeParens
Defines in which cases to put a space before opening parentheses.
Definition: Format.h:570
FormatStyle getGNUStyle()
Returns a format style complying with GNU Coding Standards: http://www.gnu.org/prep/standards/standar...
Definition: Format.cpp:690
JavaScriptQuoteStyle
Quotation styles for JavaScript strings.
Definition: Format.h:436
Always put a space before opening parentheses, except when it's prohibited by the syntax rules (in fu...
Definition: Format.h:566
bool AlignConsecutiveAssignments
If true, aligns consecutive assignments.
Definition: Format.h:88
unsigned ColumnLimit
The column limit.
Definition: Format.h:300
Never merge functions into a single line.
Definition: Format.h:135
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:1417
bool AllowShortCaseLabelsOnASingleLine
If true, short case labels will be contracted to a single line.
Definition: Format.h:129
int Priority
The priority to assign to this category.
Definition: Format.h:374
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:452
const FormatStyle & Style
Definition: Format.cpp:1311
std::vector< std::string > ForEachMacros
A vector of macros that should be interpreted as foreach loops instead of as function calls...
Definition: Format.h:367
SpaceBeforeParensOptions
Different ways to put a space before opening parentheses.
Definition: Format.h:556
Break before operators that aren't assignments.
Definition: Format.h:214
UseTabStyle UseTab
The way to use tab characters in the resulting file.
Definition: Format.h:631
std::string MacroBlockEnd
A regular expression matching macros that end a block.
Definition: Format.h:482
FormatStyle getLLVMStyle()
Returns a format style complying with the LLVM coding standards: http://llvm.org/docs/CodingStandards...
Definition: Format.cpp:487
Break after return type automatically.
Definition: Format.h:171
std::string CommentPragmas
A regular expression that describes comments with special meaning, which should not be split into lin...
Definition: Format.h:304
Only merge empty functions.
Definition: Format.h:137
Defines the clang::LangOptions interface.
std::string MacroBlockBegin
A regular expression matching macros that start a block.
Definition: Format.h:479
Should be used for JavaScript.
Definition: Format.h:467
Precise control over the wrapping of braces.
Definition: Format.h:251
LangOptions getFormattingLangOpts(const FormatStyle &Style=getLLVMStyle())
Returns the LangOpts that the formatter expects you to set.
Definition: Format.cpp:1655
bool SpacesInContainerLiterals
If true, spaces are inserted inside container literals (e.g.
Definition: Format.h:589
BraceWrappingFlags BraceWrapping
Control of individual brace wrapping cases.
Definition: Format.h:280
bool SpacesInAngles
If true, spaces will be inserted after < and before > in template argument lists. ...
Definition: Format.h:585
bool AlignOperands
If true, horizontally align operands of binary and ternary expressions.
Definition: Format.h:114
bool AfterFunction
Wrap function definitions.
Definition: Format.h:259
Break after return type automatically.
Definition: Format.h:159
Always use single quotes.
Definition: Format.h:440
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's style guides: http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml.
Definition: Format.cpp:573
Don't indent in namespaces.
Definition: Format.h:490
BinaryOperatorStyle
The style of breaking before or after binary operators.
Definition: Format.h:210
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:1599
StringRef getLanguageName(FormatStyle::LanguageKind Language)
Definition: Format.h:864
BraceBreakingStyle BreakBeforeBraces
The brace breaking style to use.
Definition: Format.h:248
Don'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:521
LanguageStandard
Supported language standards.
Definition: Format.h:601
Always attach braces to surrounding context.
Definition: Format.h:225
Align pointer in the middle.
Definition: Format.h:537
StringRef FileName
Definition: Format.cpp:1313
unsigned PenaltyExcessCharacter
The penalty for each character outside of the column limit.
Definition: Format.h:524
bool ReflowComments
If true, clang-format will attempt to re-flow comments.
Definition: Format.h:544
Put a space before opening parentheses only after control statement keywords (for/if/while...).
Definition: Format.h:561
const std::string ID
Automatic detection based on the input.
Definition: Format.h:607
bool BreakBeforeTernaryOperators
If true, ternary operators will be placed after line breaks.
Definition: Format.h:283
unsigned ContinuationIndentWidth
Indent width for line continuations.
Definition: Format.h:315
bool AlwaysBreakTemplateDeclarations
If true, always break after the template<...> of a template declaration.
Definition: Format.h:199
bool AllowShortLoopsOnASingleLine
If true, while (true) continue; can be put on a single line.
Definition: Format.h:153
bool SpacesInCStyleCastParentheses
If true, spaces may be inserted into C style casts.
Definition: Format.h:592
bool SpacesInSquareBrackets
If true, spaces will be inserted after [ and before ].
Definition: Format.h:598
ReturnTypeBreakingStyle
Different ways to break after the function definition or declaration return type. ...
Definition: Format.h:168
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:558
unsigned PenaltyReturnTypeOnItsOwnLine
Penalty for putting the return type of a function onto its own line.
Definition: Format.h:528
Indent only in inner namespaces (nested in other namespaces).
Definition: Format.h:492
std::string configurationAsText(const FormatStyle &Style)
Gets configuration in a YAML string.
Definition: Format.cpp:781
LanguageKind Language
Language, this format style is targeted at.
Definition: Format.h:476
Always break before braces.
Definition: Format.h:236
An opaque identifier used by SourceManager which refers to a source file (MemoryBuffer) along with it...
const char * StyleOptionHelpDescription
Description to be used for help text for a llvm::cl option for specifying format style.
Definition: Format.cpp:1671
ShortFunctionStyle AllowShortFunctionsOnASingleLine
Dependent on the value, int f() { return 0; } can be put on a single line.
Definition: Format.h:146
bool SortIncludes
If true, clang-format will sort #includes.
Definition: Format.h:547
Leave string quotes as they are.
Definition: Format.h:438
Use C++03-compatible syntax.
Definition: Format.h:603
Always break after the return types of top-level functions.
Definition: Format.h:175
Should be used for TableGen code.
Definition: Format.h:472
Use features of C++11 (e.g. A<A<int>> instead of A<A<int> >).
Definition: Format.h:605
bool Cpp11BracedListStyle
If true, format braced lists as best suited for C++11 braced lists.
Definition: Format.h:330
BraceBreakingStyle
Different ways to attach braces to their surrounding context.
Definition: Format.h:223
bool BreakStringLiterals
Allow breaking string literals when formatting.
Definition: Format.h:293
BracketAlignmentStyle
Different styles for aligning after open brackets.
Definition: Format.h:51
Configure each individual brace in BraceWrapping.
Definition: Format.h:244
Merge all functions fitting on a single line.
Definition: Format.h:141
bool operator==(const FormatStyle &R) const
Definition: Format.h:633
Like Attach, but break before functions.
Definition: Format.h:242
bool AfterStruct
Wrap struct definitions.
Definition: Format.h:265
bool AllowAllParametersOfDeclarationOnNextLine
Allow putting all parameters of a function declaration onto the next line even if BinPackParameters i...
Definition: Format.h:121
bool getPredefinedStyle(StringRef Name, FormatStyle::LanguageKind Language, FormatStyle *Style)
Gets a predefined style for the specified language by name.
Definition: Format.cpp:711
unsigned TabWidth
The number of columns used for tab stops.
Definition: Format.h:615
UseTabStyle
Different ways to use tab in formatting.
Definition: Format.h:618
bool SpaceAfterCStyleCast
If true, a space may be inserted after C style casts.
Definition: Format.h:550
JavaScriptQuoteStyle JavaScriptQuotes
The JavaScriptQuoteStyle to use for JavaScript strings.
Definition: Format.h:446
bool AllowShortIfStatementsOnASingleLine
If true, if (a) return; can be put on a single line.
Definition: Format.h:149
Like Attach, but break before function definitions, catch, and else.
Definition: Format.h:234
FormatStyle getNoStyle()
Returns style indicating formatting should be not applied at all.
Definition: Format.cpp:704
Align parameters on the open bracket, e.g.
Definition: Format.h:57
Only merge functions defined inside a class. Implies "empty".
Definition: Format.h:139
LanguageStandard Standard
Format compatible with this standard, e.g.
Definition: Format.h:612
unsigned ConstructorInitializerIndentWidth
The number of characters to use for indentation of constructor initializer lists. ...
Definition: Format.h:312
const std::error_category & getParseCategory()
Definition: Format.cpp:415
BinaryOperatorStyle BreakBeforeBinaryOperators
The way to wrap binary operators.
Definition: Format.h:220
Break before operators.
Definition: Format.h:216
bool ObjCSpaceBeforeProtocolList
Add a space in front of an Objective-C protocol list, i.e.
Definition: Format.h:509
bool AfterControlStatement
Wrap control statements (if/for/while/switch/..).
Definition: Format.h:255
unsigned SpacesBeforeTrailingComments
The number of spaces before trailing line comments (// - comments).
Definition: Format.h:581
bool AllowShortBlocksOnASingleLine
Allows contracting simple braced statements to a single line.
Definition: Format.h:126
bool AlignTrailingComments
If true, aligns trailing comments.
Definition: Format.h:117
ShortFunctionStyle
Different styles for merging short functions containing at most one statement.
Definition: Format.h:133
bool AfterClass
Wrap class definitions.
Definition: Format.h:253
tooling::Replacements reformat(const FormatStyle &Style, SourceManager &SourceMgr, FileID ID, ArrayRef< CharSourceRange > Ranges, bool *IncompleteFormat=nullptr)
Reformats the given Ranges in the file ID.
Definition: Format.cpp:1614
StringRef Text
Definition: Format.cpp:1195
Always break before braces and add an extra level of indentation to braces of control statements...
Definition: Format.h:240
std::error_code parseConfiguration(StringRef Text, FormatStyle *Style)
Parse configuration from YAML-formatted text.
Definition: Format.cpp:735
Align pointer to the right.
Definition: Format.h:535
DefinitionReturnTypeBreakingStyle
Different ways to break after the function definition return type.
Definition: Format.h:156
Always break after the return type.
Definition: Format.h:161
unsigned MaxEmptyLinesToKeep
The maximum number of consecutive empty lines to keep.
Definition: Format.h:485
bool AfterNamespace
Wrap namespace definitions.
Definition: Format.h:261
This class handles loading and caching of source files into memory.
Like Attach, but break before braces on function, namespace and class definitions.
Definition: Format.h:228
bool BinPackParameters
If false, a function declaration's or function definition's parameters will either all be on the same...
Definition: Format.h:207