1 //===--- Format.h - Format C++ code -----------------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
11 /// Various functions to configurably format source code.
13 //===----------------------------------------------------------------------===//
15 #ifndef LLVM_CLANG_FORMAT_FORMAT_H
16 #define LLVM_CLANG_FORMAT_FORMAT_H
18 #include "clang/Frontend/FrontendAction.h"
19 #include "clang/Tooling/Refactoring.h"
20 #include "llvm/Support/system_error.h"
26 class DiagnosticConsumer;
30 /// \brief The \c FormatStyle is used to configure the formatting to follow
31 /// specific guidelines.
33 /// \brief The column limit.
35 /// A column limit of \c 0 means that there is no column limit. In this case,
36 /// clang-format will respect the input's line breaking decisions within
40 /// \brief The maximum number of consecutive empty lines to keep.
41 unsigned MaxEmptyLinesToKeep;
43 /// \brief The penalty for each line break introduced inside a comment.
44 unsigned PenaltyBreakComment;
46 /// \brief The penalty for each line break introduced inside a string literal.
47 unsigned PenaltyBreakString;
49 /// \brief The penalty for each character outside of the column limit.
50 unsigned PenaltyExcessCharacter;
52 /// \brief The penalty for breaking before the first \c <<.
53 unsigned PenaltyBreakFirstLessLess;
55 /// \brief The penalty for breaking a function call after "call(".
56 unsigned PenaltyBreakBeforeFirstCallParameter;
58 /// \brief Set whether & and * bind to the type as opposed to the variable.
59 bool PointerBindsToType;
61 /// \brief If \c true, analyze the formatted file for the most common binding.
62 bool DerivePointerBinding;
64 /// \brief The extra indent or outdent of access modifiers, e.g. \c public:.
65 int AccessModifierOffset;
67 /// \brief Supported language standards.
68 enum LanguageStandard {
69 /// Use C++03-compatible syntax.
71 /// Use features of C++11 (e.g. \c A<A<int>> instead of
72 /// <tt>A<A<int> ></tt>).
74 /// Automatic detection based on the input.
78 /// \brief Format compatible with this standard, e.g. use
79 /// <tt>A<A<int> ></tt> instead of \c A<A<int>> for LS_Cpp03.
80 LanguageStandard Standard;
82 /// \brief Indent case labels one level from the switch statement.
84 /// When \c false, use the same indentation level as for the switch statement.
85 /// Switch statement body is always indented one level more than case labels.
86 bool IndentCaseLabels;
88 /// \brief Different ways to indent namespace contents.
89 enum NamespaceIndentationKind {
90 /// Don't indent in namespaces.
92 /// Indent only in inner namespaces (nested in other namespaces).
94 /// Indent in all namespaces.
98 /// \brief The indentation used for namespaces.
99 NamespaceIndentationKind NamespaceIndentation;
101 /// \brief The number of spaces to before trailing line comments.
102 unsigned SpacesBeforeTrailingComments;
104 /// \brief If \c false, a function call's or function definition's parameters
105 /// will either all be on the same line or will have one line each.
106 bool BinPackParameters;
108 /// \brief If \c true, clang-format detects whether function calls and
109 /// definitions are formatted with one parameter per line.
111 /// Each call can be bin-packed, one-per-line or inconclusive. If it is
112 /// inconclusive, e.g. completely on one line, but a decision needs to be
113 /// made, clang-format analyzes whether there are other bin-packed cases in
114 /// the input file and act accordingly.
116 /// NOTE: This is an experimental flag, that might go away or be renamed. Do
117 /// not use this in config files, etc. Use at your own risk.
118 bool ExperimentalAutoDetectBinPacking;
120 /// \brief Allow putting all parameters of a function declaration onto
121 /// the next line even if \c BinPackParameters is \c false.
122 bool AllowAllParametersOfDeclarationOnNextLine;
124 /// \brief Penalty for putting the return type of a function onto its own
126 unsigned PenaltyReturnTypeOnItsOwnLine;
128 /// \brief If the constructor initializers don't fit on a line, put each
129 /// initializer on its own line.
130 bool ConstructorInitializerAllOnOneLineOrOnePerLine;
132 /// \brief Always break constructor initializers before commas and align
133 /// the commas with the colon.
134 bool BreakConstructorInitializersBeforeComma;
136 /// \brief If \c true, <tt>if (a) return;</tt> can be put on a single
138 bool AllowShortIfStatementsOnASingleLine;
140 /// \brief If \c true, <tt>while (true) continue;</tt> can be put on a
142 bool AllowShortLoopsOnASingleLine;
144 /// \brief Add a space in front of an Objective-C protocol list, i.e. use
145 /// <tt>Foo <Protocol></tt> instead of \c Foo<Protocol>.
146 bool ObjCSpaceBeforeProtocolList;
148 /// \brief If \c true, aligns trailing comments.
149 bool AlignTrailingComments;
151 /// \brief If \c true, aligns escaped newlines as far left as possible.
152 /// Otherwise puts them into the right-most column.
153 bool AlignEscapedNewlinesLeft;
155 /// \brief The number of columns to use for indentation.
156 unsigned IndentWidth;
158 /// \brief The number of columns used for tab stops.
161 /// \brief The number of characters to use for indentation of constructor
162 /// initializer lists.
163 unsigned ConstructorInitializerIndentWidth;
165 /// \brief If \c true, always break after the <tt>template<...></tt> of a
166 /// template declaration.
167 bool AlwaysBreakTemplateDeclarations;
169 /// \brief If \c true, always break before multiline string literals.
170 bool AlwaysBreakBeforeMultilineStrings;
172 /// \brief Different ways to use tab in formatting.
176 /// Use tabs only for indentation.
178 /// Use tabs whenever we need to fill whitespace that spans at least from
179 /// one tab stop to the next one.
183 /// \brief The way to use tab characters in the resulting file.
186 /// \brief If \c true, binary operators will be placed after line breaks.
187 bool BreakBeforeBinaryOperators;
189 /// \brief If \c true, ternary operators will be placed after line breaks.
190 bool BreakBeforeTernaryOperators;
192 /// \brief Different ways to attach braces to their surrounding context.
193 enum BraceBreakingStyle {
194 /// Always attach braces to surrounding context.
196 /// Like \c Attach, but break before braces on function, namespace and
197 /// class definitions.
199 /// Like \c Attach, but break before function definitions.
201 /// Always break before braces.
205 /// \brief The brace breaking style to use.
206 BraceBreakingStyle BreakBeforeBraces;
208 /// \brief If \c true, format braced lists as best suited for C++11 braced
211 /// Important differences:
212 /// - No spaces inside the braced list.
213 /// - No line break before the closing brace.
214 /// - Indentation with the continuation indent, not with the block indent.
216 /// Fundamentally, C++11 braced lists are formatted exactly like function
217 /// calls would be formatted in their place. If the braced list follows a name
218 /// (e.g. a type or variable name), clang-format formats as if the \c {} were
219 /// the parentheses of a function call with that name. If there is no name,
220 /// a zero-length name is assumed.
221 bool Cpp11BracedListStyle;
223 /// \brief If \c true, indent when breaking function declarations which
224 /// are not also definitions after the type.
225 bool IndentFunctionDeclarationAfterType;
227 /// \brief If \c true, spaces will be inserted after '(' and before ')'.
228 bool SpacesInParentheses;
230 /// \brief If \c true, spaces will be inserted after '<' and before '>' in
231 /// template argument lists
234 /// \brief If \c false, spaces may be inserted into '()'.
235 bool SpaceInEmptyParentheses;
237 /// \brief If \c false, spaces may be inserted into C style casts.
238 bool SpacesInCStyleCastParentheses;
240 /// \brief If \c true, spaces will be inserted between 'for'/'if'/'while'/...
242 bool SpaceAfterControlStatementKeyword;
244 /// \brief If \c false, spaces will be removed before assignment operators.
245 bool SpaceBeforeAssignmentOperators;
247 /// \brief Indent width for line continuations.
248 unsigned ContinuationIndentWidth;
250 bool operator==(const FormatStyle &R) const {
251 return AccessModifierOffset == R.AccessModifierOffset &&
252 ConstructorInitializerIndentWidth ==
253 R.ConstructorInitializerIndentWidth &&
254 AlignEscapedNewlinesLeft == R.AlignEscapedNewlinesLeft &&
255 AlignTrailingComments == R.AlignTrailingComments &&
256 AllowAllParametersOfDeclarationOnNextLine ==
257 R.AllowAllParametersOfDeclarationOnNextLine &&
258 AllowShortIfStatementsOnASingleLine ==
259 R.AllowShortIfStatementsOnASingleLine &&
260 AllowShortLoopsOnASingleLine == R.AllowShortLoopsOnASingleLine &&
261 AlwaysBreakTemplateDeclarations ==
262 R.AlwaysBreakTemplateDeclarations &&
263 AlwaysBreakBeforeMultilineStrings ==
264 R.AlwaysBreakBeforeMultilineStrings &&
265 BinPackParameters == R.BinPackParameters &&
266 BreakBeforeBinaryOperators == R.BreakBeforeBinaryOperators &&
267 BreakBeforeTernaryOperators == R.BreakBeforeTernaryOperators &&
268 BreakBeforeBraces == R.BreakBeforeBraces &&
269 BreakConstructorInitializersBeforeComma ==
270 R.BreakConstructorInitializersBeforeComma &&
271 ColumnLimit == R.ColumnLimit &&
272 ConstructorInitializerAllOnOneLineOrOnePerLine ==
273 R.ConstructorInitializerAllOnOneLineOrOnePerLine &&
274 DerivePointerBinding == R.DerivePointerBinding &&
275 ExperimentalAutoDetectBinPacking ==
276 R.ExperimentalAutoDetectBinPacking &&
277 IndentCaseLabels == R.IndentCaseLabels &&
278 IndentFunctionDeclarationAfterType ==
279 R.IndentFunctionDeclarationAfterType &&
280 IndentWidth == R.IndentWidth &&
281 MaxEmptyLinesToKeep == R.MaxEmptyLinesToKeep &&
282 NamespaceIndentation == R.NamespaceIndentation &&
283 ObjCSpaceBeforeProtocolList == R.ObjCSpaceBeforeProtocolList &&
284 PenaltyBreakComment == R.PenaltyBreakComment &&
285 PenaltyBreakFirstLessLess == R.PenaltyBreakFirstLessLess &&
286 PenaltyBreakString == R.PenaltyBreakString &&
287 PenaltyExcessCharacter == R.PenaltyExcessCharacter &&
288 PenaltyReturnTypeOnItsOwnLine == R.PenaltyReturnTypeOnItsOwnLine &&
289 PointerBindsToType == R.PointerBindsToType &&
290 SpacesBeforeTrailingComments == R.SpacesBeforeTrailingComments &&
291 Cpp11BracedListStyle == R.Cpp11BracedListStyle &&
292 Standard == R.Standard && TabWidth == R.TabWidth &&
293 UseTab == R.UseTab && SpacesInParentheses == R.SpacesInParentheses &&
294 SpacesInAngles == R.SpacesInAngles &&
295 SpaceInEmptyParentheses == R.SpaceInEmptyParentheses &&
296 SpacesInCStyleCastParentheses == R.SpacesInCStyleCastParentheses &&
297 SpaceAfterControlStatementKeyword ==
298 R.SpaceAfterControlStatementKeyword &&
299 SpaceBeforeAssignmentOperators == R.SpaceBeforeAssignmentOperators &&
300 ContinuationIndentWidth == R.ContinuationIndentWidth;
304 /// \brief Returns a format style complying with the LLVM coding standards:
305 /// http://llvm.org/docs/CodingStandards.html.
306 FormatStyle getLLVMStyle();
308 /// \brief Returns a format style complying with Google's C++ style guide:
309 /// http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml.
310 FormatStyle getGoogleStyle();
312 /// \brief Returns a format style complying with Chromium's style guide:
313 /// http://www.chromium.org/developers/coding-style.
314 FormatStyle getChromiumStyle();
316 /// \brief Returns a format style complying with Mozilla's style guide:
317 /// https://developer.mozilla.org/en-US/docs/Developer_Guide/Coding_Style.
318 FormatStyle getMozillaStyle();
320 /// \brief Returns a format style complying with Webkit's style guide:
321 /// http://www.webkit.org/coding/coding-style.html
322 FormatStyle getWebKitStyle();
324 /// \brief Gets a predefined style by name.
326 /// Currently supported names: LLVM, Google, Chromium, Mozilla. Names are
327 /// compared case-insensitively.
329 /// Returns \c true if the Style has been set.
330 bool getPredefinedStyle(StringRef Name, FormatStyle *Style);
332 /// \brief Parse configuration from YAML-formatted text.
333 llvm::error_code parseConfiguration(StringRef Text, FormatStyle *Style);
335 /// \brief Gets configuration in a YAML string.
336 std::string configurationAsText(const FormatStyle &Style);
338 /// \brief Reformats the given \p Ranges in the token stream coming out of
341 /// Each range is extended on either end to its next bigger logic unit, i.e.
342 /// everything that might influence its formatting or might be influenced by its
345 /// Returns the \c Replacements necessary to make all \p Ranges comply with
347 tooling::Replacements reformat(const FormatStyle &Style, Lexer &Lex,
348 SourceManager &SourceMgr,
349 std::vector<CharSourceRange> Ranges);
351 /// \brief Reformats the given \p Ranges in \p Code.
353 /// Otherwise identical to the reformat() function consuming a \c Lexer.
354 tooling::Replacements reformat(const FormatStyle &Style, StringRef Code,
355 std::vector<tooling::Range> Ranges,
356 StringRef FileName = "<stdin>");
358 /// \brief Returns the \c LangOpts that the formatter expects you to set.
360 /// \param Standard determines lexing mode: LC_Cpp11 and LS_Auto turn on C++11
361 /// lexing mode, LS_Cpp03 - C++03 mode.
362 LangOptions getFormattingLangOpts(FormatStyle::LanguageStandard Standard =
363 FormatStyle::LS_Cpp11);
365 /// \brief Description to be used for help text for a llvm::cl option for
366 /// specifying format style. The description is closely related to the operation
368 extern const char *StyleOptionHelpDescription;
370 /// \brief Construct a FormatStyle based on \c StyleName.
372 /// \c StyleName can take several forms:
373 /// \li "{<key>: <value>, ...}" - Set specic style parameters.
374 /// \li "<style name>" - One of the style names supported by
375 /// getPredefinedStyle().
376 /// \li "file" - Load style configuration from a file called '.clang-format'
377 /// located in one of the parent directories of \c FileName or the current
378 /// directory if \c FileName is empty.
380 /// \param[in] StyleName Style name to interpret according to the description
382 /// \param[in] FileName Path to start search for .clang-format if \c StyleName
385 /// \returns FormatStyle as specified by \c StyleName. If no style could be
386 /// determined, the default is LLVM Style (see getLLVMStyle()).
387 FormatStyle getStyle(StringRef StyleName, StringRef FileName);
389 } // end namespace format
390 } // end namespace clang
392 #endif // LLVM_CLANG_FORMAT_FORMAT_H