Bug Summary

File:tools/clang/include/clang/Format/Format.h
Warning:line 46, column 8
Excessive padding in 'struct clang::format::FormatStyle' (47 padding bytes, where 7 is optimal). Optimal fields order: StyleSet, ForEachMacros, IncludeCategories, RawStringFormats, CommentPragmas, IncludeIsMainRegex, MacroBlockBegin, MacroBlockEnd, AccessModifierOffset, AlignAfterOpenBracket, AlignEscapedNewlines, AllowShortFunctionsOnASingleLine, AlwaysBreakAfterDefinitionReturnType, AlwaysBreakAfterReturnType, BreakBeforeBinaryOperators, BreakBeforeBraces, BreakConstructorInitializers, ColumnLimit, ConstructorInitializerIndentWidth, ContinuationIndentWidth, IncludeBlocks, IndentPPDirectives, IndentWidth, JavaScriptQuotes, Language, MaxEmptyLinesToKeep, NamespaceIndentation, ObjCBinPackProtocolList, ObjCBlockIndentWidth, PenaltyBreakAssignment, PenaltyBreakBeforeFirstCallParameter, PenaltyBreakComment, PenaltyBreakFirstLessLess, PenaltyBreakString, PenaltyExcessCharacter, PenaltyReturnTypeOnItsOwnLine, PointerAlignment, SpaceBeforeParens, SpacesBeforeTrailingComments, Standard, TabWidth, UseTab, AlignConsecutiveAssignments, AlignConsecutiveDeclarations, AlignOperands, AlignTrailingComments, AllowAllParametersOfDeclarationOnNextLine, AllowShortBlocksOnASingleLine, AllowShortCaseLabelsOnASingleLine, AllowShortIfStatementsOnASingleLine, AllowShortLoopsOnASingleLine, AlwaysBreakBeforeMultilineStrings, AlwaysBreakTemplateDeclarations, BinPackArguments, BinPackParameters, BreakBeforeTernaryOperators, BreakAfterJavaFieldAnnotations, BreakStringLiterals, BreakBeforeInheritanceComma, CompactNamespaces, ConstructorInitializerAllOnOneLineOrOnePerLine, Cpp11BracedListStyle, DerivePointerAlignment, DisableFormat, ExperimentalAutoDetectBinPacking, FixNamespaceComments, IndentCaseLabels, IndentWrappedFunctionNames, JavaScriptWrapImports, KeepEmptyLinesAtTheStartOfBlocks, ObjCSpaceAfterProperty, ObjCSpaceBeforeProtocolList, ReflowComments, SortIncludes, SortUsingDeclarations, SpaceAfterCStyleCast, SpaceAfterTemplateKeyword, SpaceBeforeAssignmentOperators, SpaceInEmptyParentheses, SpacesInAngles, SpacesInContainerLiterals, SpacesInCStyleCastParentheses, SpacesInParentheses, SpacesInSquareBrackets, BraceWrapping, consider reordering the fields or adding explicit padding members

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name ClangChangeNamespace.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-eagerly-assume -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -mrelocation-model pic -pic-level 2 -mthread-model posix -relaxed-aliasing -fmath-errno -masm-verbose -mconstructor-aliases -munwind-tables -fuse-init-array -target-cpu x86-64 -dwarf-column-info -debugger-tuning=gdb -momit-leaf-frame-pointer -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-7/lib/clang/7.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-7~svn325118/build-llvm/tools/clang/tools/extra/change-namespace/tool -I /build/llvm-toolchain-snapshot-7~svn325118/tools/clang/tools/extra/change-namespace/tool -I /build/llvm-toolchain-snapshot-7~svn325118/tools/clang/include -I /build/llvm-toolchain-snapshot-7~svn325118/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-7~svn325118/build-llvm/include -I /build/llvm-toolchain-snapshot-7~svn325118/include -I /build/llvm-toolchain-snapshot-7~svn325118/tools/clang/tools/extra/change-namespace/tool/.. -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/c++/7.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/x86_64-linux-gnu/c++/7.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/x86_64-linux-gnu/c++/7.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/c++/7.3.0/backward -internal-isystem /usr/include/clang/7.0.0/include/ -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-7/lib/clang/7.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++11 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-7~svn325118/build-llvm/tools/clang/tools/extra/change-namespace/tool -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -fobjc-runtime=gcc -fno-common -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-checker optin.performance.Padding -analyzer-output=html -analyzer-config stable-report-filename=true -o /tmp/scan-build-2018-02-14-150435-17243-1 -x c++ /build/llvm-toolchain-snapshot-7~svn325118/tools/clang/tools/extra/change-namespace/tool/ClangChangeNamespace.cpp
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
23namespace clang {
24
25class Lexer;
26class SourceManager;
27class DiagnosticConsumer;
28
29namespace vfs {
30class FileSystem;
31}
32
33namespace format {
34
35enum class ParseError { Success = 0, Error, Unsuitable };
36class ParseErrorCategory final : public std::error_category {
37public:
38 const char *name() const noexcept override;
39 std::string message(int EV) const override;
40};
41const std::error_category &getParseCategory();
42std::error_code make_error_code(ParseError e);
43
44/// \brief The ``FormatStyle`` is used to configure the formatting to follow
45/// specific guidelines.
46struct FormatStyle {
Excessive padding in 'struct clang::format::FormatStyle' (47 padding bytes, where 7 is optimal). Optimal fields order: StyleSet, ForEachMacros, IncludeCategories, RawStringFormats, CommentPragmas, IncludeIsMainRegex, MacroBlockBegin, MacroBlockEnd, AccessModifierOffset, AlignAfterOpenBracket, AlignEscapedNewlines, AllowShortFunctionsOnASingleLine, AlwaysBreakAfterDefinitionReturnType, AlwaysBreakAfterReturnType, BreakBeforeBinaryOperators, BreakBeforeBraces, BreakConstructorInitializers, ColumnLimit, ConstructorInitializerIndentWidth, ContinuationIndentWidth, IncludeBlocks, IndentPPDirectives, IndentWidth, JavaScriptQuotes, Language, MaxEmptyLinesToKeep, NamespaceIndentation, ObjCBinPackProtocolList, ObjCBlockIndentWidth, PenaltyBreakAssignment, PenaltyBreakBeforeFirstCallParameter, PenaltyBreakComment, PenaltyBreakFirstLessLess, PenaltyBreakString, PenaltyExcessCharacter, PenaltyReturnTypeOnItsOwnLine, PointerAlignment, SpaceBeforeParens, SpacesBeforeTrailingComments, Standard, TabWidth, UseTab, AlignConsecutiveAssignments, AlignConsecutiveDeclarations, AlignOperands, AlignTrailingComments, AllowAllParametersOfDeclarationOnNextLine, AllowShortBlocksOnASingleLine, AllowShortCaseLabelsOnASingleLine, AllowShortIfStatementsOnASingleLine, AllowShortLoopsOnASingleLine, AlwaysBreakBeforeMultilineStrings, AlwaysBreakTemplateDeclarations, BinPackArguments, BinPackParameters, BreakBeforeTernaryOperators, BreakAfterJavaFieldAnnotations, BreakStringLiterals, BreakBeforeInheritanceComma, CompactNamespaces, ConstructorInitializerAllOnOneLineOrOnePerLine, Cpp11BracedListStyle, DerivePointerAlignment, DisableFormat, ExperimentalAutoDetectBinPacking, FixNamespaceComments, IndentCaseLabels, IndentWrappedFunctionNames, JavaScriptWrapImports, KeepEmptyLinesAtTheStartOfBlocks, ObjCSpaceAfterProperty, ObjCSpaceBeforeProtocolList, ReflowComments, SortIncludes, SortUsingDeclarations, SpaceAfterCStyleCast, SpaceAfterTemplateKeyword, SpaceBeforeAssignmentOperators, SpaceInEmptyParentheses, SpacesInAngles, SpacesInContainerLiterals, SpacesInCStyleCastParentheses, SpacesInParentheses, SpacesInSquareBrackets, BraceWrapping, consider reordering the fields or adding explicit padding members
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 Different styles for aligning escaped newlines.
102 enum EscapedNewlineAlignmentStyle {
103 /// \brief Don't align escaped newlines.
104 /// \code
105 /// #define A \
106 /// int aaaa; \
107 /// int b; \
108 /// int dddddddddd;
109 /// \endcode
110 ENAS_DontAlign,
111 /// \brief Align escaped newlines as far left as possible.
112 /// \code
113 /// true:
114 /// #define A \
115 /// int aaaa; \
116 /// int b; \
117 /// int dddddddddd;
118 ///
119 /// false:
120 /// \endcode
121 ENAS_Left,
122 /// \brief Align escaped newlines in the right-most column.
123 /// \code
124 /// #define A \
125 /// int aaaa; \
126 /// int b; \
127 /// int dddddddddd;
128 /// \endcode
129 ENAS_Right,
130 };
131
132 /// \brief Options for aligning backslashes in escaped newlines.
133 EscapedNewlineAlignmentStyle AlignEscapedNewlines;
134
135 /// \brief If ``true``, horizontally align operands of binary and ternary
136 /// expressions.
137 ///
138 /// Specifically, this aligns operands of a single expression that needs to be
139 /// split over multiple lines, e.g.:
140 /// \code
141 /// int aaa = bbbbbbbbbbbbbbb +
142 /// ccccccccccccccc;
143 /// \endcode
144 bool AlignOperands;
145
146 /// \brief If ``true``, aligns trailing comments.
147 /// \code
148 /// true: false:
149 /// int a; // My comment a vs. int a; // My comment a
150 /// int b = 2; // comment b int b = 2; // comment about b
151 /// \endcode
152 bool AlignTrailingComments;
153
154 /// \brief If the function declaration doesn't fit on a line,
155 /// allow putting all parameters of a function declaration onto
156 /// the next line even if ``BinPackParameters`` is ``false``.
157 /// \code
158 /// true:
159 /// void myFunction(
160 /// int a, int b, int c, int d, int e);
161 ///
162 /// false:
163 /// void myFunction(int a,
164 /// int b,
165 /// int c,
166 /// int d,
167 /// int e);
168 /// \endcode
169 bool AllowAllParametersOfDeclarationOnNextLine;
170
171 /// \brief Allows contracting simple braced statements to a single line.
172 ///
173 /// E.g., this allows ``if (a) { return; }`` to be put on a single line.
174 bool AllowShortBlocksOnASingleLine;
175
176 /// \brief If ``true``, short case labels will be contracted to a single line.
177 /// \code
178 /// true: false:
179 /// switch (a) { vs. switch (a) {
180 /// case 1: x = 1; break; case 1:
181 /// case 2: return; x = 1;
182 /// } break;
183 /// case 2:
184 /// return;
185 /// }
186 /// \endcode
187 bool AllowShortCaseLabelsOnASingleLine;
188
189 /// \brief Different styles for merging short functions containing at most one
190 /// statement.
191 enum ShortFunctionStyle {
192 /// \brief Never merge functions into a single line.
193 SFS_None,
194 /// \brief Only merge functions defined inside a class. Same as "inline",
195 /// except it does not implies "empty": i.e. top level empty functions
196 /// are not merged either.
197 /// \code
198 /// class Foo {
199 /// void f() { foo(); }
200 /// };
201 /// void f() {
202 /// foo();
203 /// }
204 /// void f() {
205 /// }
206 /// \endcode
207 SFS_InlineOnly,
208 /// \brief Only merge empty functions.
209 /// \code
210 /// void f() {}
211 /// void f2() {
212 /// bar2();
213 /// }
214 /// \endcode
215 SFS_Empty,
216 /// \brief Only merge functions defined inside a class. Implies "empty".
217 /// \code
218 /// class Foo {
219 /// void f() { foo(); }
220 /// };
221 /// void f() {
222 /// foo();
223 /// }
224 /// void f() {}
225 /// \endcode
226 SFS_Inline,
227 /// \brief Merge all functions fitting on a single line.
228 /// \code
229 /// class Foo {
230 /// void f() { foo(); }
231 /// };
232 /// void f() { bar(); }
233 /// \endcode
234 SFS_All,
235 };
236
237 /// \brief Dependent on the value, ``int f() { return 0; }`` can be put on a
238 /// single line.
239 ShortFunctionStyle AllowShortFunctionsOnASingleLine;
240
241 /// \brief If ``true``, ``if (a) return;`` can be put on a single line.
242 bool AllowShortIfStatementsOnASingleLine;
243
244 /// \brief If ``true``, ``while (true) continue;`` can be put on a single
245 /// line.
246 bool AllowShortLoopsOnASingleLine;
247
248 /// \brief Different ways to break after the function definition return type.
249 /// This option is **deprecated** and is retained for backwards compatibility.
250 enum DefinitionReturnTypeBreakingStyle {
251 /// Break after return type automatically.
252 /// ``PenaltyReturnTypeOnItsOwnLine`` is taken into account.
253 DRTBS_None,
254 /// Always break after the return type.
255 DRTBS_All,
256 /// Always break after the return types of top-level functions.
257 DRTBS_TopLevel,
258 };
259
260 /// \brief Different ways to break after the function definition or
261 /// declaration return type.
262 enum ReturnTypeBreakingStyle {
263 /// Break after return type automatically.
264 /// ``PenaltyReturnTypeOnItsOwnLine`` is taken into account.
265 /// \code
266 /// class A {
267 /// int f() { return 0; };
268 /// };
269 /// int f();
270 /// int f() { return 1; }
271 /// \endcode
272 RTBS_None,
273 /// Always break after the return type.
274 /// \code
275 /// class A {
276 /// int
277 /// f() {
278 /// return 0;
279 /// };
280 /// };
281 /// int
282 /// f();
283 /// int
284 /// f() {
285 /// return 1;
286 /// }
287 /// \endcode
288 RTBS_All,
289 /// Always break after the return types of top-level functions.
290 /// \code
291 /// class A {
292 /// int f() { return 0; };
293 /// };
294 /// int
295 /// f();
296 /// int
297 /// f() {
298 /// return 1;
299 /// }
300 /// \endcode
301 RTBS_TopLevel,
302 /// Always break after the return type of function definitions.
303 /// \code
304 /// class A {
305 /// int
306 /// f() {
307 /// return 0;
308 /// };
309 /// };
310 /// int f();
311 /// int
312 /// f() {
313 /// return 1;
314 /// }
315 /// \endcode
316 RTBS_AllDefinitions,
317 /// Always break after the return type of top-level definitions.
318 /// \code
319 /// class A {
320 /// int f() { return 0; };
321 /// };
322 /// int f();
323 /// int
324 /// f() {
325 /// return 1;
326 /// }
327 /// \endcode
328 RTBS_TopLevelDefinitions,
329 };
330
331 /// \brief The function definition return type breaking style to use. This
332 /// option is **deprecated** and is retained for backwards compatibility.
333 DefinitionReturnTypeBreakingStyle AlwaysBreakAfterDefinitionReturnType;
334
335 /// \brief The function declaration return type breaking style to use.
336 ReturnTypeBreakingStyle AlwaysBreakAfterReturnType;
337
338 /// \brief If ``true``, always break before multiline string literals.
339 ///
340 /// This flag is mean to make cases where there are multiple multiline strings
341 /// in a file look more consistent. Thus, it will only take effect if wrapping
342 /// the string at that point leads to it being indented
343 /// ``ContinuationIndentWidth`` spaces from the start of the line.
344 /// \code
345 /// true: false:
346 /// aaaa = vs. aaaa = "bbbb"
347 /// "bbbb" "cccc";
348 /// "cccc";
349 /// \endcode
350 bool AlwaysBreakBeforeMultilineStrings;
351
352 /// \brief If ``true``, always break after the ``template<...>`` of a template
353 /// declaration.
354 /// \code
355 /// true: false:
356 /// template <typename T> vs. template <typename T> class C {};
357 /// class C {};
358 /// \endcode
359 bool AlwaysBreakTemplateDeclarations;
360
361 /// \brief If ``false``, a function call's arguments will either be all on the
362 /// same line or will have one line each.
363 /// \code
364 /// true:
365 /// void f() {
366 /// f(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaa,
367 /// aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);
368 /// }
369 ///
370 /// false:
371 /// void f() {
372 /// f(aaaaaaaaaaaaaaaaaaaa,
373 /// aaaaaaaaaaaaaaaaaaaa,
374 /// aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);
375 /// }
376 /// \endcode
377 bool BinPackArguments;
378
379 /// \brief If ``false``, a function declaration's or function definition's
380 /// parameters will either all be on the same line or will have one line each.
381 /// \code
382 /// true:
383 /// void f(int aaaaaaaaaaaaaaaaaaaa, int aaaaaaaaaaaaaaaaaaaa,
384 /// int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}
385 ///
386 /// false:
387 /// void f(int aaaaaaaaaaaaaaaaaaaa,
388 /// int aaaaaaaaaaaaaaaaaaaa,
389 /// int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}
390 /// \endcode
391 bool BinPackParameters;
392
393 /// \brief The style of wrapping parameters on the same line (bin-packed) or
394 /// on one line each.
395 enum BinPackStyle {
396 /// Automatically determine parameter bin-packing behavior.
397 BPS_Auto,
398 /// Always bin-pack parameters.
399 BPS_Always,
400 /// Never bin-pack parameters.
401 BPS_Never,
402 };
403
404 /// \brief The style of breaking before or after binary operators.
405 enum BinaryOperatorStyle {
406 /// Break after operators.
407 /// \code
408 /// LooooooooooongType loooooooooooooooooooooongVariable =
409 /// someLooooooooooooooooongFunction();
410 ///
411 /// bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +
412 /// aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==
413 /// aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa &&
414 /// aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >
415 /// ccccccccccccccccccccccccccccccccccccccccc;
416 /// \endcode
417 BOS_None,
418 /// Break before operators that aren't assignments.
419 /// \code
420 /// LooooooooooongType loooooooooooooooooooooongVariable =
421 /// someLooooooooooooooooongFunction();
422 ///
423 /// bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
424 /// + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
425 /// == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
426 /// && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
427 /// > ccccccccccccccccccccccccccccccccccccccccc;
428 /// \endcode
429 BOS_NonAssignment,
430 /// Break before operators.
431 /// \code
432 /// LooooooooooongType loooooooooooooooooooooongVariable
433 /// = someLooooooooooooooooongFunction();
434 ///
435 /// bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
436 /// + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
437 /// == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
438 /// && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
439 /// > ccccccccccccccccccccccccccccccccccccccccc;
440 /// \endcode
441 BOS_All,
442 };
443
444 /// \brief The way to wrap binary operators.
445 BinaryOperatorStyle BreakBeforeBinaryOperators;
446
447 /// \brief Different ways to attach braces to their surrounding context.
448 enum BraceBreakingStyle {
449 /// Always attach braces to surrounding context.
450 /// \code
451 /// try {
452 /// foo();
453 /// } catch () {
454 /// }
455 /// void foo() { bar(); }
456 /// class foo {};
457 /// if (foo()) {
458 /// } else {
459 /// }
460 /// enum X : int { A, B };
461 /// \endcode
462 BS_Attach,
463 /// Like ``Attach``, but break before braces on function, namespace and
464 /// class definitions.
465 /// \code
466 /// try {
467 /// foo();
468 /// } catch () {
469 /// }
470 /// void foo() { bar(); }
471 /// class foo
472 /// {
473 /// };
474 /// if (foo()) {
475 /// } else {
476 /// }
477 /// enum X : int { A, B };
478 /// \endcode
479 BS_Linux,
480 /// Like ``Attach``, but break before braces on enum, function, and record
481 /// definitions.
482 /// \code
483 /// try {
484 /// foo();
485 /// } catch () {
486 /// }
487 /// void foo() { bar(); }
488 /// class foo
489 /// {
490 /// };
491 /// if (foo()) {
492 /// } else {
493 /// }
494 /// enum X : int { A, B };
495 /// \endcode
496 BS_Mozilla,
497 /// Like ``Attach``, but break before function definitions, ``catch``, and
498 /// ``else``.
499 /// \code
500 /// try {
501 /// foo();
502 /// } catch () {
503 /// }
504 /// void foo() { bar(); }
505 /// class foo
506 /// {
507 /// };
508 /// if (foo()) {
509 /// } else {
510 /// }
511 /// enum X : int
512 /// {
513 /// A,
514 /// B
515 /// };
516 /// \endcode
517 BS_Stroustrup,
518 /// Always break before braces.
519 /// \code
520 /// try {
521 /// foo();
522 /// }
523 /// catch () {
524 /// }
525 /// void foo() { bar(); }
526 /// class foo {
527 /// };
528 /// if (foo()) {
529 /// }
530 /// else {
531 /// }
532 /// enum X : int { A, B };
533 /// \endcode
534 BS_Allman,
535 /// Always break before braces and add an extra level of indentation to
536 /// braces of control statements, not to those of class, function
537 /// or other definitions.
538 /// \code
539 /// try
540 /// {
541 /// foo();
542 /// }
543 /// catch ()
544 /// {
545 /// }
546 /// void foo() { bar(); }
547 /// class foo
548 /// {
549 /// };
550 /// if (foo())
551 /// {
552 /// }
553 /// else
554 /// {
555 /// }
556 /// enum X : int
557 /// {
558 /// A,
559 /// B
560 /// };
561 /// \endcode
562 BS_GNU,
563 /// Like ``Attach``, but break before functions.
564 /// \code
565 /// try {
566 /// foo();
567 /// } catch () {
568 /// }
569 /// void foo() { bar(); }
570 /// class foo {
571 /// };
572 /// if (foo()) {
573 /// } else {
574 /// }
575 /// enum X : int { A, B };
576 /// \endcode
577 BS_WebKit,
578 /// Configure each individual brace in `BraceWrapping`.
579 BS_Custom
580 };
581
582 /// \brief The brace breaking style to use.
583 BraceBreakingStyle BreakBeforeBraces;
584
585 /// \brief Precise control over the wrapping of braces.
586 /// \code
587 /// # Should be declared this way:
588 /// BreakBeforeBraces: Custom
589 /// BraceWrapping:
590 /// AfterClass: true
591 /// \endcode
592 struct BraceWrappingFlags {
593 /// \brief Wrap class definitions.
594 /// \code
595 /// true:
596 /// class foo {};
597 ///
598 /// false:
599 /// class foo
600 /// {};
601 /// \endcode
602 bool AfterClass;
603 /// \brief Wrap control statements (``if``/``for``/``while``/``switch``/..).
604 /// \code
605 /// true:
606 /// if (foo())
607 /// {
608 /// } else
609 /// {}
610 /// for (int i = 0; i < 10; ++i)
611 /// {}
612 ///
613 /// false:
614 /// if (foo()) {
615 /// } else {
616 /// }
617 /// for (int i = 0; i < 10; ++i) {
618 /// }
619 /// \endcode
620 bool AfterControlStatement;
621 /// \brief Wrap enum definitions.
622 /// \code
623 /// true:
624 /// enum X : int
625 /// {
626 /// B
627 /// };
628 ///
629 /// false:
630 /// enum X : int { B };
631 /// \endcode
632 bool AfterEnum;
633 /// \brief Wrap function definitions.
634 /// \code
635 /// true:
636 /// void foo()
637 /// {
638 /// bar();
639 /// bar2();
640 /// }
641 ///
642 /// false:
643 /// void foo() {
644 /// bar();
645 /// bar2();
646 /// }
647 /// \endcode
648 bool AfterFunction;
649 /// \brief Wrap namespace definitions.
650 /// \code
651 /// true:
652 /// namespace
653 /// {
654 /// int foo();
655 /// int bar();
656 /// }
657 ///
658 /// false:
659 /// namespace {
660 /// int foo();
661 /// int bar();
662 /// }
663 /// \endcode
664 bool AfterNamespace;
665 /// \brief Wrap ObjC definitions (``@autoreleasepool``, interfaces, ..).
666 bool AfterObjCDeclaration;
667 /// \brief Wrap struct definitions.
668 /// \code
669 /// true:
670 /// struct foo
671 /// {
672 /// int x;
673 /// };
674 ///
675 /// false:
676 /// struct foo {
677 /// int x;
678 /// };
679 /// \endcode
680 bool AfterStruct;
681 /// \brief Wrap union definitions.
682 /// \code
683 /// true:
684 /// union foo
685 /// {
686 /// int x;
687 /// }
688 ///
689 /// false:
690 /// union foo {
691 /// int x;
692 /// }
693 /// \endcode
694 bool AfterUnion;
695 /// \brief Wrap extern blocks.
696 /// \code
697 /// true:
698 /// extern "C"
699 /// {
700 /// int foo();
701 /// }
702 ///
703 /// false:
704 /// extern "C" {
705 /// int foo();
706 /// }
707 /// \endcode
708 bool AfterExternBlock;
709 /// \brief Wrap before ``catch``.
710 /// \code
711 /// true:
712 /// try {
713 /// foo();
714 /// }
715 /// catch () {
716 /// }
717 ///
718 /// false:
719 /// try {
720 /// foo();
721 /// } catch () {
722 /// }
723 /// \endcode
724 bool BeforeCatch;
725 /// \brief Wrap before ``else``.
726 /// \code
727 /// true:
728 /// if (foo()) {
729 /// }
730 /// else {
731 /// }
732 ///
733 /// false:
734 /// if (foo()) {
735 /// } else {
736 /// }
737 /// \endcode
738 bool BeforeElse;
739 /// \brief Indent the wrapped braces themselves.
740 bool IndentBraces;
741 /// \brief If ``false``, empty function body can be put on a single line.
742 /// This option is used only if the opening brace of the function has
743 /// already been wrapped, i.e. the `AfterFunction` brace wrapping mode is
744 /// set, and the function could/should not be put on a single line (as per
745 /// `AllowShortFunctionsOnASingleLine` and constructor formatting options).
746 /// \code
747 /// int f() vs. inf f()
748 /// {} {
749 /// }
750 /// \endcode
751 ///
752 bool SplitEmptyFunction;
753 /// \brief If ``false``, empty record (e.g. class, struct or union) body
754 /// can be put on a single line. This option is used only if the opening
755 /// brace of the record has already been wrapped, i.e. the `AfterClass`
756 /// (for classes) brace wrapping mode is set.
757 /// \code
758 /// class Foo vs. class Foo
759 /// {} {
760 /// }
761 /// \endcode
762 ///
763 bool SplitEmptyRecord;
764 /// \brief If ``false``, empty namespace body can be put on a single line.
765 /// This option is used only if the opening brace of the namespace has
766 /// already been wrapped, i.e. the `AfterNamespace` brace wrapping mode is
767 /// set.
768 /// \code
769 /// namespace Foo vs. namespace Foo
770 /// {} {
771 /// }
772 /// \endcode
773 ///
774 bool SplitEmptyNamespace;
775 };
776
777 /// \brief Control of individual brace wrapping cases.
778 ///
779 /// If ``BreakBeforeBraces`` is set to ``BS_Custom``, use this to specify how
780 /// each individual brace case should be handled. Otherwise, this is ignored.
781 /// \code{.yaml}
782 /// # Example of usage:
783 /// BreakBeforeBraces: Custom
784 /// BraceWrapping:
785 /// AfterEnum: true
786 /// AfterStruct: false
787 /// SplitEmptyFunction: false
788 /// \endcode
789 BraceWrappingFlags BraceWrapping;
790
791 /// \brief If ``true``, ternary operators will be placed after line breaks.
792 /// \code
793 /// true:
794 /// veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongDescription
795 /// ? firstValue
796 /// : SecondValueVeryVeryVeryVeryLong;
797 ///
798 /// false:
799 /// veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongDescription ?
800 /// firstValue :
801 /// SecondValueVeryVeryVeryVeryLong;
802 /// \endcode
803 bool BreakBeforeTernaryOperators;
804
805 /// \brief Different ways to break initializers.
806 enum BreakConstructorInitializersStyle {
807 /// Break constructor initializers before the colon and after the commas.
808 /// \code
809 /// Constructor()
810 /// : initializer1(),
811 /// initializer2()
812 /// \endcode
813 BCIS_BeforeColon,
814 /// Break constructor initializers before the colon and commas, and align
815 /// the commas with the colon.
816 /// \code
817 /// Constructor()
818 /// : initializer1()
819 /// , initializer2()
820 /// \endcode
821 BCIS_BeforeComma,
822 /// Break constructor initializers after the colon and commas.
823 /// \code
824 /// Constructor() :
825 /// initializer1(),
826 /// initializer2()
827 /// \endcode
828 BCIS_AfterColon
829 };
830
831 /// \brief The constructor initializers style to use.
832 BreakConstructorInitializersStyle BreakConstructorInitializers;
833
834 /// \brief Break after each annotation on a field in Java files.
835 /// \code{.java}
836 /// true: false:
837 /// @Partial vs. @Partial @Mock DataLoad loader;
838 /// @Mock
839 /// DataLoad loader;
840 /// \endcode
841 bool BreakAfterJavaFieldAnnotations;
842
843 /// \brief Allow breaking string literals when formatting.
844 bool BreakStringLiterals;
845
846 /// \brief The column limit.
847 ///
848 /// A column limit of ``0`` means that there is no column limit. In this case,
849 /// clang-format will respect the input's line breaking decisions within
850 /// statements unless they contradict other rules.
851 unsigned ColumnLimit;
852
853 /// \brief A regular expression that describes comments with special meaning,
854 /// which should not be split into lines or otherwise changed.
855 /// \code
856 /// // CommentPragmas: '^ FOOBAR pragma:'
857 /// // Will leave the following line unaffected
858 /// #include <vector> // FOOBAR pragma: keep
859 /// \endcode
860 std::string CommentPragmas;
861
862 /// \brief If ``true``, in the class inheritance expression clang-format will
863 /// break before ``:`` and ``,`` if there is multiple inheritance.
864 /// \code
865 /// true: false:
866 /// class MyClass vs. class MyClass : public X, public Y {
867 /// : public X };
868 /// , public Y {
869 /// };
870 /// \endcode
871 bool BreakBeforeInheritanceComma;
872
873 /// \brief If ``true``, consecutive namespace declarations will be on the same
874 /// line. If ``false``, each namespace is declared on a new line.
875 /// \code
876 /// true:
877 /// namespace Foo { namespace Bar {
878 /// }}
879 ///
880 /// false:
881 /// namespace Foo {
882 /// namespace Bar {
883 /// }
884 /// }
885 /// \endcode
886 ///
887 /// If it does not fit on a single line, the overflowing namespaces get
888 /// wrapped:
889 /// \code
890 /// namespace Foo { namespace Bar {
891 /// namespace Extra {
892 /// }}}
893 /// \endcode
894 bool CompactNamespaces;
895
896 /// \brief If the constructor initializers don't fit on a line, put each
897 /// initializer on its own line.
898 /// \code
899 /// true:
900 /// SomeClass::Constructor()
901 /// : aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa) {
902 /// return 0;
903 /// }
904 ///
905 /// false:
906 /// SomeClass::Constructor()
907 /// : aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaa),
908 /// aaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa) {
909 /// return 0;
910 /// }
911 /// \endcode
912 bool ConstructorInitializerAllOnOneLineOrOnePerLine;
913
914 /// \brief The number of characters to use for indentation of constructor
915 /// initializer lists.
916 unsigned ConstructorInitializerIndentWidth;
917
918 /// \brief Indent width for line continuations.
919 /// \code
920 /// ContinuationIndentWidth: 2
921 ///
922 /// int i = // VeryVeryVeryVeryVeryLongComment
923 /// longFunction( // Again a long comment
924 /// arg);
925 /// \endcode
926 unsigned ContinuationIndentWidth;
927
928 /// \brief If ``true``, format braced lists as best suited for C++11 braced
929 /// lists.
930 ///
931 /// Important differences:
932 /// - No spaces inside the braced list.
933 /// - No line break before the closing brace.
934 /// - Indentation with the continuation indent, not with the block indent.
935 ///
936 /// Fundamentally, C++11 braced lists are formatted exactly like function
937 /// calls would be formatted in their place. If the braced list follows a name
938 /// (e.g. a type or variable name), clang-format formats as if the ``{}`` were
939 /// the parentheses of a function call with that name. If there is no name,
940 /// a zero-length name is assumed.
941 /// \code
942 /// true: false:
943 /// vector<int> x{1, 2, 3, 4}; vs. vector<int> x{ 1, 2, 3, 4 };
944 /// vector<T> x{{}, {}, {}, {}}; vector<T> x{ {}, {}, {}, {} };
945 /// f(MyMap[{composite, key}]); f(MyMap[{ composite, key }]);
946 /// new int[3]{1, 2, 3}; new int[3]{ 1, 2, 3 };
947 /// \endcode
948 bool Cpp11BracedListStyle;
949
950 /// \brief If ``true``, analyze the formatted file for the most common
951 /// alignment of ``&`` and ``*``.
952 /// Pointer and reference alignment styles are going to be updated according
953 /// to the preferences found in the file.
954 /// ``PointerAlignment`` is then used only as fallback.
955 bool DerivePointerAlignment;
956
957 /// \brief Disables formatting completely.
958 bool DisableFormat;
959
960 /// \brief If ``true``, clang-format detects whether function calls and
961 /// definitions are formatted with one parameter per line.
962 ///
963 /// Each call can be bin-packed, one-per-line or inconclusive. If it is
964 /// inconclusive, e.g. completely on one line, but a decision needs to be
965 /// made, clang-format analyzes whether there are other bin-packed cases in
966 /// the input file and act accordingly.
967 ///
968 /// NOTE: This is an experimental flag, that might go away or be renamed. Do
969 /// not use this in config files, etc. Use at your own risk.
970 bool ExperimentalAutoDetectBinPacking;
971
972 /// \brief If ``true``, clang-format adds missing namespace end comments and
973 /// fixes invalid existing ones.
974 /// \code
975 /// true: false:
976 /// namespace a { vs. namespace a {
977 /// foo(); foo();
978 /// } // namespace a; }
979 /// \endcode
980 bool FixNamespaceComments;
981
982 /// \brief A vector of macros that should be interpreted as foreach loops
983 /// instead of as function calls.
984 ///
985 /// These are expected to be macros of the form:
986 /// \code
987 /// FOREACH(<variable-declaration>, ...)
988 /// <loop-body>
989 /// \endcode
990 ///
991 /// In the .clang-format configuration file, this can be configured like:
992 /// \code{.yaml}
993 /// ForEachMacros: ['RANGES_FOR', 'FOREACH']
994 /// \endcode
995 ///
996 /// For example: BOOST_FOREACH.
997 std::vector<std::string> ForEachMacros;
998
999 /// \brief Styles for sorting multiple ``#include`` blocks.
1000 enum IncludeBlocksStyle {
1001 /// \brief Sort each ``#include`` block separately.
1002 /// \code
1003 /// #include "b.h" into #include "b.h"
1004 ///
1005 /// #include <lib/main.h> #include "a.h"
1006 /// #include "a.h" #include <lib/main.h>
1007 /// \endcode
1008 IBS_Preserve,
1009 /// \brief Merge multiple ``#include`` blocks together and sort as one.
1010 /// \code
1011 /// #include "b.h" into #include "a.h"
1012 /// #include "b.h"
1013 /// #include <lib/main.h> #include <lib/main.h>
1014 /// #include "a.h"
1015 /// \endcode
1016 IBS_Merge,
1017 /// \brief Merge multiple ``#include`` blocks together and sort as one.
1018 /// Then split into groups based on category priority. See
1019 /// ``IncludeCategories``.
1020 /// \code
1021 /// #include "b.h" into #include "a.h"
1022 /// #include "b.h"
1023 /// #include <lib/main.h>
1024 /// #include "a.h" #include <lib/main.h>
1025 /// \endcode
1026 IBS_Regroup,
1027 };
1028
1029 /// \brief Dependent on the value, multiple ``#include`` blocks can be sorted
1030 /// as one and divided based on category.
1031 IncludeBlocksStyle IncludeBlocks;
1032
1033 /// \brief See documentation of ``IncludeCategories``.
1034 struct IncludeCategory {
1035 /// \brief The regular expression that this category matches.
1036 std::string Regex;
1037 /// \brief The priority to assign to this category.
1038 int Priority;
1039 bool operator==(const IncludeCategory &Other) const {
1040 return Regex == Other.Regex && Priority == Other.Priority;
1041 }
1042 };
1043
1044 /// \brief Regular expressions denoting the different ``#include`` categories
1045 /// used for ordering ``#includes``.
1046 ///
1047 /// These regular expressions are matched against the filename of an include
1048 /// (including the <> or "") in order. The value belonging to the first
1049 /// matching regular expression is assigned and ``#includes`` are sorted first
1050 /// according to increasing category number and then alphabetically within
1051 /// each category.
1052 ///
1053 /// If none of the regular expressions match, INT_MAX is assigned as
1054 /// category. The main header for a source file automatically gets category 0.
1055 /// so that it is generally kept at the beginning of the ``#includes``
1056 /// (http://llvm.org/docs/CodingStandards.html#include-style). However, you
1057 /// can also assign negative priorities if you have certain headers that
1058 /// always need to be first.
1059 ///
1060 /// To configure this in the .clang-format file, use:
1061 /// \code{.yaml}
1062 /// IncludeCategories:
1063 /// - Regex: '^"(llvm|llvm-c|clang|clang-c)/'
1064 /// Priority: 2
1065 /// - Regex: '^(<|"(gtest|gmock|isl|json)/)'
1066 /// Priority: 3
1067 /// - Regex: '.*'
1068 /// Priority: 1
1069 /// \endcode
1070 std::vector<IncludeCategory> IncludeCategories;
1071
1072 /// \brief Specify a regular expression of suffixes that are allowed in the
1073 /// file-to-main-include mapping.
1074 ///
1075 /// When guessing whether a #include is the "main" include (to assign
1076 /// category 0, see above), use this regex of allowed suffixes to the header
1077 /// stem. A partial match is done, so that:
1078 /// - "" means "arbitrary suffix"
1079 /// - "$" means "no suffix"
1080 ///
1081 /// For example, if configured to "(_test)?$", then a header a.h would be seen
1082 /// as the "main" include in both a.cc and a_test.cc.
1083 std::string IncludeIsMainRegex;
1084
1085 /// \brief Indent case labels one level from the switch statement.
1086 ///
1087 /// When ``false``, use the same indentation level as for the switch statement.
1088 /// Switch statement body is always indented one level more than case labels.
1089 /// \code
1090 /// false: true:
1091 /// switch (fool) { vs. switch (fool) {
1092 /// case 1: case 1:
1093 /// bar(); bar();
1094 /// break; break;
1095 /// default: default:
1096 /// plop(); plop();
1097 /// } }
1098 /// \endcode
1099 bool IndentCaseLabels;
1100
1101 /// \brief Options for indenting preprocessor directives.
1102 enum PPDirectiveIndentStyle {
1103 /// Does not indent any directives.
1104 /// \code
1105 /// #if FOO
1106 /// #if BAR
1107 /// #include <foo>
1108 /// #endif
1109 /// #endif
1110 /// \endcode
1111 PPDIS_None,
1112 /// Indents directives after the hash.
1113 /// \code
1114 /// #if FOO
1115 /// # if BAR
1116 /// # include <foo>
1117 /// # endif
1118 /// #endif
1119 /// \endcode
1120 PPDIS_AfterHash
1121 };
1122
1123 /// \brief The preprocessor directive indenting style to use.
1124 PPDirectiveIndentStyle IndentPPDirectives;
1125
1126 /// \brief The number of columns to use for indentation.
1127 /// \code
1128 /// IndentWidth: 3
1129 ///
1130 /// void f() {
1131 /// someFunction();
1132 /// if (true, false) {
1133 /// f();
1134 /// }
1135 /// }
1136 /// \endcode
1137 unsigned IndentWidth;
1138
1139 /// \brief Indent if a function definition or declaration is wrapped after the
1140 /// type.
1141 /// \code
1142 /// true:
1143 /// LoooooooooooooooooooooooooooooooooooooooongReturnType
1144 /// LoooooooooooooooooooooooooooooooongFunctionDeclaration();
1145 ///
1146 /// false:
1147 /// LoooooooooooooooooooooooooooooooooooooooongReturnType
1148 /// LoooooooooooooooooooooooooooooooongFunctionDeclaration();
1149 /// \endcode
1150 bool IndentWrappedFunctionNames;
1151
1152 /// \brief Quotation styles for JavaScript strings. Does not affect template
1153 /// strings.
1154 enum JavaScriptQuoteStyle {
1155 /// Leave string quotes as they are.
1156 /// \code{.js}
1157 /// string1 = "foo";
1158 /// string2 = 'bar';
1159 /// \endcode
1160 JSQS_Leave,
1161 /// Always use single quotes.
1162 /// \code{.js}
1163 /// string1 = 'foo';
1164 /// string2 = 'bar';
1165 /// \endcode
1166 JSQS_Single,
1167 /// Always use double quotes.
1168 /// \code{.js}
1169 /// string1 = "foo";
1170 /// string2 = "bar";
1171 /// \endcode
1172 JSQS_Double
1173 };
1174
1175 /// \brief The JavaScriptQuoteStyle to use for JavaScript strings.
1176 JavaScriptQuoteStyle JavaScriptQuotes;
1177
1178 /// \brief Whether to wrap JavaScript import/export statements.
1179 /// \code{.js}
1180 /// true:
1181 /// import {
1182 /// VeryLongImportsAreAnnoying,
1183 /// VeryLongImportsAreAnnoying,
1184 /// VeryLongImportsAreAnnoying,
1185 /// } from 'some/module.js'
1186 ///
1187 /// false:
1188 /// import {VeryLongImportsAreAnnoying, VeryLongImportsAreAnnoying, VeryLongImportsAreAnnoying,} from "some/module.js"
1189 /// \endcode
1190 bool JavaScriptWrapImports;
1191
1192 /// \brief If true, the empty line at the start of blocks is kept.
1193 /// \code
1194 /// true: false:
1195 /// if (foo) { vs. if (foo) {
1196 /// bar();
1197 /// bar(); }
1198 /// }
1199 /// \endcode
1200 bool KeepEmptyLinesAtTheStartOfBlocks;
1201
1202 /// \brief Supported languages.
1203 ///
1204 /// When stored in a configuration file, specifies the language, that the
1205 /// configuration targets. When passed to the ``reformat()`` function, enables
1206 /// syntax features specific to the language.
1207 enum LanguageKind {
1208 /// Do not use.
1209 LK_None,
1210 /// Should be used for C, C++.
1211 LK_Cpp,
1212 /// Should be used for Java.
1213 LK_Java,
1214 /// Should be used for JavaScript.
1215 LK_JavaScript,
1216 /// Should be used for Objective-C, Objective-C++.
1217 LK_ObjC,
1218 /// Should be used for Protocol Buffers
1219 /// (https://developers.google.com/protocol-buffers/).
1220 LK_Proto,
1221 /// Should be used for TableGen code.
1222 LK_TableGen,
1223 /// Should be used for Protocol Buffer messages in text format
1224 /// (https://developers.google.com/protocol-buffers/).
1225 LK_TextProto
1226 };
1227 bool isCpp() const { return Language == LK_Cpp || Language == LK_ObjC; }
1228
1229 /// \brief Language, this format style is targeted at.
1230 LanguageKind Language;
1231
1232 /// \brief A regular expression matching macros that start a block.
1233 /// \code
1234 /// # With:
1235 /// MacroBlockBegin: "^NS_MAP_BEGIN|\
1236 /// NS_TABLE_HEAD$"
1237 /// MacroBlockEnd: "^\
1238 /// NS_MAP_END|\
1239 /// NS_TABLE_.*_END$"
1240 ///
1241 /// NS_MAP_BEGIN
1242 /// foo();
1243 /// NS_MAP_END
1244 ///
1245 /// NS_TABLE_HEAD
1246 /// bar();
1247 /// NS_TABLE_FOO_END
1248 ///
1249 /// # Without:
1250 /// NS_MAP_BEGIN
1251 /// foo();
1252 /// NS_MAP_END
1253 ///
1254 /// NS_TABLE_HEAD
1255 /// bar();
1256 /// NS_TABLE_FOO_END
1257 /// \endcode
1258 std::string MacroBlockBegin;
1259
1260 /// \brief A regular expression matching macros that end a block.
1261 std::string MacroBlockEnd;
1262
1263 /// \brief The maximum number of consecutive empty lines to keep.
1264 /// \code
1265 /// MaxEmptyLinesToKeep: 1 vs. MaxEmptyLinesToKeep: 0
1266 /// int f() { int f() {
1267 /// int = 1; int i = 1;
1268 /// i = foo();
1269 /// i = foo(); return i;
1270 /// }
1271 /// return i;
1272 /// }
1273 /// \endcode
1274 unsigned MaxEmptyLinesToKeep;
1275
1276 /// \brief Different ways to indent namespace contents.
1277 enum NamespaceIndentationKind {
1278 /// Don't indent in namespaces.
1279 /// \code
1280 /// namespace out {
1281 /// int i;
1282 /// namespace in {
1283 /// int i;
1284 /// }
1285 /// }
1286 /// \endcode
1287 NI_None,
1288 /// Indent only in inner namespaces (nested in other namespaces).
1289 /// \code
1290 /// namespace out {
1291 /// int i;
1292 /// namespace in {
1293 /// int i;
1294 /// }
1295 /// }
1296 /// \endcode
1297 NI_Inner,
1298 /// Indent in all namespaces.
1299 /// \code
1300 /// namespace out {
1301 /// int i;
1302 /// namespace in {
1303 /// int i;
1304 /// }
1305 /// }
1306 /// \endcode
1307 NI_All
1308 };
1309
1310 /// \brief The indentation used for namespaces.
1311 NamespaceIndentationKind NamespaceIndentation;
1312
1313 /// \brief Controls bin-packing Objective-C protocol conformance list
1314 /// items into as few lines as possible when they go over ``ColumnLimit``.
1315 ///
1316 /// If ``Auto`` (the default), delegates to the value in
1317 /// ``BinPackParameters``. If that is ``true``, bin-packs Objective-C
1318 /// protocol conformance list items into as few lines as possible
1319 /// whenever they go over ``ColumnLimit``.
1320 ///
1321 /// If ``Always``, always bin-packs Objective-C protocol conformance
1322 /// list items into as few lines as possible whenever they go over
1323 /// ``ColumnLimit``.
1324 ///
1325 /// If ``Never``, lays out Objective-C protocol conformance list items
1326 /// onto individual lines whenever they go over ``ColumnLimit``.
1327 ///
1328 /// \code
1329 /// Always (or Auto, if BinPackParameters=true):
1330 /// @interface ccccccccccccc () <
1331 /// ccccccccccccc, ccccccccccccc,
1332 /// ccccccccccccc, ccccccccccccc> {
1333 /// }
1334 ///
1335 /// Never (or Auto, if BinPackParameters=false):
1336 /// @interface ddddddddddddd () <
1337 /// ddddddddddddd,
1338 /// ddddddddddddd,
1339 /// ddddddddddddd,
1340 /// ddddddddddddd> {
1341 /// }
1342 /// \endcode
1343 BinPackStyle ObjCBinPackProtocolList;
1344
1345 /// \brief The number of characters to use for indentation of ObjC blocks.
1346 /// \code{.objc}
1347 /// ObjCBlockIndentWidth: 4
1348 ///
1349 /// [operation setCompletionBlock:^{
1350 /// [self onOperationDone];
1351 /// }];
1352 /// \endcode
1353 unsigned ObjCBlockIndentWidth;
1354
1355 /// \brief Add a space after ``@property`` in Objective-C, i.e. use
1356 /// ``@property (readonly)`` instead of ``@property(readonly)``.
1357 bool ObjCSpaceAfterProperty;
1358
1359 /// \brief Add a space in front of an Objective-C protocol list, i.e. use
1360 /// ``Foo <Protocol>`` instead of ``Foo<Protocol>``.
1361 bool ObjCSpaceBeforeProtocolList;
1362
1363 /// \brief The penalty for breaking around an assignment operator.
1364 unsigned PenaltyBreakAssignment;
1365
1366 /// \brief The penalty for breaking a function call after ``call(``.
1367 unsigned PenaltyBreakBeforeFirstCallParameter;
1368
1369 /// \brief The penalty for each line break introduced inside a comment.
1370 unsigned PenaltyBreakComment;
1371
1372 /// \brief The penalty for breaking before the first ``<<``.
1373 unsigned PenaltyBreakFirstLessLess;
1374
1375 /// \brief The penalty for each line break introduced inside a string literal.
1376 unsigned PenaltyBreakString;
1377
1378 /// \brief The penalty for each character outside of the column limit.
1379 unsigned PenaltyExcessCharacter;
1380
1381 /// \brief Penalty for putting the return type of a function onto its own
1382 /// line.
1383 unsigned PenaltyReturnTypeOnItsOwnLine;
1384
1385 /// \brief The ``&`` and ``*`` alignment style.
1386 enum PointerAlignmentStyle {
1387 /// Align pointer to the left.
1388 /// \code
1389 /// int* a;
1390 /// \endcode
1391 PAS_Left,
1392 /// Align pointer to the right.
1393 /// \code
1394 /// int *a;
1395 /// \endcode
1396 PAS_Right,
1397 /// Align pointer in the middle.
1398 /// \code
1399 /// int * a;
1400 /// \endcode
1401 PAS_Middle
1402 };
1403
1404 /// \brief Pointer and reference alignment style.
1405 PointerAlignmentStyle PointerAlignment;
1406
1407 /// See documentation of ``RawStringFormats``.
1408 struct RawStringFormat {
1409 /// \brief The language of this raw string.
1410 LanguageKind Language;
1411 /// \brief A list of raw string delimiters that match this language.
1412 std::vector<std::string> Delimiters;
1413 /// \brief A list of enclosing function names that match this language.
1414 std::vector<std::string> EnclosingFunctions;
1415 /// \brief The canonical delimiter for this language.
1416 std::string CanonicalDelimiter;
1417 /// \brief The style name on which this raw string format is based on.
1418 /// If not specified, the raw string format is based on the style that this
1419 /// format is based on.
1420 std::string BasedOnStyle;
1421 bool operator==(const RawStringFormat &Other) const {
1422 return Language == Other.Language && Delimiters == Other.Delimiters &&
1423 EnclosingFunctions == Other.EnclosingFunctions &&
1424 CanonicalDelimiter == Other.CanonicalDelimiter &&
1425 BasedOnStyle == Other.BasedOnStyle;
1426 }
1427 };
1428
1429 /// \brief Defines hints for detecting supported languages code blocks in raw
1430 /// strings.
1431 ///
1432 /// A raw string with a matching delimiter or a matching enclosing function
1433 /// name will be reformatted assuming the specified language based on the
1434 /// style for that language defined in the .clang-format file. If no style has
1435 /// been defined in the .clang-format file for the specific language, a
1436 /// predefined style given by 'BasedOnStyle' is used. If 'BasedOnStyle' is not
1437 /// found, the formatting is based on llvm style. A matching delimiter takes
1438 /// precedence over a matching enclosing function name for determining the
1439 /// language of the raw string contents.
1440 ///
1441 /// If a canonical delimiter is specified, occurrences of other delimiters for
1442 /// the same language will be updated to the canonical if possible.
1443 ///
1444 /// There should be at most one specification per language and each delimiter
1445 /// and enclosing function should not occur in multiple specifications.
1446 ///
1447 /// To configure this in the .clang-format file, use:
1448 /// \code{.yaml}
1449 /// RawStringFormats:
1450 /// - Language: TextProto
1451 /// Delimiters:
1452 /// - 'pb'
1453 /// - 'proto'
1454 /// EnclosingFunctions:
1455 /// - 'PARSE_TEXT_PROTO'
1456 /// BasedOnStyle: google
1457 /// - Language: Cpp
1458 /// Delimiters:
1459 /// - 'cc'
1460 /// - 'cpp'
1461 /// BasedOnStyle: llvm
1462 /// CanonicalDelimiter: 'cc'
1463 /// \endcode
1464 std::vector<RawStringFormat> RawStringFormats;
1465
1466 /// \brief If ``true``, clang-format will attempt to re-flow comments.
1467 /// \code
1468 /// false:
1469 /// // veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongComment with plenty of information
1470 /// /* second veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongComment with plenty of information */
1471 ///
1472 /// true:
1473 /// // veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongComment with plenty of
1474 /// // information
1475 /// /* second veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongComment with plenty of
1476 /// * information */
1477 /// \endcode
1478 bool ReflowComments;
1479
1480 /// \brief If ``true``, clang-format will sort ``#includes``.
1481 /// \code
1482 /// false: true:
1483 /// #include "b.h" vs. #include "a.h"
1484 /// #include "a.h" #include "b.h"
1485 /// \endcode
1486 bool SortIncludes;
1487
1488 /// \brief If ``true``, clang-format will sort using declarations.
1489 ///
1490 /// The order of using declarations is defined as follows:
1491 /// Split the strings by "::" and discard any initial empty strings. The last
1492 /// element of each list is a non-namespace name; all others are namespace
1493 /// names. Sort the lists of names lexicographically, where the sort order of
1494 /// individual names is that all non-namespace names come before all namespace
1495 /// names, and within those groups, names are in case-insensitive
1496 /// lexicographic order.
1497 /// \code
1498 /// false: true:
1499 /// using std::cout; vs. using std::cin;
1500 /// using std::cin; using std::cout;
1501 /// \endcode
1502 bool SortUsingDeclarations;
1503
1504 /// \brief If ``true``, a space is inserted after C style casts.
1505 /// \code
1506 /// true: false:
1507 /// (int)i; vs. (int) i;
1508 /// \endcode
1509 bool SpaceAfterCStyleCast;
1510
1511 /// \brief If \c true, a space will be inserted after the 'template' keyword.
1512 /// \code
1513 /// true: false:
1514 /// template <int> void foo(); vs. template<int> void foo();
1515 /// \endcode
1516 bool SpaceAfterTemplateKeyword;
1517
1518 /// \brief If ``false``, spaces will be removed before assignment operators.
1519 /// \code
1520 /// true: false:
1521 /// int a = 5; vs. int a=5;
1522 /// a += 42 a+=42;
1523 /// \endcode
1524 bool SpaceBeforeAssignmentOperators;
1525
1526 /// \brief Different ways to put a space before opening parentheses.
1527 enum SpaceBeforeParensOptions {
1528 /// Never put a space before opening parentheses.
1529 /// \code
1530 /// void f() {
1531 /// if(true) {
1532 /// f();
1533 /// }
1534 /// }
1535 /// \endcode
1536 SBPO_Never,
1537 /// Put a space before opening parentheses only after control statement
1538 /// keywords (``for/if/while...``).
1539 /// \code
1540 /// void f() {
1541 /// if (true) {
1542 /// f();
1543 /// }
1544 /// }
1545 /// \endcode
1546 SBPO_ControlStatements,
1547 /// Always put a space before opening parentheses, except when it's
1548 /// prohibited by the syntax rules (in function-like macro definitions) or
1549 /// when determined by other style rules (after unary operators, opening
1550 /// parentheses, etc.)
1551 /// \code
1552 /// void f () {
1553 /// if (true) {
1554 /// f ();
1555 /// }
1556 /// }
1557 /// \endcode
1558 SBPO_Always
1559 };
1560
1561 /// \brief Defines in which cases to put a space before opening parentheses.
1562 SpaceBeforeParensOptions SpaceBeforeParens;
1563
1564 /// \brief If ``true``, spaces may be inserted into ``()``.
1565 /// \code
1566 /// true: false:
1567 /// void f( ) { vs. void f() {
1568 /// int x[] = {foo( ), bar( )}; int x[] = {foo(), bar()};
1569 /// if (true) { if (true) {
1570 /// f( ); f();
1571 /// } }
1572 /// } }
1573 /// \endcode
1574 bool SpaceInEmptyParentheses;
1575
1576 /// \brief The number of spaces before trailing line comments
1577 /// (``//`` - comments).
1578 ///
1579 /// This does not affect trailing block comments (``/*`` - comments) as
1580 /// those commonly have different usage patterns and a number of special
1581 /// cases.
1582 /// \code
1583 /// SpacesBeforeTrailingComments: 3
1584 /// void f() {
1585 /// if (true) { // foo1
1586 /// f(); // bar
1587 /// } // foo
1588 /// }
1589 /// \endcode
1590 unsigned SpacesBeforeTrailingComments;
1591
1592 /// \brief If ``true``, spaces will be inserted after ``<`` and before ``>``
1593 /// in template argument lists.
1594 /// \code
1595 /// true: false:
1596 /// static_cast< int >(arg); vs. static_cast<int>(arg);
1597 /// std::function< void(int) > fct; std::function<void(int)> fct;
1598 /// \endcode
1599 bool SpacesInAngles;
1600
1601 /// \brief If ``true``, spaces are inserted inside container literals (e.g.
1602 /// ObjC and Javascript array and dict literals).
1603 /// \code{.js}
1604 /// true: false:
1605 /// var arr = [ 1, 2, 3 ]; vs. var arr = [1, 2, 3];
1606 /// f({a : 1, b : 2, c : 3}); f({a: 1, b: 2, c: 3});
1607 /// \endcode
1608 bool SpacesInContainerLiterals;
1609
1610 /// \brief If ``true``, spaces may be inserted into C style casts.
1611 /// \code
1612 /// true: false:
1613 /// x = ( int32 )y vs. x = (int32)y
1614 /// \endcode
1615 bool SpacesInCStyleCastParentheses;
1616
1617 /// \brief If ``true``, spaces will be inserted after ``(`` and before ``)``.
1618 /// \code
1619 /// true: false:
1620 /// t f( Deleted & ) & = delete; vs. t f(Deleted &) & = delete;
1621 /// \endcode
1622 bool SpacesInParentheses;
1623
1624 /// \brief If ``true``, spaces will be inserted after ``[`` and before ``]``.
1625 /// Lambdas or unspecified size array declarations will not be affected.
1626 /// \code
1627 /// true: false:
1628 /// int a[ 5 ]; vs. int a[5];
1629 /// std::unique_ptr<int[]> foo() {} // Won't be affected
1630 /// \endcode
1631 bool SpacesInSquareBrackets;
1632
1633 /// \brief Supported language standards.
1634 enum LanguageStandard {
1635 /// Use C++03-compatible syntax.
1636 LS_Cpp03,
1637 /// Use features of C++11, C++14 and C++1z (e.g. ``A<A<int>>`` instead of
1638 /// ``A<A<int> >``).
1639 LS_Cpp11,
1640 /// Automatic detection based on the input.
1641 LS_Auto
1642 };
1643
1644 /// \brief Format compatible with this standard, e.g. use ``A<A<int> >``
1645 /// instead of ``A<A<int>>`` for ``LS_Cpp03``.
1646 LanguageStandard Standard;
1647
1648 /// \brief The number of columns used for tab stops.
1649 unsigned TabWidth;
1650
1651 /// \brief Different ways to use tab in formatting.
1652 enum UseTabStyle {
1653 /// Never use tab.
1654 UT_Never,
1655 /// Use tabs only for indentation.
1656 UT_ForIndentation,
1657 /// Use tabs only for line continuation and indentation.
1658 UT_ForContinuationAndIndentation,
1659 /// Use tabs whenever we need to fill whitespace that spans at least from
1660 /// one tab stop to the next one.
1661 UT_Always
1662 };
1663
1664 /// \brief The way to use tab characters in the resulting file.
1665 UseTabStyle UseTab;
1666
1667 bool operator==(const FormatStyle &R) const {
1668 return AccessModifierOffset == R.AccessModifierOffset &&
1669 AlignAfterOpenBracket == R.AlignAfterOpenBracket &&
1670 AlignConsecutiveAssignments == R.AlignConsecutiveAssignments &&
1671 AlignConsecutiveDeclarations == R.AlignConsecutiveDeclarations &&
1672 AlignEscapedNewlines == R.AlignEscapedNewlines &&
1673 AlignOperands == R.AlignOperands &&
1674 AlignTrailingComments == R.AlignTrailingComments &&
1675 AllowAllParametersOfDeclarationOnNextLine ==
1676 R.AllowAllParametersOfDeclarationOnNextLine &&
1677 AllowShortBlocksOnASingleLine == R.AllowShortBlocksOnASingleLine &&
1678 AllowShortCaseLabelsOnASingleLine ==
1679 R.AllowShortCaseLabelsOnASingleLine &&
1680 AllowShortFunctionsOnASingleLine ==
1681 R.AllowShortFunctionsOnASingleLine &&
1682 AllowShortIfStatementsOnASingleLine ==
1683 R.AllowShortIfStatementsOnASingleLine &&
1684 AllowShortLoopsOnASingleLine == R.AllowShortLoopsOnASingleLine &&
1685 AlwaysBreakAfterReturnType == R.AlwaysBreakAfterReturnType &&
1686 AlwaysBreakBeforeMultilineStrings ==
1687 R.AlwaysBreakBeforeMultilineStrings &&
1688 AlwaysBreakTemplateDeclarations ==
1689 R.AlwaysBreakTemplateDeclarations &&
1690 BinPackArguments == R.BinPackArguments &&
1691 BinPackParameters == R.BinPackParameters &&
1692 BreakBeforeBinaryOperators == R.BreakBeforeBinaryOperators &&
1693 BreakBeforeBraces == R.BreakBeforeBraces &&
1694 BreakBeforeTernaryOperators == R.BreakBeforeTernaryOperators &&
1695 BreakConstructorInitializers == R.BreakConstructorInitializers &&
1696 CompactNamespaces == R.CompactNamespaces &&
1697 BreakAfterJavaFieldAnnotations == R.BreakAfterJavaFieldAnnotations &&
1698 BreakStringLiterals == R.BreakStringLiterals &&
1699 ColumnLimit == R.ColumnLimit && CommentPragmas == R.CommentPragmas &&
1700 BreakBeforeInheritanceComma == R.BreakBeforeInheritanceComma &&
1701 ConstructorInitializerAllOnOneLineOrOnePerLine ==
1702 R.ConstructorInitializerAllOnOneLineOrOnePerLine &&
1703 ConstructorInitializerIndentWidth ==
1704 R.ConstructorInitializerIndentWidth &&
1705 ContinuationIndentWidth == R.ContinuationIndentWidth &&
1706 Cpp11BracedListStyle == R.Cpp11BracedListStyle &&
1707 DerivePointerAlignment == R.DerivePointerAlignment &&
1708 DisableFormat == R.DisableFormat &&
1709 ExperimentalAutoDetectBinPacking ==
1710 R.ExperimentalAutoDetectBinPacking &&
1711 FixNamespaceComments == R.FixNamespaceComments &&
1712 ForEachMacros == R.ForEachMacros &&
1713 IncludeBlocks == R.IncludeBlocks &&
1714 IncludeCategories == R.IncludeCategories &&
1715 IndentCaseLabels == R.IndentCaseLabels &&
1716 IndentPPDirectives == R.IndentPPDirectives &&
1717 IndentWidth == R.IndentWidth && Language == R.Language &&
1718 IndentWrappedFunctionNames == R.IndentWrappedFunctionNames &&
1719 JavaScriptQuotes == R.JavaScriptQuotes &&
1720 JavaScriptWrapImports == R.JavaScriptWrapImports &&
1721 KeepEmptyLinesAtTheStartOfBlocks ==
1722 R.KeepEmptyLinesAtTheStartOfBlocks &&
1723 MacroBlockBegin == R.MacroBlockBegin &&
1724 MacroBlockEnd == R.MacroBlockEnd &&
1725 MaxEmptyLinesToKeep == R.MaxEmptyLinesToKeep &&
1726 NamespaceIndentation == R.NamespaceIndentation &&
1727 ObjCBinPackProtocolList == R.ObjCBinPackProtocolList &&
1728 ObjCBlockIndentWidth == R.ObjCBlockIndentWidth &&
1729 ObjCSpaceAfterProperty == R.ObjCSpaceAfterProperty &&
1730 ObjCSpaceBeforeProtocolList == R.ObjCSpaceBeforeProtocolList &&
1731 PenaltyBreakAssignment ==
1732 R.PenaltyBreakAssignment &&
1733 PenaltyBreakBeforeFirstCallParameter ==
1734 R.PenaltyBreakBeforeFirstCallParameter &&
1735 PenaltyBreakComment == R.PenaltyBreakComment &&
1736 PenaltyBreakFirstLessLess == R.PenaltyBreakFirstLessLess &&
1737 PenaltyBreakString == R.PenaltyBreakString &&
1738 PenaltyExcessCharacter == R.PenaltyExcessCharacter &&
1739 PenaltyReturnTypeOnItsOwnLine == R.PenaltyReturnTypeOnItsOwnLine &&
1740 PointerAlignment == R.PointerAlignment &&
1741 RawStringFormats == R.RawStringFormats &&
1742 SpaceAfterCStyleCast == R.SpaceAfterCStyleCast &&
1743 SpaceAfterTemplateKeyword == R.SpaceAfterTemplateKeyword &&
1744 SpaceBeforeAssignmentOperators == R.SpaceBeforeAssignmentOperators &&
1745 SpaceBeforeParens == R.SpaceBeforeParens &&
1746 SpaceInEmptyParentheses == R.SpaceInEmptyParentheses &&
1747 SpacesBeforeTrailingComments == R.SpacesBeforeTrailingComments &&
1748 SpacesInAngles == R.SpacesInAngles &&
1749 SpacesInContainerLiterals == R.SpacesInContainerLiterals &&
1750 SpacesInCStyleCastParentheses == R.SpacesInCStyleCastParentheses &&
1751 SpacesInParentheses == R.SpacesInParentheses &&
1752 SpacesInSquareBrackets == R.SpacesInSquareBrackets &&
1753 Standard == R.Standard && TabWidth == R.TabWidth &&
1754 UseTab == R.UseTab;
1755 }
1756
1757 llvm::Optional<FormatStyle> GetLanguageStyle(LanguageKind Language) const;
1758
1759 // Stores per-language styles. A FormatStyle instance inside has an empty
1760 // StyleSet. A FormatStyle instance returned by the Get method has its
1761 // StyleSet set to a copy of the originating StyleSet, effectively keeping the
1762 // internal representation of that StyleSet alive.
1763 //
1764 // The memory management and ownership reminds of a birds nest: chicks
1765 // leaving the nest take photos of the nest with them.
1766 struct FormatStyleSet {
1767 typedef std::map<FormatStyle::LanguageKind, FormatStyle> MapType;
1768
1769 llvm::Optional<FormatStyle> Get(FormatStyle::LanguageKind Language) const;
1770
1771 // Adds \p Style to this FormatStyleSet. Style must not have an associated
1772 // FormatStyleSet.
1773 // Style.Language should be different than LK_None. If this FormatStyleSet
1774 // already contains an entry for Style.Language, that gets replaced with the
1775 // passed Style.
1776 void Add(FormatStyle Style);
1777
1778 // Clears this FormatStyleSet.
1779 void Clear();
1780
1781 private:
1782 std::shared_ptr<MapType> Styles;
1783 };
1784
1785 static FormatStyleSet BuildStyleSetFromConfiguration(
1786 const FormatStyle &MainStyle,
1787 const std::vector<FormatStyle> &ConfigurationStyles);
1788
1789private:
1790 FormatStyleSet StyleSet;
1791
1792 friend std::error_code parseConfiguration(StringRef Text, FormatStyle *Style);
1793};
1794
1795/// \brief Returns a format style complying with the LLVM coding standards:
1796/// http://llvm.org/docs/CodingStandards.html.
1797FormatStyle getLLVMStyle();
1798
1799/// \brief Returns a format style complying with one of Google's style guides:
1800/// http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml.
1801/// http://google-styleguide.googlecode.com/svn/trunk/javascriptguide.xml.
1802/// https://developers.google.com/protocol-buffers/docs/style.
1803FormatStyle getGoogleStyle(FormatStyle::LanguageKind Language);
1804
1805/// \brief Returns a format style complying with Chromium's style guide:
1806/// http://www.chromium.org/developers/coding-style.
1807FormatStyle getChromiumStyle(FormatStyle::LanguageKind Language);
1808
1809/// \brief Returns a format style complying with Mozilla's style guide:
1810/// https://developer.mozilla.org/en-US/docs/Developer_Guide/Coding_Style.
1811FormatStyle getMozillaStyle();
1812
1813/// \brief Returns a format style complying with Webkit's style guide:
1814/// http://www.webkit.org/coding/coding-style.html
1815FormatStyle getWebKitStyle();
1816
1817/// \brief Returns a format style complying with GNU Coding Standards:
1818/// http://www.gnu.org/prep/standards/standards.html
1819FormatStyle getGNUStyle();
1820
1821/// \brief Returns style indicating formatting should be not applied at all.
1822FormatStyle getNoStyle();
1823
1824/// \brief Gets a predefined style for the specified language by name.
1825///
1826/// Currently supported names: LLVM, Google, Chromium, Mozilla. Names are
1827/// compared case-insensitively.
1828///
1829/// Returns ``true`` if the Style has been set.
1830bool getPredefinedStyle(StringRef Name, FormatStyle::LanguageKind Language,
1831 FormatStyle *Style);
1832
1833/// \brief Parse configuration from YAML-formatted text.
1834///
1835/// Style->Language is used to get the base style, if the ``BasedOnStyle``
1836/// option is present.
1837///
1838/// The FormatStyleSet of Style is reset.
1839///
1840/// When ``BasedOnStyle`` is not present, options not present in the YAML
1841/// document, are retained in \p Style.
1842std::error_code parseConfiguration(StringRef Text, FormatStyle *Style);
1843
1844/// \brief Gets configuration in a YAML string.
1845std::string configurationAsText(const FormatStyle &Style);
1846
1847/// \brief Returns the replacements necessary to sort all ``#include`` blocks
1848/// that are affected by ``Ranges``.
1849tooling::Replacements sortIncludes(const FormatStyle &Style, StringRef Code,
1850 ArrayRef<tooling::Range> Ranges,
1851 StringRef FileName,
1852 unsigned *Cursor = nullptr);
1853
1854/// \brief Returns the replacements corresponding to applying and formatting
1855/// \p Replaces on success; otheriwse, return an llvm::Error carrying
1856/// llvm::StringError.
1857llvm::Expected<tooling::Replacements>
1858formatReplacements(StringRef Code, const tooling::Replacements &Replaces,
1859 const FormatStyle &Style);
1860
1861/// \brief Returns the replacements corresponding to applying \p Replaces and
1862/// cleaning up the code after that on success; otherwise, return an llvm::Error
1863/// carrying llvm::StringError.
1864/// This also supports inserting/deleting C++ #include directives:
1865/// - If a replacement has offset UINT_MAX, length 0, and a replacement text
1866/// that is an #include directive, this will insert the #include into the
1867/// correct block in the \p Code. When searching for points to insert new
1868/// header, this ignores #include's after the #include block(s) in the
1869/// beginning of a file to avoid inserting headers into code sections where
1870/// new #include's should not be added by default. These code sections
1871/// include:
1872/// - raw string literals (containing #include).
1873/// - #if blocks.
1874/// - Special #include's among declarations (e.g. functions).
1875/// - If a replacement has offset UINT_MAX, length 1, and a replacement text
1876/// that is the name of the header to be removed, the header will be removed
1877/// from \p Code if it exists.
1878llvm::Expected<tooling::Replacements>
1879cleanupAroundReplacements(StringRef Code, const tooling::Replacements &Replaces,
1880 const FormatStyle &Style);
1881
1882/// \brief Represents the status of a formatting attempt.
1883struct FormattingAttemptStatus {
1884 /// \brief A value of ``false`` means that any of the affected ranges were not
1885 /// formatted due to a non-recoverable syntax error.
1886 bool FormatComplete = true;
1887
1888 /// \brief If ``FormatComplete`` is false, ``Line`` records a one-based
1889 /// original line number at which a syntax error might have occurred. This is
1890 /// based on a best-effort analysis and could be imprecise.
1891 unsigned Line = 0;
1892};
1893
1894/// \brief Reformats the given \p Ranges in \p Code.
1895///
1896/// Each range is extended on either end to its next bigger logic unit, i.e.
1897/// everything that might influence its formatting or might be influenced by its
1898/// formatting.
1899///
1900/// Returns the ``Replacements`` necessary to make all \p Ranges comply with
1901/// \p Style.
1902///
1903/// If ``Status`` is non-null, its value will be populated with the status of
1904/// this formatting attempt. See \c FormattingAttemptStatus.
1905tooling::Replacements reformat(const FormatStyle &Style, StringRef Code,
1906 ArrayRef<tooling::Range> Ranges,
1907 StringRef FileName = "<stdin>",
1908 FormattingAttemptStatus *Status = nullptr);
1909
1910/// \brief Same as above, except if ``IncompleteFormat`` is non-null, its value
1911/// will be set to true if any of the affected ranges were not formatted due to
1912/// a non-recoverable syntax error.
1913tooling::Replacements reformat(const FormatStyle &Style, StringRef Code,
1914 ArrayRef<tooling::Range> Ranges,
1915 StringRef FileName,
1916 bool *IncompleteFormat);
1917
1918/// \brief Clean up any erroneous/redundant code in the given \p Ranges in \p
1919/// Code.
1920///
1921/// Returns the ``Replacements`` that clean up all \p Ranges in \p Code.
1922tooling::Replacements cleanup(const FormatStyle &Style, StringRef Code,
1923 ArrayRef<tooling::Range> Ranges,
1924 StringRef FileName = "<stdin>");
1925
1926/// \brief Fix namespace end comments in the given \p Ranges in \p Code.
1927///
1928/// Returns the ``Replacements`` that fix the namespace comments in all
1929/// \p Ranges in \p Code.
1930tooling::Replacements fixNamespaceEndComments(const FormatStyle &Style,
1931 StringRef Code,
1932 ArrayRef<tooling::Range> Ranges,
1933 StringRef FileName = "<stdin>");
1934
1935/// \brief Sort consecutive using declarations in the given \p Ranges in
1936/// \p Code.
1937///
1938/// Returns the ``Replacements`` that sort the using declarations in all
1939/// \p Ranges in \p Code.
1940tooling::Replacements sortUsingDeclarations(const FormatStyle &Style,
1941 StringRef Code,
1942 ArrayRef<tooling::Range> Ranges,
1943 StringRef FileName = "<stdin>");
1944
1945/// \brief Returns the ``LangOpts`` that the formatter expects you to set.
1946///
1947/// \param Style determines specific settings for lexing mode.
1948LangOptions getFormattingLangOpts(const FormatStyle &Style = getLLVMStyle());
1949
1950/// \brief Description to be used for help text for a ``llvm::cl`` option for
1951/// specifying format style. The description is closely related to the operation
1952/// of ``getStyle()``.
1953extern const char *StyleOptionHelpDescription;
1954
1955/// \brief Construct a FormatStyle based on ``StyleName``.
1956///
1957/// ``StyleName`` can take several forms:
1958/// * "{<key>: <value>, ...}" - Set specic style parameters.
1959/// * "<style name>" - One of the style names supported by
1960/// getPredefinedStyle().
1961/// * "file" - Load style configuration from a file called ``.clang-format``
1962/// located in one of the parent directories of ``FileName`` or the current
1963/// directory if ``FileName`` is empty.
1964///
1965/// \param[in] StyleName Style name to interpret according to the description
1966/// above.
1967/// \param[in] FileName Path to start search for .clang-format if ``StyleName``
1968/// == "file".
1969/// \param[in] FallbackStyle The name of a predefined style used to fallback to
1970/// in case \p StyleName is "file" and no file can be found.
1971/// \param[in] Code The actual code to be formatted. Used to determine the
1972/// language if the filename isn't sufficient.
1973/// \param[in] FS The underlying file system, in which the file resides. By
1974/// default, the file system is the real file system.
1975///
1976/// \returns FormatStyle as specified by ``StyleName``. If ``StyleName`` is
1977/// "file" and no file is found, returns ``FallbackStyle``. If no style could be
1978/// determined, returns an Error.
1979llvm::Expected<FormatStyle> getStyle(StringRef StyleName, StringRef FileName,
1980 StringRef FallbackStyle,
1981 StringRef Code = "",
1982 vfs::FileSystem *FS = nullptr);
1983
1984// \brief Returns a string representation of ``Language``.
1985inline StringRef getLanguageName(FormatStyle::LanguageKind Language) {
1986 switch (Language) {
1987 case FormatStyle::LK_Cpp:
1988 return "C++";
1989 case FormatStyle::LK_ObjC:
1990 return "Objective-C";
1991 case FormatStyle::LK_Java:
1992 return "Java";
1993 case FormatStyle::LK_JavaScript:
1994 return "JavaScript";
1995 case FormatStyle::LK_Proto:
1996 return "Proto";
1997 case FormatStyle::LK_TextProto:
1998 return "TextProto";
1999 default:
2000 return "Unknown";
2001 }
2002}
2003
2004} // end namespace format
2005} // end namespace clang
2006
2007namespace std {
2008template <>
2009struct is_error_code_enum<clang::format::ParseError> : std::true_type {};
2010}
2011
2012#endif // LLVM_CLANG_FORMAT_FORMAT_H