Bug Summary

File:tools/clang/include/clang/Format/Format.h
Warning:line 46, column 8
Excessive padding in 'struct clang::format::FormatStyle' (40 padding bytes, where 0 is optimal). Optimal fields order: ForEachMacros, IncludeCategories, CommentPragmas, IncludeIsMainRegex, MacroBlockBegin, MacroBlockEnd, AccessModifierOffset, AlignAfterOpenBracket, AlignEscapedNewlines, AllowShortFunctionsOnASingleLine, AlwaysBreakAfterDefinitionReturnType, AlwaysBreakAfterReturnType, BreakBeforeBinaryOperators, BreakBeforeBraces, ColumnLimit, ConstructorInitializerIndentWidth, ContinuationIndentWidth, IndentWidth, JavaScriptQuotes, Language, MaxEmptyLinesToKeep, NamespaceIndentation, ObjCBlockIndentWidth, 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, BreakConstructorInitializersBeforeComma, BreakAfterJavaFieldAnnotations, BreakStringLiterals, BreakBeforeInheritanceComma, ConstructorInitializerAllOnOneLineOrOnePerLine, Cpp11BracedListStyle, DerivePointerAlignment, DisableFormat, ExperimentalAutoDetectBinPacking, FixNamespaceComments, IndentCaseLabels, IndentWrappedFunctionNames, JavaScriptWrapImports, KeepEmptyLinesAtTheStartOfBlocks, ObjCSpaceAfterProperty, ObjCSpaceBeforeProtocolList, ReflowComments, SortIncludes, SpaceAfterCStyleCast, SpaceAfterTemplateKeyword, SpaceBeforeAssignmentOperators, SpaceInEmptyParentheses, SpacesInAngles, SpacesInContainerLiterals, SpacesInCStyleCastParentheses, SpacesInParentheses, SpacesInSquareBrackets, BraceWrapping, consider reordering the fields or adding explicit padding members

Annotated Source Code

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' (40 padding bytes, where 0 is optimal). Optimal fields order: ForEachMacros, IncludeCategories, CommentPragmas, IncludeIsMainRegex, MacroBlockBegin, MacroBlockEnd, AccessModifierOffset, AlignAfterOpenBracket, AlignEscapedNewlines, AllowShortFunctionsOnASingleLine, AlwaysBreakAfterDefinitionReturnType, AlwaysBreakAfterReturnType, BreakBeforeBinaryOperators, BreakBeforeBraces, ColumnLimit, ConstructorInitializerIndentWidth, ContinuationIndentWidth, IndentWidth, JavaScriptQuotes, Language, MaxEmptyLinesToKeep, NamespaceIndentation, ObjCBlockIndentWidth, 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, BreakConstructorInitializersBeforeComma, BreakAfterJavaFieldAnnotations, BreakStringLiterals, BreakBeforeInheritanceComma, ConstructorInitializerAllOnOneLineOrOnePerLine, Cpp11BracedListStyle, DerivePointerAlignment, DisableFormat, ExperimentalAutoDetectBinPacking, FixNamespaceComments, IndentCaseLabels, IndentWrappedFunctionNames, JavaScriptWrapImports, KeepEmptyLinesAtTheStartOfBlocks, ObjCSpaceAfterProperty, ObjCSpaceBeforeProtocolList, ReflowComments, SortIncludes, 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 Allow putting all parameters of a function declaration onto
155 /// the next line even if ``BinPackParameters`` is ``false``.
156 /// \code
157 /// true: false:
158 /// myFunction(foo, vs. myFunction(foo, bar, plop);
159 /// bar,
160 /// plop);
161 /// \endcode
162 bool AllowAllParametersOfDeclarationOnNextLine;
163
164 /// \brief Allows contracting simple braced statements to a single line.
165 ///
166 /// E.g., this allows ``if (a) { return; }`` to be put on a single line.
167 bool AllowShortBlocksOnASingleLine;
168
169 /// \brief If ``true``, short case labels will be contracted to a single line.
170 /// \code
171 /// true: false:
172 /// switch (a) { vs. switch (a) {
173 /// case 1: x = 1; break; case 1:
174 /// case 2: return; x = 1;
175 /// } break;
176 /// case 2:
177 /// return;
178 /// }
179 /// \endcode
180 bool AllowShortCaseLabelsOnASingleLine;
181
182 /// \brief Different styles for merging short functions containing at most one
183 /// statement.
184 enum ShortFunctionStyle {
185 /// \brief Never merge functions into a single line.
186 SFS_None,
187 /// \brief Only merge empty functions.
188 /// \code
189 /// void f() { bar(); }
190 /// void f2() {
191 /// bar2();
192 /// }
193 /// \endcode
194 SFS_Empty,
195 /// \brief Only merge functions defined inside a class. Implies "empty".
196 /// \code
197 /// class Foo {
198 /// void f() { foo(); }
199 /// };
200 /// \endcode
201 SFS_Inline,
202 /// \brief Merge all functions fitting on a single line.
203 /// \code
204 /// class Foo {
205 /// void f() { foo(); }
206 /// };
207 /// void f() { bar(); }
208 /// \endcode
209 SFS_All,
210 };
211
212 /// \brief Dependent on the value, ``int f() { return 0; }`` can be put on a
213 /// single line.
214 ShortFunctionStyle AllowShortFunctionsOnASingleLine;
215
216 /// \brief If ``true``, ``if (a) return;`` can be put on a single line.
217 bool AllowShortIfStatementsOnASingleLine;
218
219 /// \brief If ``true``, ``while (true) continue;`` can be put on a single
220 /// line.
221 bool AllowShortLoopsOnASingleLine;
222
223 /// \brief Different ways to break after the function definition return type.
224 /// This option is **deprecated** and is retained for backwards compatibility.
225 enum DefinitionReturnTypeBreakingStyle {
226 /// Break after return type automatically.
227 /// ``PenaltyReturnTypeOnItsOwnLine`` is taken into account.
228 DRTBS_None,
229 /// Always break after the return type.
230 DRTBS_All,
231 /// Always break after the return types of top-level functions.
232 DRTBS_TopLevel,
233 };
234
235 /// \brief Different ways to break after the function definition or
236 /// declaration return type.
237 enum ReturnTypeBreakingStyle {
238 /// Break after return type automatically.
239 /// ``PenaltyReturnTypeOnItsOwnLine`` is taken into account.
240 /// \code
241 /// class A {
242 /// int f() { return 0; };
243 /// };
244 /// int f();
245 /// int f() { return 1; }
246 /// \endcode
247 RTBS_None,
248 /// Always break after the return type.
249 /// \code
250 /// class A {
251 /// int
252 /// f() {
253 /// return 0;
254 /// };
255 /// };
256 /// int
257 /// f();
258 /// int
259 /// f() {
260 /// return 1;
261 /// }
262 /// \endcode
263 RTBS_All,
264 /// Always break after the return types of top-level functions.
265 /// \code
266 /// class A {
267 /// int f() { return 0; };
268 /// };
269 /// int
270 /// f();
271 /// int
272 /// f() {
273 /// return 1;
274 /// }
275 /// \endcode
276 RTBS_TopLevel,
277 /// Always break after the return type of function definitions.
278 /// \code
279 /// class A {
280 /// int
281 /// f() {
282 /// return 0;
283 /// };
284 /// };
285 /// int f();
286 /// int
287 /// f() {
288 /// return 1;
289 /// }
290 /// \endcode
291 RTBS_AllDefinitions,
292 /// Always break after the return type of top-level definitions.
293 /// \code
294 /// class A {
295 /// int f() { return 0; };
296 /// };
297 /// int f();
298 /// int
299 /// f() {
300 /// return 1;
301 /// }
302 /// \endcode
303 RTBS_TopLevelDefinitions,
304 };
305
306 /// \brief The function definition return type breaking style to use. This
307 /// option is **deprecated** and is retained for backwards compatibility.
308 DefinitionReturnTypeBreakingStyle AlwaysBreakAfterDefinitionReturnType;
309
310 /// \brief The function declaration return type breaking style to use.
311 ReturnTypeBreakingStyle AlwaysBreakAfterReturnType;
312
313 /// \brief If ``true``, always break before multiline string literals.
314 ///
315 /// This flag is mean to make cases where there are multiple multiline strings
316 /// in a file look more consistent. Thus, it will only take effect if wrapping
317 /// the string at that point leads to it being indented
318 /// ``ContinuationIndentWidth`` spaces from the start of the line.
319 /// \code
320 /// true: false:
321 /// aaaa = vs. aaaa = "bbbb"
322 /// "bbbb" "cccc";
323 /// "cccc";
324 /// \endcode
325 bool AlwaysBreakBeforeMultilineStrings;
326
327 /// \brief If ``true``, always break after the ``template<...>`` of a template
328 /// declaration.
329 /// \code
330 /// true: false:
331 /// template <typename T> vs. template <typename T> class C {};
332 /// class C {};
333 /// \endcode
334 bool AlwaysBreakTemplateDeclarations;
335
336 /// \brief If ``false``, a function call's arguments will either be all on the
337 /// same line or will have one line each.
338 /// \code
339 /// true:
340 /// void f() {
341 /// f(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaa,
342 /// aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);
343 /// }
344 ///
345 /// false:
346 /// void f() {
347 /// f(aaaaaaaaaaaaaaaaaaaa,
348 /// aaaaaaaaaaaaaaaaaaaa,
349 /// aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);
350 /// }
351 /// \endcode
352 bool BinPackArguments;
353
354 /// \brief If ``false``, a function declaration's or function definition's
355 /// parameters will either all be on the same line or will have one line each.
356 /// \code
357 /// true:
358 /// void f(int aaaaaaaaaaaaaaaaaaaa, int aaaaaaaaaaaaaaaaaaaa,
359 /// int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}
360 ///
361 /// false:
362 /// void f(int aaaaaaaaaaaaaaaaaaaa,
363 /// int aaaaaaaaaaaaaaaaaaaa,
364 /// int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}
365 /// \endcode
366 bool BinPackParameters;
367
368 /// \brief The style of breaking before or after binary operators.
369 enum BinaryOperatorStyle {
370 /// Break after operators.
371 /// \code
372 /// LooooooooooongType loooooooooooooooooooooongVariable =
373 /// someLooooooooooooooooongFunction();
374 ///
375 /// bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +
376 /// aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==
377 /// aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa &&
378 /// aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >
379 /// ccccccccccccccccccccccccccccccccccccccccc;
380 /// \endcode
381 BOS_None,
382 /// Break before operators that aren't assignments.
383 /// \code
384 /// LooooooooooongType loooooooooooooooooooooongVariable =
385 /// someLooooooooooooooooongFunction();
386 ///
387 /// bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
388 /// + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
389 /// == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
390 /// && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
391 /// > ccccccccccccccccccccccccccccccccccccccccc;
392 /// \endcode
393 BOS_NonAssignment,
394 /// Break before operators.
395 /// \code
396 /// LooooooooooongType loooooooooooooooooooooongVariable
397 /// = someLooooooooooooooooongFunction();
398 ///
399 /// bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
400 /// + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
401 /// == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
402 /// && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
403 /// > ccccccccccccccccccccccccccccccccccccccccc;
404 /// \endcode
405 BOS_All,
406 };
407
408 /// \brief The way to wrap binary operators.
409 BinaryOperatorStyle BreakBeforeBinaryOperators;
410
411 /// \brief Different ways to attach braces to their surrounding context.
412 enum BraceBreakingStyle {
413 /// Always attach braces to surrounding context.
414 /// \code
415 /// try {
416 /// foo();
417 /// } catch () {
418 /// }
419 /// void foo() { bar(); }
420 /// class foo {};
421 /// if (foo()) {
422 /// } else {
423 /// }
424 /// enum X : int { A, B };
425 /// \endcode
426 BS_Attach,
427 /// Like ``Attach``, but break before braces on function, namespace and
428 /// class definitions.
429 /// \code
430 /// try {
431 /// foo();
432 /// } catch () {
433 /// }
434 /// void foo() { bar(); }
435 /// class foo
436 /// {
437 /// };
438 /// if (foo()) {
439 /// } else {
440 /// }
441 /// enum X : int { A, B };
442 /// \endcode
443 BS_Linux,
444 /// Like ``Attach``, but break before braces on enum, function, and record
445 /// definitions.
446 /// \code
447 /// try {
448 /// foo();
449 /// } catch () {
450 /// }
451 /// void foo() { bar(); }
452 /// class foo
453 /// {
454 /// };
455 /// if (foo()) {
456 /// } else {
457 /// }
458 /// enum X : int { A, B };
459 /// \endcode
460 BS_Mozilla,
461 /// Like ``Attach``, but break before function definitions, ``catch``, and
462 /// ``else``.
463 /// \code
464 /// try {
465 /// foo();
466 /// } catch () {
467 /// }
468 /// void foo() { bar(); }
469 /// class foo
470 /// {
471 /// };
472 /// if (foo()) {
473 /// } else {
474 /// }
475 /// enum X : int
476 /// {
477 /// A,
478 /// B
479 /// };
480 /// \endcode
481 BS_Stroustrup,
482 /// Always break before braces.
483 /// \code
484 /// try {
485 /// foo();
486 /// }
487 /// catch () {
488 /// }
489 /// void foo() { bar(); }
490 /// class foo {
491 /// };
492 /// if (foo()) {
493 /// }
494 /// else {
495 /// }
496 /// enum X : int { A, B };
497 /// \endcode
498 BS_Allman,
499 /// Always break before braces and add an extra level of indentation to
500 /// braces of control statements, not to those of class, function
501 /// or other definitions.
502 /// \code
503 /// try
504 /// {
505 /// foo();
506 /// }
507 /// catch ()
508 /// {
509 /// }
510 /// void foo() { bar(); }
511 /// class foo
512 /// {
513 /// };
514 /// if (foo())
515 /// {
516 /// }
517 /// else
518 /// {
519 /// }
520 /// enum X : int
521 /// {
522 /// A,
523 /// B
524 /// };
525 /// \endcode
526 BS_GNU,
527 /// Like ``Attach``, but break before functions.
528 /// \code
529 /// try {
530 /// foo();
531 /// } catch () {
532 /// }
533 /// void foo() { bar(); }
534 /// class foo {
535 /// };
536 /// if (foo()) {
537 /// } else {
538 /// }
539 /// enum X : int { A, B };
540 /// \endcode
541 BS_WebKit,
542 /// Configure each individual brace in `BraceWrapping`.
543 BS_Custom
544 };
545
546 /// \brief The brace breaking style to use.
547 BraceBreakingStyle BreakBeforeBraces;
548
549 /// \brief Precise control over the wrapping of braces.
550 /// \code
551 /// # Should be declared this way:
552 /// BreakBeforeBraces: Custom
553 /// BraceWrapping:
554 /// AfterClass: true
555 /// \endcode
556 struct BraceWrappingFlags {
557 /// \brief Wrap class definitions.
558 /// \code
559 /// true:
560 /// class foo {};
561 ///
562 /// false:
563 /// class foo
564 /// {};
565 /// \endcode
566 bool AfterClass;
567 /// \brief Wrap control statements (``if``/``for``/``while``/``switch``/..).
568 /// \code
569 /// true:
570 /// if (foo())
571 /// {
572 /// } else
573 /// {}
574 /// for (int i = 0; i < 10; ++i)
575 /// {}
576 ///
577 /// false:
578 /// if (foo()) {
579 /// } else {
580 /// }
581 /// for (int i = 0; i < 10; ++i) {
582 /// }
583 /// \endcode
584 bool AfterControlStatement;
585 /// \brief Wrap enum definitions.
586 /// \code
587 /// true:
588 /// enum X : int
589 /// {
590 /// B
591 /// };
592 ///
593 /// false:
594 /// enum X : int { B };
595 /// \endcode
596 bool AfterEnum;
597 /// \brief Wrap function definitions.
598 /// \code
599 /// true:
600 /// void foo()
601 /// {
602 /// bar();
603 /// bar2();
604 /// }
605 ///
606 /// false:
607 /// void foo() {
608 /// bar();
609 /// bar2();
610 /// }
611 /// \endcode
612 bool AfterFunction;
613 /// \brief Wrap namespace definitions.
614 /// \code
615 /// true:
616 /// namespace
617 /// {
618 /// int foo();
619 /// int bar();
620 /// }
621 ///
622 /// false:
623 /// namespace {
624 /// int foo();
625 /// int bar();
626 /// }
627 /// \endcode
628 bool AfterNamespace;
629 /// \brief Wrap ObjC definitions (``@autoreleasepool``, interfaces, ..).
630 bool AfterObjCDeclaration;
631 /// \brief Wrap struct definitions.
632 /// \code
633 /// true:
634 /// struct foo
635 /// {
636 /// int x;
637 /// }
638 ///
639 /// false:
640 /// struct foo {
641 /// int x;
642 /// }
643 /// \endcode
644 bool AfterStruct;
645 /// \brief Wrap union definitions.
646 /// \code
647 /// true:
648 /// union foo
649 /// {
650 /// int x;
651 /// }
652 ///
653 /// false:
654 /// union foo {
655 /// int x;
656 /// }
657 /// \endcode
658 bool AfterUnion;
659 /// \brief Wrap before ``catch``.
660 /// \code
661 /// true:
662 /// try {
663 /// foo();
664 /// }
665 /// catch () {
666 /// }
667 ///
668 /// false:
669 /// try {
670 /// foo();
671 /// } catch () {
672 /// }
673 /// \endcode
674 bool BeforeCatch;
675 /// \brief Wrap before ``else``.
676 /// \code
677 /// true:
678 /// if (foo()) {
679 /// }
680 /// else {
681 /// }
682 ///
683 /// false:
684 /// if (foo()) {
685 /// } else {
686 /// }
687 /// \endcode
688 bool BeforeElse;
689 /// \brief Indent the wrapped braces themselves.
690 bool IndentBraces;
691 };
692
693 /// \brief Control of individual brace wrapping cases.
694 ///
695 /// If ``BreakBeforeBraces`` is set to ``BS_Custom``, use this to specify how
696 /// each individual brace case should be handled. Otherwise, this is ignored.
697 BraceWrappingFlags BraceWrapping;
698
699 /// \brief If ``true``, ternary operators will be placed after line breaks.
700 /// \code
701 /// true:
702 /// veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongDescription
703 /// ? firstValue
704 /// : SecondValueVeryVeryVeryVeryLong;
705 ///
706 /// true:
707 /// veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongDescription ?
708 /// firstValue :
709 /// SecondValueVeryVeryVeryVeryLong;
710 /// \endcode
711 bool BreakBeforeTernaryOperators;
712
713 /// \brief Always break constructor initializers before commas and align
714 /// the commas with the colon.
715 /// \code
716 /// true: false:
717 /// SomeClass::Constructor() vs. SomeClass::Constructor() : a(a),
718 /// : a(a) b(b),
719 /// , b(b) c(c) {}
720 /// , c(c) {}
721 /// \endcode
722 bool BreakConstructorInitializersBeforeComma;
723
724 /// \brief Break after each annotation on a field in Java files.
725 /// \code{.java}
726 /// true: false:
727 /// @Partial vs. @Partial @Mock DataLoad loader;
728 /// @Mock
729 /// DataLoad loader;
730 /// \endcode
731 bool BreakAfterJavaFieldAnnotations;
732
733 /// \brief Allow breaking string literals when formatting.
734 bool BreakStringLiterals;
735
736 /// \brief The column limit.
737 ///
738 /// A column limit of ``0`` means that there is no column limit. In this case,
739 /// clang-format will respect the input's line breaking decisions within
740 /// statements unless they contradict other rules.
741 unsigned ColumnLimit;
742
743 /// \brief A regular expression that describes comments with special meaning,
744 /// which should not be split into lines or otherwise changed.
745 /// \code
746 /// // CommentPragmas: '^ FOOBAR pragma:'
747 /// // Will leave the following line unaffected
748 /// #include <vector> // FOOBAR pragma: keep
749 /// \endcode
750 std::string CommentPragmas;
751
752 /// \brief If ``true``, in the class inheritance expression clang-format will
753 /// break before ``:`` and ``,`` if there is multiple inheritance.
754 /// \code
755 /// true: false:
756 /// class MyClass vs. class MyClass : public X, public Y {
757 /// : public X };
758 /// , public Y {
759 /// };
760 /// \endcode
761 bool BreakBeforeInheritanceComma;
762
763 /// \brief If the constructor initializers don't fit on a line, put each
764 /// initializer on its own line.
765 /// \code
766 /// true:
767 /// SomeClass::Constructor()
768 /// : aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa) {
769 /// return 0;
770 /// }
771 ///
772 /// false:
773 /// SomeClass::Constructor()
774 /// : aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaa),
775 /// aaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa) {
776 /// return 0;
777 /// }
778 /// \endcode
779 bool ConstructorInitializerAllOnOneLineOrOnePerLine;
780
781 /// \brief The number of characters to use for indentation of constructor
782 /// initializer lists.
783 unsigned ConstructorInitializerIndentWidth;
784
785 /// \brief Indent width for line continuations.
786 /// \code
787 /// ContinuationIndentWidth: 2
788 ///
789 /// int i = // VeryVeryVeryVeryVeryLongComment
790 /// longFunction( // Again a long comment
791 /// arg);
792 /// \endcode
793 unsigned ContinuationIndentWidth;
794
795 /// \brief If ``true``, format braced lists as best suited for C++11 braced
796 /// lists.
797 ///
798 /// Important differences:
799 /// - No spaces inside the braced list.
800 /// - No line break before the closing brace.
801 /// - Indentation with the continuation indent, not with the block indent.
802 ///
803 /// Fundamentally, C++11 braced lists are formatted exactly like function
804 /// calls would be formatted in their place. If the braced list follows a name
805 /// (e.g. a type or variable name), clang-format formats as if the ``{}`` were
806 /// the parentheses of a function call with that name. If there is no name,
807 /// a zero-length name is assumed.
808 /// \code
809 /// true: false:
810 /// vector<int> x{1, 2, 3, 4}; vs. vector<int> x{ 1, 2, 3, 4 };
811 /// vector<T> x{{}, {}, {}, {}}; vector<T> x{ {}, {}, {}, {} };
812 /// f(MyMap[{composite, key}]); f(MyMap[{ composite, key }]);
813 /// new int[3]{1, 2, 3}; new int[3]{ 1, 2, 3 };
814 /// \endcode
815 bool Cpp11BracedListStyle;
816
817 /// \brief If ``true``, analyze the formatted file for the most common
818 /// alignment of ``&`` and ``*``.
819 /// Pointer and reference alignment styles are going to be updated according
820 /// to the preferences found in the file.
821 /// ``PointerAlignment`` is then used only as fallback.
822 bool DerivePointerAlignment;
823
824 /// \brief Disables formatting completely.
825 bool DisableFormat;
826
827 /// \brief If ``true``, clang-format detects whether function calls and
828 /// definitions are formatted with one parameter per line.
829 ///
830 /// Each call can be bin-packed, one-per-line or inconclusive. If it is
831 /// inconclusive, e.g. completely on one line, but a decision needs to be
832 /// made, clang-format analyzes whether there are other bin-packed cases in
833 /// the input file and act accordingly.
834 ///
835 /// NOTE: This is an experimental flag, that might go away or be renamed. Do
836 /// not use this in config files, etc. Use at your own risk.
837 bool ExperimentalAutoDetectBinPacking;
838
839 /// \brief If ``true``, clang-format adds missing namespace end comments and
840 /// fixes invalid existing ones.
841 /// \code
842 /// true: false:
843 /// namespace a { vs. namespace a {
844 /// foo(); foo();
845 /// } // namespace a; }
846 /// \endcode
847 bool FixNamespaceComments;
848
849 /// \brief A vector of macros that should be interpreted as foreach loops
850 /// instead of as function calls.
851 ///
852 /// These are expected to be macros of the form:
853 /// \code
854 /// FOREACH(<variable-declaration>, ...)
855 /// <loop-body>
856 /// \endcode
857 ///
858 /// In the .clang-format configuration file, this can be configured like:
859 /// \code{.yaml}
860 /// ForEachMacros: ['RANGES_FOR', 'FOREACH']
861 /// \endcode
862 ///
863 /// For example: BOOST_FOREACH.
864 std::vector<std::string> ForEachMacros;
865
866 /// \brief See documentation of ``IncludeCategories``.
867 struct IncludeCategory {
868 /// \brief The regular expression that this category matches.
869 std::string Regex;
870 /// \brief The priority to assign to this category.
871 int Priority;
872 bool operator==(const IncludeCategory &Other) const {
873 return Regex == Other.Regex && Priority == Other.Priority;
874 }
875 };
876
877 /// \brief Regular expressions denoting the different ``#include`` categories
878 /// used for ordering ``#includes``.
879 ///
880 /// These regular expressions are matched against the filename of an include
881 /// (including the <> or "") in order. The value belonging to the first
882 /// matching regular expression is assigned and ``#includes`` are sorted first
883 /// according to increasing category number and then alphabetically within
884 /// each category.
885 ///
886 /// If none of the regular expressions match, INT_MAX is assigned as
887 /// category. The main header for a source file automatically gets category 0.
888 /// so that it is generally kept at the beginning of the ``#includes``
889 /// (http://llvm.org/docs/CodingStandards.html#include-style). However, you
890 /// can also assign negative priorities if you have certain headers that
891 /// always need to be first.
892 ///
893 /// To configure this in the .clang-format file, use:
894 /// \code{.yaml}
895 /// IncludeCategories:
896 /// - Regex: '^"(llvm|llvm-c|clang|clang-c)/'
897 /// Priority: 2
898 /// - Regex: '^(<|"(gtest|isl|json)/)'
899 /// Priority: 3
900 /// - Regex: '.*'
901 /// Priority: 1
902 /// \endcode
903 std::vector<IncludeCategory> IncludeCategories;
904
905 /// \brief Specify a regular expression of suffixes that are allowed in the
906 /// file-to-main-include mapping.
907 ///
908 /// When guessing whether a #include is the "main" include (to assign
909 /// category 0, see above), use this regex of allowed suffixes to the header
910 /// stem. A partial match is done, so that:
911 /// - "" means "arbitrary suffix"
912 /// - "$" means "no suffix"
913 ///
914 /// For example, if configured to "(_test)?$", then a header a.h would be seen
915 /// as the "main" include in both a.cc and a_test.cc.
916 std::string IncludeIsMainRegex;
917
918 /// \brief Indent case labels one level from the switch statement.
919 ///
920 /// When ``false``, use the same indentation level as for the switch statement.
921 /// Switch statement body is always indented one level more than case labels.
922 /// \code
923 /// false: true:
924 /// switch (fool) { vs. switch (fool) {
925 /// case 1: case 1:
926 /// bar(); bar();
927 /// break; break;
928 /// default: default:
929 /// plop(); plop();
930 /// } }
931 /// \endcode
932 bool IndentCaseLabels;
933
934 /// \brief The number of columns to use for indentation.
935 /// \code
936 /// IndentWidth: 3
937 ///
938 /// void f() {
939 /// someFunction();
940 /// if (true, false) {
941 /// f();
942 /// }
943 /// }
944 /// \endcode
945 unsigned IndentWidth;
946
947 /// \brief Indent if a function definition or declaration is wrapped after the
948 /// type.
949 /// \code
950 /// true:
951 /// LoooooooooooooooooooooooooooooooooooooooongReturnType
952 /// LoooooooooooooooooooooooooooooooongFunctionDeclaration();
953 ///
954 /// false:
955 /// LoooooooooooooooooooooooooooooooooooooooongReturnType
956 /// LoooooooooooooooooooooooooooooooongFunctionDeclaration();
957 /// \endcode
958 bool IndentWrappedFunctionNames;
959
960 /// \brief Quotation styles for JavaScript strings. Does not affect template
961 /// strings.
962 enum JavaScriptQuoteStyle {
963 /// Leave string quotes as they are.
964 /// \code{.js}
965 /// string1 = "foo";
966 /// string2 = 'bar';
967 /// \endcode
968 JSQS_Leave,
969 /// Always use single quotes.
970 /// \code{.js}
971 /// string1 = 'foo';
972 /// string2 = 'bar';
973 /// \endcode
974 JSQS_Single,
975 /// Always use double quotes.
976 /// \code{.js}
977 /// string1 = "foo";
978 /// string2 = "bar";
979 /// \endcode
980 JSQS_Double
981 };
982
983 /// \brief The JavaScriptQuoteStyle to use for JavaScript strings.
984 JavaScriptQuoteStyle JavaScriptQuotes;
985
986 /// \brief Whether to wrap JavaScript import/export statements.
987 /// \code{.js}
988 /// true:
989 /// import {
990 /// VeryLongImportsAreAnnoying,
991 /// VeryLongImportsAreAnnoying,
992 /// VeryLongImportsAreAnnoying,
993 /// } from 'some/module.js'
994 ///
995 /// false:
996 /// import {VeryLongImportsAreAnnoying, VeryLongImportsAreAnnoying, VeryLongImportsAreAnnoying,} from "some/module.js"
997 /// \endcode
998 bool JavaScriptWrapImports;
999
1000 /// \brief If true, the empty line at the start of blocks is kept.
1001 /// \code
1002 /// true: false:
1003 /// if (foo) { vs. if (foo) {
1004 /// bar();
1005 /// bar(); }
1006 /// }
1007 /// \endcode
1008 bool KeepEmptyLinesAtTheStartOfBlocks;
1009
1010 /// \brief Supported languages.
1011 ///
1012 /// When stored in a configuration file, specifies the language, that the
1013 /// configuration targets. When passed to the ``reformat()`` function, enables
1014 /// syntax features specific to the language.
1015 enum LanguageKind {
1016 /// Do not use.
1017 LK_None,
1018 /// Should be used for C, C++.
1019 LK_Cpp,
1020 /// Should be used for Java.
1021 LK_Java,
1022 /// Should be used for JavaScript.
1023 LK_JavaScript,
1024 /// Should be used for Objective-C, Objective-C++.
1025 LK_ObjC,
1026 /// Should be used for Protocol Buffers
1027 /// (https://developers.google.com/protocol-buffers/).
1028 LK_Proto,
1029 /// Should be used for TableGen code.
1030 LK_TableGen
1031 };
1032 bool isCpp() const { return Language == LK_Cpp || Language == LK_ObjC; }
1033
1034 /// \brief Language, this format style is targeted at.
1035 LanguageKind Language;
1036
1037 /// \brief A regular expression matching macros that start a block.
1038 /// \code
1039 /// # With:
1040 /// MacroBlockBegin: "^NS_MAP_BEGIN|\
1041 /// NS_TABLE_HEAD$"
1042 /// MacroBlockEnd: "^\
1043 /// NS_MAP_END|\
1044 /// NS_TABLE_.*_END$"
1045 ///
1046 /// NS_MAP_BEGIN
1047 /// foo();
1048 /// NS_MAP_END
1049 ///
1050 /// NS_TABLE_HEAD
1051 /// bar();
1052 /// NS_TABLE_FOO_END
1053 ///
1054 /// # Without:
1055 /// NS_MAP_BEGIN
1056 /// foo();
1057 /// NS_MAP_END
1058 ///
1059 /// NS_TABLE_HEAD
1060 /// bar();
1061 /// NS_TABLE_FOO_END
1062 /// \endcode
1063 std::string MacroBlockBegin;
1064
1065 /// \brief A regular expression matching macros that end a block.
1066 std::string MacroBlockEnd;
1067
1068 /// \brief The maximum number of consecutive empty lines to keep.
1069 /// \code
1070 /// MaxEmptyLinesToKeep: 1 vs. MaxEmptyLinesToKeep: 0
1071 /// int f() { int f() {
1072 /// int = 1; int i = 1;
1073 /// i = foo();
1074 /// i = foo(); return i;
1075 /// }
1076 /// return i;
1077 /// }
1078 /// \endcode
1079 unsigned MaxEmptyLinesToKeep;
1080
1081 /// \brief Different ways to indent namespace contents.
1082 enum NamespaceIndentationKind {
1083 /// Don't indent in namespaces.
1084 /// \code
1085 /// namespace out {
1086 /// int i;
1087 /// namespace in {
1088 /// int i;
1089 /// }
1090 /// }
1091 /// \endcode
1092 NI_None,
1093 /// Indent only in inner namespaces (nested in other namespaces).
1094 /// \code
1095 /// namespace out {
1096 /// int i;
1097 /// namespace in {
1098 /// int i;
1099 /// }
1100 /// }
1101 /// \endcode
1102 NI_Inner,
1103 /// Indent in all namespaces.
1104 /// \code
1105 /// namespace out {
1106 /// int i;
1107 /// namespace in {
1108 /// int i;
1109 /// }
1110 /// }
1111 /// \endcode
1112 NI_All
1113 };
1114
1115 /// \brief The indentation used for namespaces.
1116 NamespaceIndentationKind NamespaceIndentation;
1117
1118 /// \brief The number of characters to use for indentation of ObjC blocks.
1119 /// \code{.objc}
1120 /// ObjCBlockIndentWidth: 4
1121 ///
1122 /// [operation setCompletionBlock:^{
1123 /// [self onOperationDone];
1124 /// }];
1125 /// \endcode
1126 unsigned ObjCBlockIndentWidth;
1127
1128 /// \brief Add a space after ``@property`` in Objective-C, i.e. use
1129 /// ``@property (readonly)`` instead of ``@property(readonly)``.
1130 bool ObjCSpaceAfterProperty;
1131
1132 /// \brief Add a space in front of an Objective-C protocol list, i.e. use
1133 /// ``Foo <Protocol>`` instead of ``Foo<Protocol>``.
1134 bool ObjCSpaceBeforeProtocolList;
1135
1136 /// \brief The penalty for breaking a function call after ``call(``.
1137 unsigned PenaltyBreakBeforeFirstCallParameter;
1138
1139 /// \brief The penalty for each line break introduced inside a comment.
1140 unsigned PenaltyBreakComment;
1141
1142 /// \brief The penalty for breaking before the first ``<<``.
1143 unsigned PenaltyBreakFirstLessLess;
1144
1145 /// \brief The penalty for each line break introduced inside a string literal.
1146 unsigned PenaltyBreakString;
1147
1148 /// \brief The penalty for each character outside of the column limit.
1149 unsigned PenaltyExcessCharacter;
1150
1151 /// \brief Penalty for putting the return type of a function onto its own
1152 /// line.
1153 unsigned PenaltyReturnTypeOnItsOwnLine;
1154
1155 /// \brief The ``&`` and ``*`` alignment style.
1156 enum PointerAlignmentStyle {
1157 /// Align pointer to the left.
1158 /// \code
1159 /// int* a;
1160 /// \endcode
1161 PAS_Left,
1162 /// Align pointer to the right.
1163 /// \code
1164 /// int *a;
1165 /// \endcode
1166 PAS_Right,
1167 /// Align pointer in the middle.
1168 /// \code
1169 /// int * a;
1170 /// \endcode
1171 PAS_Middle
1172 };
1173
1174 /// \brief Pointer and reference alignment style.
1175 PointerAlignmentStyle PointerAlignment;
1176
1177 /// \brief If ``true``, clang-format will attempt to re-flow comments.
1178 /// \code
1179 /// false:
1180 /// // veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongComment with plenty of information
1181 /// /* second veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongComment with plenty of information */
1182 ///
1183 /// true:
1184 /// // veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongComment with plenty of
1185 /// // information
1186 /// /* second veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongComment with plenty of
1187 /// * information */
1188 /// \endcode
1189 bool ReflowComments;
1190
1191 /// \brief If ``true``, clang-format will sort ``#includes``.
1192 /// \code
1193 /// false: true:
1194 /// #include "b.h" vs. #include "a.h"
1195 /// #include "a.h" #include "b.h"
1196 /// \endcode
1197 bool SortIncludes;
1198
1199 /// \brief If ``true``, a space is inserted after C style casts.
1200 /// \code
1201 /// true: false:
1202 /// (int)i; vs. (int) i;
1203 /// \endcode
1204 bool SpaceAfterCStyleCast;
1205
1206 /// \brief If \c true, a space will be inserted after the 'template' keyword.
1207 /// \code
1208 /// true: false:
1209 /// template <int> void foo(); vs. template<int> void foo();
1210 /// \endcode
1211 bool SpaceAfterTemplateKeyword;
1212
1213 /// \brief If ``false``, spaces will be removed before assignment operators.
1214 /// \code
1215 /// true: false:
1216 /// int a = 5; vs. int a=5;
1217 /// a += 42 a+=42;
1218 /// \endcode
1219 bool SpaceBeforeAssignmentOperators;
1220
1221 /// \brief Different ways to put a space before opening parentheses.
1222 enum SpaceBeforeParensOptions {
1223 /// Never put a space before opening parentheses.
1224 /// \code
1225 /// void f() {
1226 /// if(true) {
1227 /// f();
1228 /// }
1229 /// }
1230 /// \endcode
1231 SBPO_Never,
1232 /// Put a space before opening parentheses only after control statement
1233 /// keywords (``for/if/while...``).
1234 /// \code
1235 /// void f() {
1236 /// if (true) {
1237 /// f();
1238 /// }
1239 /// }
1240 /// \endcode
1241 SBPO_ControlStatements,
1242 /// Always put a space before opening parentheses, except when it's
1243 /// prohibited by the syntax rules (in function-like macro definitions) or
1244 /// when determined by other style rules (after unary operators, opening
1245 /// parentheses, etc.)
1246 /// \code
1247 /// void f () {
1248 /// if (true) {
1249 /// f ();
1250 /// }
1251 /// }
1252 /// \endcode
1253 SBPO_Always
1254 };
1255
1256 /// \brief Defines in which cases to put a space before opening parentheses.
1257 SpaceBeforeParensOptions SpaceBeforeParens;
1258
1259 /// \brief If ``true``, spaces may be inserted into ``()``.
1260 /// \code
1261 /// true: false:
1262 /// void f( ) { vs. void f() {
1263 /// int x[] = {foo( ), bar( )}; int x[] = {foo(), bar()};
1264 /// if (true) { if (true) {
1265 /// f( ); f();
1266 /// } }
1267 /// } }
1268 /// \endcode
1269 bool SpaceInEmptyParentheses;
1270
1271 /// \brief The number of spaces before trailing line comments
1272 /// (``//`` - comments).
1273 ///
1274 /// This does not affect trailing block comments (``/*`` - comments) as
1275 /// those commonly have different usage patterns and a number of special
1276 /// cases.
1277 /// \code
1278 /// SpacesBeforeTrailingComments: 3
1279 /// void f() {
1280 /// if (true) { // foo1
1281 /// f(); // bar
1282 /// } // foo
1283 /// }
1284 /// \endcode
1285 unsigned SpacesBeforeTrailingComments;
1286
1287 /// \brief If ``true``, spaces will be inserted after ``<`` and before ``>``
1288 /// in template argument lists.
1289 /// \code
1290 /// true: false:
1291 /// static_cast< int >(arg); vs. static_cast<int>(arg);
1292 /// std::function< void(int) > fct; std::function<void(int)> fct;
1293 /// \endcode
1294 bool SpacesInAngles;
1295
1296 /// \brief If ``true``, spaces are inserted inside container literals (e.g.
1297 /// ObjC and Javascript array and dict literals).
1298 /// \code{.js}
1299 /// true: false:
1300 /// var arr = [ 1, 2, 3 ]; vs. var arr = [1, 2, 3];
1301 /// f({a : 1, b : 2, c : 3}); f({a: 1, b: 2, c: 3});
1302 /// \endcode
1303 bool SpacesInContainerLiterals;
1304
1305 /// \brief If ``true``, spaces may be inserted into C style casts.
1306 /// \code
1307 /// true: false:
1308 /// x = ( int32 )y vs. x = (int32)y
1309 /// \endcode
1310 bool SpacesInCStyleCastParentheses;
1311
1312 /// \brief If ``true``, spaces will be inserted after ``(`` and before ``)``.
1313 /// \code
1314 /// true: false:
1315 /// t f( Deleted & ) & = delete; vs. t f(Deleted &) & = delete;
1316 /// \endcode
1317 bool SpacesInParentheses;
1318
1319 /// \brief If ``true``, spaces will be inserted after ``[`` and before ``]``.
1320 /// Lambdas or unspecified size array declarations will not be affected.
1321 /// \code
1322 /// true: false:
1323 /// int a[ 5 ]; vs. int a[5];
1324 /// std::unique_ptr<int[]> foo() {} // Won't be affected
1325 /// \endcode
1326 bool SpacesInSquareBrackets;
1327
1328 /// \brief Supported language standards.
1329 enum LanguageStandard {
1330 /// Use C++03-compatible syntax.
1331 LS_Cpp03,
1332 /// Use features of C++11, C++14 and C++1z (e.g. ``A<A<int>>`` instead of
1333 /// ``A<A<int> >``).
1334 LS_Cpp11,
1335 /// Automatic detection based on the input.
1336 LS_Auto
1337 };
1338
1339 /// \brief Format compatible with this standard, e.g. use ``A<A<int> >``
1340 /// instead of ``A<A<int>>`` for ``LS_Cpp03``.
1341 LanguageStandard Standard;
1342
1343 /// \brief The number of columns used for tab stops.
1344 unsigned TabWidth;
1345
1346 /// \brief Different ways to use tab in formatting.
1347 enum UseTabStyle {
1348 /// Never use tab.
1349 UT_Never,
1350 /// Use tabs only for indentation.
1351 UT_ForIndentation,
1352 /// Use tabs only for line continuation and indentation.
1353 UT_ForContinuationAndIndentation,
1354 /// Use tabs whenever we need to fill whitespace that spans at least from
1355 /// one tab stop to the next one.
1356 UT_Always
1357 };
1358
1359 /// \brief The way to use tab characters in the resulting file.
1360 UseTabStyle UseTab;
1361
1362 bool operator==(const FormatStyle &R) const {
1363 return AccessModifierOffset == R.AccessModifierOffset &&
1364 AlignAfterOpenBracket == R.AlignAfterOpenBracket &&
1365 AlignConsecutiveAssignments == R.AlignConsecutiveAssignments &&
1366 AlignConsecutiveDeclarations == R.AlignConsecutiveDeclarations &&
1367 AlignEscapedNewlines == R.AlignEscapedNewlines &&
1368 AlignOperands == R.AlignOperands &&
1369 AlignTrailingComments == R.AlignTrailingComments &&
1370 AllowAllParametersOfDeclarationOnNextLine ==
1371 R.AllowAllParametersOfDeclarationOnNextLine &&
1372 AllowShortBlocksOnASingleLine == R.AllowShortBlocksOnASingleLine &&
1373 AllowShortCaseLabelsOnASingleLine ==
1374 R.AllowShortCaseLabelsOnASingleLine &&
1375 AllowShortFunctionsOnASingleLine ==
1376 R.AllowShortFunctionsOnASingleLine &&
1377 AllowShortIfStatementsOnASingleLine ==
1378 R.AllowShortIfStatementsOnASingleLine &&
1379 AllowShortLoopsOnASingleLine == R.AllowShortLoopsOnASingleLine &&
1380 AlwaysBreakAfterReturnType == R.AlwaysBreakAfterReturnType &&
1381 AlwaysBreakBeforeMultilineStrings ==
1382 R.AlwaysBreakBeforeMultilineStrings &&
1383 AlwaysBreakTemplateDeclarations ==
1384 R.AlwaysBreakTemplateDeclarations &&
1385 BinPackArguments == R.BinPackArguments &&
1386 BinPackParameters == R.BinPackParameters &&
1387 BreakBeforeBinaryOperators == R.BreakBeforeBinaryOperators &&
1388 BreakBeforeBraces == R.BreakBeforeBraces &&
1389 BreakBeforeTernaryOperators == R.BreakBeforeTernaryOperators &&
1390 BreakConstructorInitializersBeforeComma ==
1391 R.BreakConstructorInitializersBeforeComma &&
1392 BreakAfterJavaFieldAnnotations == R.BreakAfterJavaFieldAnnotations &&
1393 BreakStringLiterals == R.BreakStringLiterals &&
1394 ColumnLimit == R.ColumnLimit && CommentPragmas == R.CommentPragmas &&
1395 BreakBeforeInheritanceComma == R.BreakBeforeInheritanceComma &&
1396 ConstructorInitializerAllOnOneLineOrOnePerLine ==
1397 R.ConstructorInitializerAllOnOneLineOrOnePerLine &&
1398 ConstructorInitializerIndentWidth ==
1399 R.ConstructorInitializerIndentWidth &&
1400 ContinuationIndentWidth == R.ContinuationIndentWidth &&
1401 Cpp11BracedListStyle == R.Cpp11BracedListStyle &&
1402 DerivePointerAlignment == R.DerivePointerAlignment &&
1403 DisableFormat == R.DisableFormat &&
1404 ExperimentalAutoDetectBinPacking ==
1405 R.ExperimentalAutoDetectBinPacking &&
1406 FixNamespaceComments == R.FixNamespaceComments &&
1407 ForEachMacros == R.ForEachMacros &&
1408 IncludeCategories == R.IncludeCategories &&
1409 IndentCaseLabels == R.IndentCaseLabels &&
1410 IndentWidth == R.IndentWidth && Language == R.Language &&
1411 IndentWrappedFunctionNames == R.IndentWrappedFunctionNames &&
1412 JavaScriptQuotes == R.JavaScriptQuotes &&
1413 JavaScriptWrapImports == R.JavaScriptWrapImports &&
1414 KeepEmptyLinesAtTheStartOfBlocks ==
1415 R.KeepEmptyLinesAtTheStartOfBlocks &&
1416 MacroBlockBegin == R.MacroBlockBegin &&
1417 MacroBlockEnd == R.MacroBlockEnd &&
1418 MaxEmptyLinesToKeep == R.MaxEmptyLinesToKeep &&
1419 NamespaceIndentation == R.NamespaceIndentation &&
1420 ObjCBlockIndentWidth == R.ObjCBlockIndentWidth &&
1421 ObjCSpaceAfterProperty == R.ObjCSpaceAfterProperty &&
1422 ObjCSpaceBeforeProtocolList == R.ObjCSpaceBeforeProtocolList &&
1423 PenaltyBreakBeforeFirstCallParameter ==
1424 R.PenaltyBreakBeforeFirstCallParameter &&
1425 PenaltyBreakComment == R.PenaltyBreakComment &&
1426 PenaltyBreakFirstLessLess == R.PenaltyBreakFirstLessLess &&
1427 PenaltyBreakString == R.PenaltyBreakString &&
1428 PenaltyExcessCharacter == R.PenaltyExcessCharacter &&
1429 PenaltyReturnTypeOnItsOwnLine == R.PenaltyReturnTypeOnItsOwnLine &&
1430 PointerAlignment == R.PointerAlignment &&
1431 SpaceAfterCStyleCast == R.SpaceAfterCStyleCast &&
1432 SpaceAfterTemplateKeyword == R.SpaceAfterTemplateKeyword &&
1433 SpaceBeforeAssignmentOperators == R.SpaceBeforeAssignmentOperators &&
1434 SpaceBeforeParens == R.SpaceBeforeParens &&
1435 SpaceInEmptyParentheses == R.SpaceInEmptyParentheses &&
1436 SpacesBeforeTrailingComments == R.SpacesBeforeTrailingComments &&
1437 SpacesInAngles == R.SpacesInAngles &&
1438 SpacesInContainerLiterals == R.SpacesInContainerLiterals &&
1439 SpacesInCStyleCastParentheses == R.SpacesInCStyleCastParentheses &&
1440 SpacesInParentheses == R.SpacesInParentheses &&
1441 SpacesInSquareBrackets == R.SpacesInSquareBrackets &&
1442 Standard == R.Standard && TabWidth == R.TabWidth &&
1443 UseTab == R.UseTab;
1444 }
1445};
1446
1447/// \brief Returns a format style complying with the LLVM coding standards:
1448/// http://llvm.org/docs/CodingStandards.html.
1449FormatStyle getLLVMStyle();
1450
1451/// \brief Returns a format style complying with one of Google's style guides:
1452/// http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml.
1453/// http://google-styleguide.googlecode.com/svn/trunk/javascriptguide.xml.
1454/// https://developers.google.com/protocol-buffers/docs/style.
1455FormatStyle getGoogleStyle(FormatStyle::LanguageKind Language);
1456
1457/// \brief Returns a format style complying with Chromium's style guide:
1458/// http://www.chromium.org/developers/coding-style.
1459FormatStyle getChromiumStyle(FormatStyle::LanguageKind Language);
1460
1461/// \brief Returns a format style complying with Mozilla's style guide:
1462/// https://developer.mozilla.org/en-US/docs/Developer_Guide/Coding_Style.
1463FormatStyle getMozillaStyle();
1464
1465/// \brief Returns a format style complying with Webkit's style guide:
1466/// http://www.webkit.org/coding/coding-style.html
1467FormatStyle getWebKitStyle();
1468
1469/// \brief Returns a format style complying with GNU Coding Standards:
1470/// http://www.gnu.org/prep/standards/standards.html
1471FormatStyle getGNUStyle();
1472
1473/// \brief Returns style indicating formatting should be not applied at all.
1474FormatStyle getNoStyle();
1475
1476/// \brief Gets a predefined style for the specified language by name.
1477///
1478/// Currently supported names: LLVM, Google, Chromium, Mozilla. Names are
1479/// compared case-insensitively.
1480///
1481/// Returns ``true`` if the Style has been set.
1482bool getPredefinedStyle(StringRef Name, FormatStyle::LanguageKind Language,
1483 FormatStyle *Style);
1484
1485/// \brief Parse configuration from YAML-formatted text.
1486///
1487/// Style->Language is used to get the base style, if the ``BasedOnStyle``
1488/// option is present.
1489///
1490/// When ``BasedOnStyle`` is not present, options not present in the YAML
1491/// document, are retained in \p Style.
1492std::error_code parseConfiguration(StringRef Text, FormatStyle *Style);
1493
1494/// \brief Gets configuration in a YAML string.
1495std::string configurationAsText(const FormatStyle &Style);
1496
1497/// \brief Returns the replacements necessary to sort all ``#include`` blocks
1498/// that are affected by ``Ranges``.
1499tooling::Replacements sortIncludes(const FormatStyle &Style, StringRef Code,
1500 ArrayRef<tooling::Range> Ranges,
1501 StringRef FileName,
1502 unsigned *Cursor = nullptr);
1503
1504/// \brief Returns the replacements corresponding to applying and formatting
1505/// \p Replaces on success; otheriwse, return an llvm::Error carrying
1506/// llvm::StringError.
1507llvm::Expected<tooling::Replacements>
1508formatReplacements(StringRef Code, const tooling::Replacements &Replaces,
1509 const FormatStyle &Style);
1510
1511/// \brief Returns the replacements corresponding to applying \p Replaces and
1512/// cleaning up the code after that on success; otherwise, return an llvm::Error
1513/// carrying llvm::StringError.
1514/// This also supports inserting/deleting C++ #include directives:
1515/// - If a replacement has offset UINT_MAX, length 0, and a replacement text
1516/// that is an #include directive, this will insert the #include into the
1517/// correct block in the \p Code. When searching for points to insert new
1518/// header, this ignores #include's after the #include block(s) in the
1519/// beginning of a file to avoid inserting headers into code sections where
1520/// new #include's should not be added by default. These code sections
1521/// include:
1522/// - raw string literals (containing #include).
1523/// - #if blocks.
1524/// - Special #include's among declarations (e.g. functions).
1525/// - If a replacement has offset UINT_MAX, length 1, and a replacement text
1526/// that is the name of the header to be removed, the header will be removed
1527/// from \p Code if it exists.
1528llvm::Expected<tooling::Replacements>
1529cleanupAroundReplacements(StringRef Code, const tooling::Replacements &Replaces,
1530 const FormatStyle &Style);
1531
1532/// \brief Represents the status of a formatting attempt.
1533struct FormattingAttemptStatus {
1534 /// \brief A value of ``false`` means that any of the affected ranges were not
1535 /// formatted due to a non-recoverable syntax error.
1536 bool FormatComplete = true;
1537
1538 /// \brief If ``FormatComplete`` is false, ``Line`` records a one-based
1539 /// original line number at which a syntax error might have occurred. This is
1540 /// based on a best-effort analysis and could be imprecise.
1541 unsigned Line = 0;
1542};
1543
1544/// \brief Reformats the given \p Ranges in \p Code.
1545///
1546/// Each range is extended on either end to its next bigger logic unit, i.e.
1547/// everything that might influence its formatting or might be influenced by its
1548/// formatting.
1549///
1550/// Returns the ``Replacements`` necessary to make all \p Ranges comply with
1551/// \p Style.
1552///
1553/// If ``Status`` is non-null, its value will be populated with the status of
1554/// this formatting attempt. See \c FormattingAttemptStatus.
1555tooling::Replacements reformat(const FormatStyle &Style, StringRef Code,
1556 ArrayRef<tooling::Range> Ranges,
1557 StringRef FileName = "<stdin>",
1558 FormattingAttemptStatus *Status = nullptr);
1559
1560/// \brief Same as above, except if ``IncompleteFormat`` is non-null, its value
1561/// will be set to true if any of the affected ranges were not formatted due to
1562/// a non-recoverable syntax error.
1563tooling::Replacements reformat(const FormatStyle &Style, StringRef Code,
1564 ArrayRef<tooling::Range> Ranges,
1565 StringRef FileName,
1566 bool *IncompleteFormat);
1567
1568/// \brief Clean up any erroneous/redundant code in the given \p Ranges in \p
1569/// Code.
1570///
1571/// Returns the ``Replacements`` that clean up all \p Ranges in \p Code.
1572tooling::Replacements cleanup(const FormatStyle &Style, StringRef Code,
1573 ArrayRef<tooling::Range> Ranges,
1574 StringRef FileName = "<stdin>");
1575
1576/// \brief Fix namespace end comments in the given \p Ranges in \p Code.
1577///
1578/// Returns the ``Replacements`` that fix the namespace comments in all
1579/// \p Ranges in \p Code.
1580tooling::Replacements fixNamespaceEndComments(const FormatStyle &Style,
1581 StringRef Code,
1582 ArrayRef<tooling::Range> Ranges,
1583 StringRef FileName = "<stdin>");
1584
1585/// \brief Returns the ``LangOpts`` that the formatter expects you to set.
1586///
1587/// \param Style determines specific settings for lexing mode.
1588LangOptions getFormattingLangOpts(const FormatStyle &Style = getLLVMStyle());
1589
1590/// \brief Description to be used for help text for a ``llvm::cl`` option for
1591/// specifying format style. The description is closely related to the operation
1592/// of ``getStyle()``.
1593extern const char *StyleOptionHelpDescription;
1594
1595/// \brief Construct a FormatStyle based on ``StyleName``.
1596///
1597/// ``StyleName`` can take several forms:
1598/// * "{<key>: <value>, ...}" - Set specic style parameters.
1599/// * "<style name>" - One of the style names supported by
1600/// getPredefinedStyle().
1601/// * "file" - Load style configuration from a file called ``.clang-format``
1602/// located in one of the parent directories of ``FileName`` or the current
1603/// directory if ``FileName`` is empty.
1604///
1605/// \param[in] StyleName Style name to interpret according to the description
1606/// above.
1607/// \param[in] FileName Path to start search for .clang-format if ``StyleName``
1608/// == "file".
1609/// \param[in] FallbackStyle The name of a predefined style used to fallback to
1610/// in case \p StyleName is "file" and no file can be found.
1611/// \param[in] Code The actual code to be formatted. Used to determine the
1612/// language if the filename isn't sufficient.
1613/// \param[in] FS The underlying file system, in which the file resides. By
1614/// default, the file system is the real file system.
1615///
1616/// \returns FormatStyle as specified by ``StyleName``. If ``StyleName`` is
1617/// "file" and no file is found, returns ``FallbackStyle``. If no style could be
1618/// determined, returns an Error.
1619llvm::Expected<FormatStyle> getStyle(StringRef StyleName, StringRef FileName,
1620 StringRef FallbackStyle,
1621 StringRef Code = "",
1622 vfs::FileSystem *FS = nullptr);
1623
1624// \brief Returns a string representation of ``Language``.
1625inline StringRef getLanguageName(FormatStyle::LanguageKind Language) {
1626 switch (Language) {
1627 case FormatStyle::LK_Cpp:
1628 return "C++";
1629 case FormatStyle::LK_ObjC:
1630 return "Objective-C";
1631 case FormatStyle::LK_Java:
1632 return "Java";
1633 case FormatStyle::LK_JavaScript:
1634 return "JavaScript";
1635 case FormatStyle::LK_Proto:
1636 return "Proto";
1637 default:
1638 return "Unknown";
1639 }
1640}
1641
1642} // end namespace format
1643} // end namespace clang
1644
1645namespace std {
1646template <>
1647struct is_error_code_enum<clang::format::ParseError> : std::true_type {};
1648}
1649
1650#endif // LLVM_CLANG_FORMAT_FORMAT_H