Coverage Report

Created: 2020-09-19 12:23

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/include/clang/Format/Format.h
Line
Count
Source (jump to first uncovered line)
1
//===--- Format.h - Format C++ code -----------------------------*- C++ -*-===//
2
//
3
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
// See https://llvm.org/LICENSE.txt for license information.
5
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
//
7
//===----------------------------------------------------------------------===//
8
///
9
/// \file
10
/// Various functions to configurably format source code.
11
///
12
//===----------------------------------------------------------------------===//
13
14
#ifndef LLVM_CLANG_FORMAT_FORMAT_H
15
#define LLVM_CLANG_FORMAT_FORMAT_H
16
17
#include "clang/Basic/LangOptions.h"
18
#include "clang/Tooling/Core/Replacement.h"
19
#include "clang/Tooling/Inclusions/IncludeStyle.h"
20
#include "llvm/ADT/ArrayRef.h"
21
#include "llvm/Support/Regex.h"
22
#include <system_error>
23
24
namespace llvm {
25
namespace vfs {
26
class FileSystem;
27
}
28
} // namespace llvm
29
30
namespace clang {
31
32
class Lexer;
33
class SourceManager;
34
class DiagnosticConsumer;
35
36
namespace format {
37
38
enum class ParseError {
39
  Success = 0,
40
  Error,
41
  Unsuitable,
42
  BinPackTrailingCommaConflict
43
};
44
class ParseErrorCategory final : public std::error_category {
45
public:
46
  const char *name() const noexcept override;
47
  std::string message(int EV) const override;
48
};
49
const std::error_category &getParseCategory();
50
std::error_code make_error_code(ParseError e);
51
52
/// The ``FormatStyle`` is used to configure the formatting to follow
53
/// specific guidelines.
54
struct FormatStyle {
55
  /// The extra indent or outdent of access modifiers, e.g. ``public:``.
56
  int AccessModifierOffset;
57
58
  /// Different styles for aligning after open brackets.
59
  enum BracketAlignmentStyle {
60
    /// Align parameters on the open bracket, e.g.:
61
    /// \code
62
    ///   someLongFunction(argument1,
63
    ///                    argument2);
64
    /// \endcode
65
    BAS_Align,
66
    /// Don't align, instead use ``ContinuationIndentWidth``, e.g.:
67
    /// \code
68
    ///   someLongFunction(argument1,
69
    ///       argument2);
70
    /// \endcode
71
    BAS_DontAlign,
72
    /// Always break after an open bracket, if the parameters don't fit
73
    /// on a single line, e.g.:
74
    /// \code
75
    ///   someLongFunction(
76
    ///       argument1, argument2);
77
    /// \endcode
78
    BAS_AlwaysBreak,
79
  };
80
81
  /// If ``true``, horizontally aligns arguments after an open bracket.
82
  ///
83
  /// This applies to round brackets (parentheses), angle brackets and square
84
  /// brackets.
85
  BracketAlignmentStyle AlignAfterOpenBracket;
86
87
  /// \brief If ``true``, aligns consecutive C/C++ preprocessor macros.
88
  ///
89
  /// This will align C/C++ preprocessor macros of consecutive lines.
90
  /// Will result in formattings like
91
  /// \code
92
  ///   #define SHORT_NAME       42
93
  ///   #define LONGER_NAME      0x007f
94
  ///   #define EVEN_LONGER_NAME (2)
95
  ///   #define foo(x)           (x * x)
96
  ///   #define bar(y, z)        (y + z)
97
  /// \endcode
98
  bool AlignConsecutiveMacros;
99
100
  /// If ``true``, aligns consecutive assignments.
101
  ///
102
  /// This will align the assignment operators of consecutive lines. This
103
  /// will result in formattings like
104
  /// \code
105
  ///   int aaaa = 12;
106
  ///   int b    = 23;
107
  ///   int ccc  = 23;
108
  /// \endcode
109
  bool AlignConsecutiveAssignments;
110
111
  /// If ``true``, aligns consecutive bitfield members.
112
  ///
113
  /// This will align the bitfield separators of consecutive lines. This
114
  /// will result in formattings like
115
  /// \code
116
  ///   int aaaa : 1;
117
  ///   int b    : 12;
118
  ///   int ccc  : 8;
119
  /// \endcode
120
  bool AlignConsecutiveBitFields;
121
122
  /// If ``true``, aligns consecutive declarations.
123
  ///
124
  /// This will align the declaration names of consecutive lines. This
125
  /// will result in formattings like
126
  /// \code
127
  ///   int         aaaa = 12;
128
  ///   float       b = 23;
129
  ///   std::string ccc = 23;
130
  /// \endcode
131
  bool AlignConsecutiveDeclarations;
132
133
  /// Different styles for aligning escaped newlines.
134
  enum EscapedNewlineAlignmentStyle {
135
    /// Don't align escaped newlines.
136
    /// \code
137
    ///   #define A \
138
    ///     int aaaa; \
139
    ///     int b; \
140
    ///     int dddddddddd;
141
    /// \endcode
142
    ENAS_DontAlign,
143
    /// Align escaped newlines as far left as possible.
144
    /// \code
145
    ///   true:
146
    ///   #define A   \
147
    ///     int aaaa; \
148
    ///     int b;    \
149
    ///     int dddddddddd;
150
    ///
151
    ///   false:
152
    /// \endcode
153
    ENAS_Left,
154
    /// Align escaped newlines in the right-most column.
155
    /// \code
156
    ///   #define A                                                                      \
157
    ///     int aaaa;                                                                    \
158
    ///     int b;                                                                       \
159
    ///     int dddddddddd;
160
    /// \endcode
161
    ENAS_Right,
162
  };
163
164
  /// Options for aligning backslashes in escaped newlines.
165
  EscapedNewlineAlignmentStyle AlignEscapedNewlines;
166
167
  /// Different styles for aligning operands.
168
  enum OperandAlignmentStyle {
169
    /// Do not align operands of binary and ternary expressions.
170
    /// The wrapped lines are indented ``ContinuationIndentWidth`` spaces from
171
    /// the start of the line.
172
    OAS_DontAlign,
173
    /// Horizontally align operands of binary and ternary expressions.
174
    ///
175
    /// Specifically, this aligns operands of a single expression that needs
176
    /// to be split over multiple lines, e.g.:
177
    /// \code
178
    ///   int aaa = bbbbbbbbbbbbbbb +
179
    ///             ccccccccccccccc;
180
    /// \endcode
181
    ///
182
    /// When ``BreakBeforeBinaryOperators`` is set, the wrapped operator is
183
    /// aligned with the operand on the first line.
184
    /// \code
185
    ///   int aaa = bbbbbbbbbbbbbbb
186
    ///             + ccccccccccccccc;
187
    /// \endcode
188
    OAS_Align,
189
    /// Horizontally align operands of binary and ternary expressions.
190
    ///
191
    /// This is similar to ``AO_Align``, except when
192
    /// ``BreakBeforeBinaryOperators`` is set, the operator is un-indented so
193
    /// that the wrapped operand is aligned with the operand on the first line.
194
    /// \code
195
    ///   int aaa = bbbbbbbbbbbbbbb
196
    ///           + ccccccccccccccc;
197
    /// \endcode
198
    OAS_AlignAfterOperator,
199
  };
200
201
  /// If ``true``, horizontally align operands of binary and ternary
202
  /// expressions.
203
  OperandAlignmentStyle AlignOperands;
204
205
  /// If ``true``, aligns trailing comments.
206
  /// \code
207
  ///   true:                                   false:
208
  ///   int a;     // My comment a      vs.     int a; // My comment a
209
  ///   int b = 2; // comment  b                int b = 2; // comment about b
210
  /// \endcode
211
  bool AlignTrailingComments;
212
213
  /// \brief If a function call or braced initializer list doesn't fit on a
214
  /// line, allow putting all arguments onto the next line, even if
215
  /// ``BinPackArguments`` is ``false``.
216
  /// \code
217
  ///   true:
218
  ///   callFunction(
219
  ///       a, b, c, d);
220
  ///
221
  ///   false:
222
  ///   callFunction(a,
223
  ///                b,
224
  ///                c,
225
  ///                d);
226
  /// \endcode
227
  bool AllowAllArgumentsOnNextLine;
228
229
  /// \brief If a constructor definition with a member initializer list doesn't
230
  /// fit on a single line, allow putting all member initializers onto the next
231
  /// line, if ```ConstructorInitializerAllOnOneLineOrOnePerLine``` is true.
232
  /// Note that this parameter has no effect if
233
  /// ```ConstructorInitializerAllOnOneLineOrOnePerLine``` is false.
234
  /// \code
235
  ///   true:
236
  ///   MyClass::MyClass() :
237
  ///       member0(0), member1(2) {}
238
  ///
239
  ///   false:
240
  ///   MyClass::MyClass() :
241
  ///       member0(0),
242
  ///       member1(2) {}
243
  bool AllowAllConstructorInitializersOnNextLine;
244
245
  /// If the function declaration doesn't fit on a line,
246
  /// allow putting all parameters of a function declaration onto
247
  /// the next line even if ``BinPackParameters`` is ``false``.
248
  /// \code
249
  ///   true:
250
  ///   void myFunction(
251
  ///       int a, int b, int c, int d, int e);
252
  ///
253
  ///   false:
254
  ///   void myFunction(int a,
255
  ///                   int b,
256
  ///                   int c,
257
  ///                   int d,
258
  ///                   int e);
259
  /// \endcode
260
  bool AllowAllParametersOfDeclarationOnNextLine;
261
262
  /// Allow short enums on a single line.
263
  /// \code
264
  ///   true:
265
  ///   enum { A, B } myEnum;
266
  ///
267
  ///   false:
268
  ///   enum
269
  ///   {
270
  ///     A,
271
  ///     B
272
  ///   } myEnum;
273
  /// \endcode
274
  bool AllowShortEnumsOnASingleLine;
275
276
  /// Different styles for merging short blocks containing at most one
277
  /// statement.
278
  enum ShortBlockStyle {
279
    /// Never merge blocks into a single line.
280
    /// \code
281
    ///   while (true) {
282
    ///   }
283
    ///   while (true) {
284
    ///     continue;
285
    ///   }
286
    /// \endcode
287
    SBS_Never,
288
    /// Only merge empty blocks.
289
    /// \code
290
    ///   while (true) {}
291
    ///   while (true) {
292
    ///     continue;
293
    ///   }
294
    /// \endcode
295
    SBS_Empty,
296
    /// Always merge short blocks into a single line.
297
    /// \code
298
    ///   while (true) {}
299
    ///   while (true) { continue; }
300
    /// \endcode
301
    SBS_Always,
302
  };
303
304
  /// Dependent on the value, ``while (true) { continue; }`` can be put on a
305
  /// single line.
306
  ShortBlockStyle AllowShortBlocksOnASingleLine;
307
308
  /// If ``true``, short case labels will be contracted to a single line.
309
  /// \code
310
  ///   true:                                   false:
311
  ///   switch (a) {                    vs.     switch (a) {
312
  ///   case 1: x = 1; break;                   case 1:
313
  ///   case 2: return;                           x = 1;
314
  ///   }                                         break;
315
  ///                                           case 2:
316
  ///                                             return;
317
  ///                                           }
318
  /// \endcode
319
  bool AllowShortCaseLabelsOnASingleLine;
320
321
  /// Different styles for merging short functions containing at most one
322
  /// statement.
323
  enum ShortFunctionStyle {
324
    /// Never merge functions into a single line.
325
    SFS_None,
326
    /// Only merge functions defined inside a class. Same as "inline",
327
    /// except it does not implies "empty": i.e. top level empty functions
328
    /// are not merged either.
329
    /// \code
330
    ///   class Foo {
331
    ///     void f() { foo(); }
332
    ///   };
333
    ///   void f() {
334
    ///     foo();
335
    ///   }
336
    ///   void f() {
337
    ///   }
338
    /// \endcode
339
    SFS_InlineOnly,
340
    /// Only merge empty functions.
341
    /// \code
342
    ///   void f() {}
343
    ///   void f2() {
344
    ///     bar2();
345
    ///   }
346
    /// \endcode
347
    SFS_Empty,
348
    /// Only merge functions defined inside a class. Implies "empty".
349
    /// \code
350
    ///   class Foo {
351
    ///     void f() { foo(); }
352
    ///   };
353
    ///   void f() {
354
    ///     foo();
355
    ///   }
356
    ///   void f() {}
357
    /// \endcode
358
    SFS_Inline,
359
    /// Merge all functions fitting on a single line.
360
    /// \code
361
    ///   class Foo {
362
    ///     void f() { foo(); }
363
    ///   };
364
    ///   void f() { bar(); }
365
    /// \endcode
366
    SFS_All,
367
  };
368
369
  /// Dependent on the value, ``int f() { return 0; }`` can be put on a
370
  /// single line.
371
  ShortFunctionStyle AllowShortFunctionsOnASingleLine;
372
373
  /// Different styles for handling short if lines
374
  enum ShortIfStyle {
375
    /// Never put short ifs on the same line.
376
    /// \code
377
    ///   if (a)
378
    ///     return ;
379
    ///   else {
380
    ///     return;
381
    ///   }
382
    /// \endcode
383
    SIS_Never,
384
    /// Without else put short ifs on the same line only if
385
    /// the else is not a compound statement.
386
    /// \code
387
    ///   if (a) return;
388
    ///   else
389
    ///     return;
390
    /// \endcode
391
    SIS_WithoutElse,
392
    /// Always put short ifs on the same line if
393
    /// the else is not a compound statement or not.
394
    /// \code
395
    ///   if (a) return;
396
    ///   else {
397
    ///     return;
398
    ///   }
399
    /// \endcode
400
    SIS_Always,
401
  };
402
403
  /// If ``true``, ``if (a) return;`` can be put on a single line.
404
  ShortIfStyle AllowShortIfStatementsOnASingleLine;
405
406
  /// Different styles for merging short lambdas containing at most one
407
  /// statement.
408
  enum ShortLambdaStyle {
409
    /// Never merge lambdas into a single line.
410
    SLS_None,
411
    /// Only merge empty lambdas.
412
    /// \code
413
    ///   auto lambda = [](int a) {}
414
    ///   auto lambda2 = [](int a) {
415
    ///       return a;
416
    ///   };
417
    /// \endcode
418
    SLS_Empty,
419
    /// Merge lambda into a single line if argument of a function.
420
    /// \code
421
    ///   auto lambda = [](int a) {
422
    ///       return a;
423
    ///   };
424
    ///   sort(a.begin(), a.end(), ()[] { return x < y; })
425
    /// \endcode
426
    SLS_Inline,
427
    /// Merge all lambdas fitting on a single line.
428
    /// \code
429
    ///   auto lambda = [](int a) {}
430
    ///   auto lambda2 = [](int a) { return a; };
431
    /// \endcode
432
    SLS_All,
433
  };
434
435
  /// Dependent on the value, ``auto lambda []() { return 0; }`` can be put on a
436
  /// single line.
437
  ShortLambdaStyle AllowShortLambdasOnASingleLine;
438
439
  /// If ``true``, ``while (true) continue;`` can be put on a single
440
  /// line.
441
  bool AllowShortLoopsOnASingleLine;
442
443
  /// Different ways to break after the function definition return type.
444
  /// This option is **deprecated** and is retained for backwards compatibility.
445
  enum DefinitionReturnTypeBreakingStyle {
446
    /// Break after return type automatically.
447
    /// ``PenaltyReturnTypeOnItsOwnLine`` is taken into account.
448
    DRTBS_None,
449
    /// Always break after the return type.
450
    DRTBS_All,
451
    /// Always break after the return types of top-level functions.
452
    DRTBS_TopLevel,
453
  };
454
455
  /// Different ways to break after the function definition or
456
  /// declaration return type.
457
  enum ReturnTypeBreakingStyle {
458
    /// Break after return type automatically.
459
    /// ``PenaltyReturnTypeOnItsOwnLine`` is taken into account.
460
    /// \code
461
    ///   class A {
462
    ///     int f() { return 0; };
463
    ///   };
464
    ///   int f();
465
    ///   int f() { return 1; }
466
    /// \endcode
467
    RTBS_None,
468
    /// Always break after the return type.
469
    /// \code
470
    ///   class A {
471
    ///     int
472
    ///     f() {
473
    ///       return 0;
474
    ///     };
475
    ///   };
476
    ///   int
477
    ///   f();
478
    ///   int
479
    ///   f() {
480
    ///     return 1;
481
    ///   }
482
    /// \endcode
483
    RTBS_All,
484
    /// Always break after the return types of top-level functions.
485
    /// \code
486
    ///   class A {
487
    ///     int f() { return 0; };
488
    ///   };
489
    ///   int
490
    ///   f();
491
    ///   int
492
    ///   f() {
493
    ///     return 1;
494
    ///   }
495
    /// \endcode
496
    RTBS_TopLevel,
497
    /// Always break after the return type of function definitions.
498
    /// \code
499
    ///   class A {
500
    ///     int
501
    ///     f() {
502
    ///       return 0;
503
    ///     };
504
    ///   };
505
    ///   int f();
506
    ///   int
507
    ///   f() {
508
    ///     return 1;
509
    ///   }
510
    /// \endcode
511
    RTBS_AllDefinitions,
512
    /// Always break after the return type of top-level definitions.
513
    /// \code
514
    ///   class A {
515
    ///     int f() { return 0; };
516
    ///   };
517
    ///   int f();
518
    ///   int
519
    ///   f() {
520
    ///     return 1;
521
    ///   }
522
    /// \endcode
523
    RTBS_TopLevelDefinitions,
524
  };
525
526
  /// The function definition return type breaking style to use.  This
527
  /// option is **deprecated** and is retained for backwards compatibility.
528
  DefinitionReturnTypeBreakingStyle AlwaysBreakAfterDefinitionReturnType;
529
530
  /// The function declaration return type breaking style to use.
531
  ReturnTypeBreakingStyle AlwaysBreakAfterReturnType;
532
533
  /// If ``true``, always break before multiline string literals.
534
  ///
535
  /// This flag is mean to make cases where there are multiple multiline strings
536
  /// in a file look more consistent. Thus, it will only take effect if wrapping
537
  /// the string at that point leads to it being indented
538
  /// ``ContinuationIndentWidth`` spaces from the start of the line.
539
  /// \code
540
  ///    true:                                  false:
541
  ///    aaaa =                         vs.     aaaa = "bbbb"
542
  ///        "bbbb"                                    "cccc";
543
  ///        "cccc";
544
  /// \endcode
545
  bool AlwaysBreakBeforeMultilineStrings;
546
547
  /// Different ways to break after the template declaration.
548
  enum BreakTemplateDeclarationsStyle {
549
    /// Do not force break before declaration.
550
    /// ``PenaltyBreakTemplateDeclaration`` is taken into account.
551
    /// \code
552
    ///    template <typename T> T foo() {
553
    ///    }
554
    ///    template <typename T> T foo(int aaaaaaaaaaaaaaaaaaaaa,
555
    ///                                int bbbbbbbbbbbbbbbbbbbbb) {
556
    ///    }
557
    /// \endcode
558
    BTDS_No,
559
    /// Force break after template declaration only when the following
560
    /// declaration spans multiple lines.
561
    /// \code
562
    ///    template <typename T> T foo() {
563
    ///    }
564
    ///    template <typename T>
565
    ///    T foo(int aaaaaaaaaaaaaaaaaaaaa,
566
    ///          int bbbbbbbbbbbbbbbbbbbbb) {
567
    ///    }
568
    /// \endcode
569
    BTDS_MultiLine,
570
    /// Always break after template declaration.
571
    /// \code
572
    ///    template <typename T>
573
    ///    T foo() {
574
    ///    }
575
    ///    template <typename T>
576
    ///    T foo(int aaaaaaaaaaaaaaaaaaaaa,
577
    ///          int bbbbbbbbbbbbbbbbbbbbb) {
578
    ///    }
579
    /// \endcode
580
    BTDS_Yes
581
  };
582
583
  /// The template declaration breaking style to use.
584
  BreakTemplateDeclarationsStyle AlwaysBreakTemplateDeclarations;
585
586
  /// A vector of strings that should be interpreted as attributes/qualifiers
587
  /// instead of identifiers. This can be useful for language extensions or
588
  /// static analyzer annotations.
589
  ///
590
  /// For example:
591
  /// \code
592
  ///   x = (char *__capability)&y;
593
  ///   int function(void) __ununsed;
594
  ///   void only_writes_to_buffer(char *__output buffer);
595
  /// \endcode
596
  ///
597
  /// In the .clang-format configuration file, this can be configured like:
598
  /// \code{.yaml}
599
  ///   AttributeMacros: ['__capability', '__output', '__ununsed']
600
  /// \endcode
601
  ///
602
  std::vector<std::string> AttributeMacros;
603
604
  /// If ``false``, a function call's arguments will either be all on the
605
  /// same line or will have one line each.
606
  /// \code
607
  ///   true:
608
  ///   void f() {
609
  ///     f(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaa,
610
  ///       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);
611
  ///   }
612
  ///
613
  ///   false:
614
  ///   void f() {
615
  ///     f(aaaaaaaaaaaaaaaaaaaa,
616
  ///       aaaaaaaaaaaaaaaaaaaa,
617
  ///       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);
618
  ///   }
619
  /// \endcode
620
  bool BinPackArguments;
621
622
  /// The style of inserting trailing commas into container literals.
623
  enum TrailingCommaStyle {
624
    /// Do not insert trailing commas.
625
    TCS_None,
626
    /// Insert trailing commas in container literals that were wrapped over
627
    /// multiple lines. Note that this is conceptually incompatible with
628
    /// bin-packing, because the trailing comma is used as an indicator
629
    /// that a container should be formatted one-per-line (i.e. not bin-packed).
630
    /// So inserting a trailing comma counteracts bin-packing.
631
    TCS_Wrapped,
632
  };
633
634
  /// If set to ``TCS_Wrapped`` will insert trailing commas in container
635
  /// literals (arrays and objects) that wrap across multiple lines.
636
  /// It is currently only available for JavaScript
637
  /// and disabled by default ``TCS_None``.
638
  /// ``InsertTrailingCommas`` cannot be used together with ``BinPackArguments``
639
  /// as inserting the comma disables bin-packing.
640
  /// \code
641
  ///   TSC_Wrapped:
642
  ///   const someArray = [
643
  ///   aaaaaaaaaaaaaaaaaaaaaaaaaa,
644
  ///   aaaaaaaaaaaaaaaaaaaaaaaaaa,
645
  ///   aaaaaaaaaaaaaaaaaaaaaaaaaa,
646
  ///   //                        ^ inserted
647
  ///   ]
648
  /// \endcode
649
  TrailingCommaStyle InsertTrailingCommas;
650
651
  /// If ``false``, a function declaration's or function definition's
652
  /// parameters will either all be on the same line or will have one line each.
653
  /// \code
654
  ///   true:
655
  ///   void f(int aaaaaaaaaaaaaaaaaaaa, int aaaaaaaaaaaaaaaaaaaa,
656
  ///          int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}
657
  ///
658
  ///   false:
659
  ///   void f(int aaaaaaaaaaaaaaaaaaaa,
660
  ///          int aaaaaaaaaaaaaaaaaaaa,
661
  ///          int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}
662
  /// \endcode
663
  bool BinPackParameters;
664
665
  /// The style of wrapping parameters on the same line (bin-packed) or
666
  /// on one line each.
667
  enum BinPackStyle {
668
    /// Automatically determine parameter bin-packing behavior.
669
    BPS_Auto,
670
    /// Always bin-pack parameters.
671
    BPS_Always,
672
    /// Never bin-pack parameters.
673
    BPS_Never,
674
  };
675
676
  /// The style of breaking before or after binary operators.
677
  enum BinaryOperatorStyle {
678
    /// Break after operators.
679
    /// \code
680
    ///    LooooooooooongType loooooooooooooooooooooongVariable =
681
    ///        someLooooooooooooooooongFunction();
682
    ///
683
    ///    bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +
684
    ///                         aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==
685
    ///                     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa &&
686
    ///                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >
687
    ///                     ccccccccccccccccccccccccccccccccccccccccc;
688
    /// \endcode
689
    BOS_None,
690
    /// Break before operators that aren't assignments.
691
    /// \code
692
    ///    LooooooooooongType loooooooooooooooooooooongVariable =
693
    ///        someLooooooooooooooooongFunction();
694
    ///
695
    ///    bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
696
    ///                         + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
697
    ///                     == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
698
    ///                 && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
699
    ///                        > ccccccccccccccccccccccccccccccccccccccccc;
700
    /// \endcode
701
    BOS_NonAssignment,
702
    /// Break before operators.
703
    /// \code
704
    ///    LooooooooooongType loooooooooooooooooooooongVariable
705
    ///        = someLooooooooooooooooongFunction();
706
    ///
707
    ///    bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
708
    ///                         + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
709
    ///                     == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
710
    ///                 && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
711
    ///                        > ccccccccccccccccccccccccccccccccccccccccc;
712
    /// \endcode
713
    BOS_All,
714
  };
715
716
  /// The way to wrap binary operators.
717
  BinaryOperatorStyle BreakBeforeBinaryOperators;
718
719
  /// Different ways to attach braces to their surrounding context.
720
  enum BraceBreakingStyle {
721
    /// Always attach braces to surrounding context.
722
    /// \code
723
    ///   try {
724
    ///     foo();
725
    ///   } catch () {
726
    ///   }
727
    ///   void foo() { bar(); }
728
    ///   class foo {};
729
    ///   if (foo()) {
730
    ///   } else {
731
    ///   }
732
    ///   enum X : int { A, B };
733
    /// \endcode
734
    BS_Attach,
735
    /// Like ``Attach``, but break before braces on function, namespace and
736
    /// class definitions.
737
    /// \code
738
    ///   try {
739
    ///     foo();
740
    ///   } catch () {
741
    ///   }
742
    ///   void foo() { bar(); }
743
    ///   class foo
744
    ///   {
745
    ///   };
746
    ///   if (foo()) {
747
    ///   } else {
748
    ///   }
749
    ///   enum X : int { A, B };
750
    /// \endcode
751
    BS_Linux,
752
    /// Like ``Attach``, but break before braces on enum, function, and record
753
    /// definitions.
754
    /// \code
755
    ///   try {
756
    ///     foo();
757
    ///   } catch () {
758
    ///   }
759
    ///   void foo() { bar(); }
760
    ///   class foo
761
    ///   {
762
    ///   };
763
    ///   if (foo()) {
764
    ///   } else {
765
    ///   }
766
    ///   enum X : int { A, B };
767
    /// \endcode
768
    BS_Mozilla,
769
    /// Like ``Attach``, but break before function definitions, ``catch``, and
770
    /// ``else``.
771
    /// \code
772
    ///   try {
773
    ///     foo();
774
    ///   }
775
    ///   catch () {
776
    ///   }
777
    ///   void foo() { bar(); }
778
    ///   class foo {
779
    ///   };
780
    ///   if (foo()) {
781
    ///   }
782
    ///   else {
783
    ///   }
784
    ///   enum X : int { A, B };
785
    /// \endcode
786
    BS_Stroustrup,
787
    /// Always break before braces.
788
    /// \code
789
    ///   try
790
    ///   {
791
    ///     foo();
792
    ///   }
793
    ///   catch ()
794
    ///   {
795
    ///   }
796
    ///   void foo() { bar(); }
797
    ///   class foo
798
    ///   {
799
    ///   };
800
    ///   if (foo())
801
    ///   {
802
    ///   }
803
    ///   else
804
    ///   {
805
    ///   }
806
    ///   enum X : int
807
    ///   {
808
    ///     A,
809
    ///     B
810
    ///   };
811
    /// \endcode
812
    BS_Allman,
813
    /// Like ``Allman`` but always indent braces and line up code with braces.
814
    /// \code
815
    ///   try
816
    ///     {
817
    ///     foo();
818
    ///     }
819
    ///   catch ()
820
    ///     {
821
    ///     }
822
    ///   void foo() { bar(); }
823
    ///   class foo
824
    ///     {
825
    ///     };
826
    ///   if (foo())
827
    ///     {
828
    ///     }
829
    ///   else
830
    ///     {
831
    ///     }
832
    ///   enum X : int
833
    ///     {
834
    ///     A,
835
    ///     B
836
    ///     };
837
    /// \endcode
838
    BS_Whitesmiths,
839
    /// Always break before braces and add an extra level of indentation to
840
    /// braces of control statements, not to those of class, function
841
    /// or other definitions.
842
    /// \code
843
    ///   try
844
    ///     {
845
    ///       foo();
846
    ///     }
847
    ///   catch ()
848
    ///     {
849
    ///     }
850
    ///   void foo() { bar(); }
851
    ///   class foo
852
    ///   {
853
    ///   };
854
    ///   if (foo())
855
    ///     {
856
    ///     }
857
    ///   else
858
    ///     {
859
    ///     }
860
    ///   enum X : int
861
    ///   {
862
    ///     A,
863
    ///     B
864
    ///   };
865
    /// \endcode
866
    BS_GNU,
867
    /// Like ``Attach``, but break before functions.
868
    /// \code
869
    ///   try {
870
    ///     foo();
871
    ///   } catch () {
872
    ///   }
873
    ///   void foo() { bar(); }
874
    ///   class foo {
875
    ///   };
876
    ///   if (foo()) {
877
    ///   } else {
878
    ///   }
879
    ///   enum X : int { A, B };
880
    /// \endcode
881
    BS_WebKit,
882
    /// Configure each individual brace in `BraceWrapping`.
883
    BS_Custom
884
  };
885
886
  /// The brace breaking style to use.
887
  BraceBreakingStyle BreakBeforeBraces;
888
889
  /// Different ways to wrap braces after control statements.
890
  enum BraceWrappingAfterControlStatementStyle {
891
    /// Never wrap braces after a control statement.
892
    /// \code
893
    ///   if (foo()) {
894
    ///   } else {
895
    ///   }
896
    ///   for (int i = 0; i < 10; ++i) {
897
    ///   }
898
    /// \endcode
899
    BWACS_Never,
900
    /// Only wrap braces after a multi-line control statement.
901
    /// \code
902
    ///   if (foo && bar &&
903
    ///       baz)
904
    ///   {
905
    ///     quux();
906
    ///   }
907
    ///   while (foo || bar) {
908
    ///   }
909
    /// \endcode
910
    BWACS_MultiLine,
911
    /// Always wrap braces after a control statement.
912
    /// \code
913
    ///   if (foo())
914
    ///   {
915
    ///   } else
916
    ///   {}
917
    ///   for (int i = 0; i < 10; ++i)
918
    ///   {}
919
    /// \endcode
920
    BWACS_Always
921
  };
922
923
  /// Precise control over the wrapping of braces.
924
  /// \code
925
  ///   # Should be declared this way:
926
  ///   BreakBeforeBraces: Custom
927
  ///   BraceWrapping:
928
  ///       AfterClass: true
929
  /// \endcode
930
  struct BraceWrappingFlags {
931
    /// Wrap case labels.
932
    /// \code
933
    ///   false:                                true:
934
    ///   switch (foo) {                vs.     switch (foo) {
935
    ///     case 1: {                             case 1:
936
    ///       bar();                              {
937
    ///       break;                                bar();
938
    ///     }                                       break;
939
    ///     default: {                            }
940
    ///       plop();                             default:
941
    ///     }                                     {
942
    ///   }                                         plop();
943
    ///                                           }
944
    ///                                         }
945
    /// \endcode
946
    bool AfterCaseLabel;
947
    /// Wrap class definitions.
948
    /// \code
949
    ///   true:
950
    ///   class foo {};
951
    ///
952
    ///   false:
953
    ///   class foo
954
    ///   {};
955
    /// \endcode
956
    bool AfterClass;
957
958
    /// Wrap control statements (``if``/``for``/``while``/``switch``/..).
959
    BraceWrappingAfterControlStatementStyle AfterControlStatement;
960
    /// Wrap enum definitions.
961
    /// \code
962
    ///   true:
963
    ///   enum X : int
964
    ///   {
965
    ///     B
966
    ///   };
967
    ///
968
    ///   false:
969
    ///   enum X : int { B };
970
    /// \endcode
971
    bool AfterEnum;
972
    /// Wrap function definitions.
973
    /// \code
974
    ///   true:
975
    ///   void foo()
976
    ///   {
977
    ///     bar();
978
    ///     bar2();
979
    ///   }
980
    ///
981
    ///   false:
982
    ///   void foo() {
983
    ///     bar();
984
    ///     bar2();
985
    ///   }
986
    /// \endcode
987
    bool AfterFunction;
988
    /// Wrap namespace definitions.
989
    /// \code
990
    ///   true:
991
    ///   namespace
992
    ///   {
993
    ///   int foo();
994
    ///   int bar();
995
    ///   }
996
    ///
997
    ///   false:
998
    ///   namespace {
999
    ///   int foo();
1000
    ///   int bar();
1001
    ///   }
1002
    /// \endcode
1003
    bool AfterNamespace;
1004
    /// Wrap ObjC definitions (interfaces, implementations...).
1005
    /// \note @autoreleasepool and @synchronized blocks are wrapped
1006
    /// according to `AfterControlStatement` flag.
1007
    bool AfterObjCDeclaration;
1008
    /// Wrap struct definitions.
1009
    /// \code
1010
    ///   true:
1011
    ///   struct foo
1012
    ///   {
1013
    ///     int x;
1014
    ///   };
1015
    ///
1016
    ///   false:
1017
    ///   struct foo {
1018
    ///     int x;
1019
    ///   };
1020
    /// \endcode
1021
    bool AfterStruct;
1022
    /// Wrap union definitions.
1023
    /// \code
1024
    ///   true:
1025
    ///   union foo
1026
    ///   {
1027
    ///     int x;
1028
    ///   }
1029
    ///
1030
    ///   false:
1031
    ///   union foo {
1032
    ///     int x;
1033
    ///   }
1034
    /// \endcode
1035
    bool AfterUnion;
1036
    /// Wrap extern blocks.
1037
    /// \code
1038
    ///   true:
1039
    ///   extern "C"
1040
    ///   {
1041
    ///     int foo();
1042
    ///   }
1043
    ///
1044
    ///   false:
1045
    ///   extern "C" {
1046
    ///   int foo();
1047
    ///   }
1048
    /// \endcode
1049
    bool AfterExternBlock; // Partially superseded by IndentExternBlock
1050
    /// Wrap before ``catch``.
1051
    /// \code
1052
    ///   true:
1053
    ///   try {
1054
    ///     foo();
1055
    ///   }
1056
    ///   catch () {
1057
    ///   }
1058
    ///
1059
    ///   false:
1060
    ///   try {
1061
    ///     foo();
1062
    ///   } catch () {
1063
    ///   }
1064
    /// \endcode
1065
    bool BeforeCatch;
1066
    /// Wrap before ``else``.
1067
    /// \code
1068
    ///   true:
1069
    ///   if (foo()) {
1070
    ///   }
1071
    ///   else {
1072
    ///   }
1073
    ///
1074
    ///   false:
1075
    ///   if (foo()) {
1076
    ///   } else {
1077
    ///   }
1078
    /// \endcode
1079
    bool BeforeElse;
1080
    /// Wrap lambda block.
1081
    /// \code
1082
    ///   true:
1083
    ///   connect(
1084
    ///     []()
1085
    ///     {
1086
    ///       foo();
1087
    ///       bar();
1088
    ///     });
1089
    ///
1090
    ///   false:
1091
    ///   connect([]() {
1092
    ///     foo();
1093
    ///     bar();
1094
    ///   });
1095
    /// \endcode
1096
    bool BeforeLambdaBody;
1097
    /// Wrap before ``while``.
1098
    /// \code
1099
    ///   true:
1100
    ///   do {
1101
    ///     foo();
1102
    ///   }
1103
    ///   while (1);
1104
    ///
1105
    ///   false:
1106
    ///   do {
1107
    ///     foo();
1108
    ///   } while (1);
1109
    /// \endcode
1110
    bool BeforeWhile;
1111
    /// Indent the wrapped braces themselves.
1112
    bool IndentBraces;
1113
    /// If ``false``, empty function body can be put on a single line.
1114
    /// This option is used only if the opening brace of the function has
1115
    /// already been wrapped, i.e. the `AfterFunction` brace wrapping mode is
1116
    /// set, and the function could/should not be put on a single line (as per
1117
    /// `AllowShortFunctionsOnASingleLine` and constructor formatting options).
1118
    /// \code
1119
    ///   int f()   vs.   int f()
1120
    ///   {}              {
1121
    ///                   }
1122
    /// \endcode
1123
    ///
1124
    bool SplitEmptyFunction;
1125
    /// If ``false``, empty record (e.g. class, struct or union) body
1126
    /// can be put on a single line. This option is used only if the opening
1127
    /// brace of the record has already been wrapped, i.e. the `AfterClass`
1128
    /// (for classes) brace wrapping mode is set.
1129
    /// \code
1130
    ///   class Foo   vs.  class Foo
1131
    ///   {}               {
1132
    ///                    }
1133
    /// \endcode
1134
    ///
1135
    bool SplitEmptyRecord;
1136
    /// If ``false``, empty namespace body can be put on a single line.
1137
    /// This option is used only if the opening brace of the namespace has
1138
    /// already been wrapped, i.e. the `AfterNamespace` brace wrapping mode is
1139
    /// set.
1140
    /// \code
1141
    ///   namespace Foo   vs.  namespace Foo
1142
    ///   {}                   {
1143
    ///                        }
1144
    /// \endcode
1145
    ///
1146
    bool SplitEmptyNamespace;
1147
  };
1148
1149
  /// Control of individual brace wrapping cases.
1150
  ///
1151
  /// If ``BreakBeforeBraces`` is set to ``BS_Custom``, use this to specify how
1152
  /// each individual brace case should be handled. Otherwise, this is ignored.
1153
  /// \code{.yaml}
1154
  ///   # Example of usage:
1155
  ///   BreakBeforeBraces: Custom
1156
  ///   BraceWrapping:
1157
  ///     AfterEnum: true
1158
  ///     AfterStruct: false
1159
  ///     SplitEmptyFunction: false
1160
  /// \endcode
1161
  BraceWrappingFlags BraceWrapping;
1162
1163
  /// If ``true``, ternary operators will be placed after line breaks.
1164
  /// \code
1165
  ///    true:
1166
  ///    veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongDescription
1167
  ///        ? firstValue
1168
  ///        : SecondValueVeryVeryVeryVeryLong;
1169
  ///
1170
  ///    false:
1171
  ///    veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongDescription ?
1172
  ///        firstValue :
1173
  ///        SecondValueVeryVeryVeryVeryLong;
1174
  /// \endcode
1175
  bool BreakBeforeTernaryOperators;
1176
1177
  /// Different ways to break initializers.
1178
  enum BreakConstructorInitializersStyle {
1179
    /// Break constructor initializers before the colon and after the commas.
1180
    /// \code
1181
    ///    Constructor()
1182
    ///        : initializer1(),
1183
    ///          initializer2()
1184
    /// \endcode
1185
    BCIS_BeforeColon,
1186
    /// Break constructor initializers before the colon and commas, and align
1187
    /// the commas with the colon.
1188
    /// \code
1189
    ///    Constructor()
1190
    ///        : initializer1()
1191
    ///        , initializer2()
1192
    /// \endcode
1193
    BCIS_BeforeComma,
1194
    /// Break constructor initializers after the colon and commas.
1195
    /// \code
1196
    ///    Constructor() :
1197
    ///        initializer1(),
1198
    ///        initializer2()
1199
    /// \endcode
1200
    BCIS_AfterColon
1201
  };
1202
1203
  /// The constructor initializers style to use.
1204
  BreakConstructorInitializersStyle BreakConstructorInitializers;
1205
1206
  /// Break after each annotation on a field in Java files.
1207
  /// \code{.java}
1208
  ///    true:                                  false:
1209
  ///    @Partial                       vs.     @Partial @Mock DataLoad loader;
1210
  ///    @Mock
1211
  ///    DataLoad loader;
1212
  /// \endcode
1213
  bool BreakAfterJavaFieldAnnotations;
1214
1215
  /// Allow breaking string literals when formatting.
1216
  /// \code
1217
  ///    true:
1218
  ///    const char* x = "veryVeryVeryVeryVeryVe"
1219
  ///                    "ryVeryVeryVeryVeryVery"
1220
  ///                    "VeryLongString";
1221
  ///
1222
  ///    false:
1223
  ///    const char* x =
1224
  ///      "veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongString";
1225
  /// \endcode
1226
  bool BreakStringLiterals;
1227
1228
  /// The column limit.
1229
  ///
1230
  /// A column limit of ``0`` means that there is no column limit. In this case,
1231
  /// clang-format will respect the input's line breaking decisions within
1232
  /// statements unless they contradict other rules.
1233
  unsigned ColumnLimit;
1234
1235
  /// A regular expression that describes comments with special meaning,
1236
  /// which should not be split into lines or otherwise changed.
1237
  /// \code
1238
  ///    // CommentPragmas: '^ FOOBAR pragma:'
1239
  ///    // Will leave the following line unaffected
1240
  ///    #include <vector> // FOOBAR pragma: keep
1241
  /// \endcode
1242
  std::string CommentPragmas;
1243
1244
  /// Different ways to break inheritance list.
1245
  enum BreakInheritanceListStyle {
1246
    /// Break inheritance list before the colon and after the commas.
1247
    /// \code
1248
    ///    class Foo
1249
    ///        : Base1,
1250
    ///          Base2
1251
    ///    {};
1252
    /// \endcode
1253
    BILS_BeforeColon,
1254
    /// Break inheritance list before the colon and commas, and align
1255
    /// the commas with the colon.
1256
    /// \code
1257
    ///    class Foo
1258
    ///        : Base1
1259
    ///        , Base2
1260
    ///    {};
1261
    /// \endcode
1262
    BILS_BeforeComma,
1263
    /// Break inheritance list after the colon and commas.
1264
    /// \code
1265
    ///    class Foo :
1266
    ///        Base1,
1267
    ///        Base2
1268
    ///    {};
1269
    /// \endcode
1270
    BILS_AfterColon
1271
  };
1272
1273
  /// The inheritance list style to use.
1274
  BreakInheritanceListStyle BreakInheritanceList;
1275
1276
  /// If ``true``, consecutive namespace declarations will be on the same
1277
  /// line. If ``false``, each namespace is declared on a new line.
1278
  /// \code
1279
  ///   true:
1280
  ///   namespace Foo { namespace Bar {
1281
  ///   }}
1282
  ///
1283
  ///   false:
1284
  ///   namespace Foo {
1285
  ///   namespace Bar {
1286
  ///   }
1287
  ///   }
1288
  /// \endcode
1289
  ///
1290
  /// If it does not fit on a single line, the overflowing namespaces get
1291
  /// wrapped:
1292
  /// \code
1293
  ///   namespace Foo { namespace Bar {
1294
  ///   namespace Extra {
1295
  ///   }}}
1296
  /// \endcode
1297
  bool CompactNamespaces;
1298
1299
  // clang-format off
1300
  /// If the constructor initializers don't fit on a line, put each
1301
  /// initializer on its own line.
1302
  /// \code
1303
  ///   true:
1304
  ///   SomeClass::Constructor()
1305
  ///       : aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa) {
1306
  ///     return 0;
1307
  ///   }
1308
  ///
1309
  ///   false:
1310
  ///   SomeClass::Constructor()
1311
  ///       : aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaa),
1312
  ///         aaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa) {
1313
  ///     return 0;
1314
  ///   }
1315
  /// \endcode
1316
  bool ConstructorInitializerAllOnOneLineOrOnePerLine;
1317
  // clang-format on
1318
1319
  /// The number of characters to use for indentation of constructor
1320
  /// initializer lists as well as inheritance lists.
1321
  unsigned ConstructorInitializerIndentWidth;
1322
1323
  /// Indent width for line continuations.
1324
  /// \code
1325
  ///    ContinuationIndentWidth: 2
1326
  ///
1327
  ///    int i =         //  VeryVeryVeryVeryVeryLongComment
1328
  ///      longFunction( // Again a long comment
1329
  ///        arg);
1330
  /// \endcode
1331
  unsigned ContinuationIndentWidth;
1332
1333
  /// If ``true``, format braced lists as best suited for C++11 braced
1334
  /// lists.
1335
  ///
1336
  /// Important differences:
1337
  /// - No spaces inside the braced list.
1338
  /// - No line break before the closing brace.
1339
  /// - Indentation with the continuation indent, not with the block indent.
1340
  ///
1341
  /// Fundamentally, C++11 braced lists are formatted exactly like function
1342
  /// calls would be formatted in their place. If the braced list follows a name
1343
  /// (e.g. a type or variable name), clang-format formats as if the ``{}`` were
1344
  /// the parentheses of a function call with that name. If there is no name,
1345
  /// a zero-length name is assumed.
1346
  /// \code
1347
  ///    true:                                  false:
1348
  ///    vector<int> x{1, 2, 3, 4};     vs.     vector<int> x{ 1, 2, 3, 4 };
1349
  ///    vector<T> x{{}, {}, {}, {}};           vector<T> x{ {}, {}, {}, {} };
1350
  ///    f(MyMap[{composite, key}]);            f(MyMap[{ composite, key }]);
1351
  ///    new int[3]{1, 2, 3};                   new int[3]{ 1, 2, 3 };
1352
  /// \endcode
1353
  bool Cpp11BracedListStyle;
1354
1355
  /// \brief Analyze the formatted file for the most used line ending (``\r\n``
1356
  /// or ``\n``). ``UseCRLF`` is only used as a fallback if none can be derived.
1357
  bool DeriveLineEnding;
1358
1359
  /// If ``true``, analyze the formatted file for the most common
1360
  /// alignment of ``&`` and ``*``.
1361
  /// Pointer and reference alignment styles are going to be updated according
1362
  /// to the preferences found in the file.
1363
  /// ``PointerAlignment`` is then used only as fallback.
1364
  bool DerivePointerAlignment;
1365
1366
  /// Disables formatting completely.
1367
  bool DisableFormat;
1368
1369
  /// If ``true``, clang-format detects whether function calls and
1370
  /// definitions are formatted with one parameter per line.
1371
  ///
1372
  /// Each call can be bin-packed, one-per-line or inconclusive. If it is
1373
  /// inconclusive, e.g. completely on one line, but a decision needs to be
1374
  /// made, clang-format analyzes whether there are other bin-packed cases in
1375
  /// the input file and act accordingly.
1376
  ///
1377
  /// NOTE: This is an experimental flag, that might go away or be renamed. Do
1378
  /// not use this in config files, etc. Use at your own risk.
1379
  bool ExperimentalAutoDetectBinPacking;
1380
1381
  /// If ``true``, clang-format adds missing namespace end comments and
1382
  /// fixes invalid existing ones.
1383
  /// \code
1384
  ///    true:                                  false:
1385
  ///    namespace a {                  vs.     namespace a {
1386
  ///    foo();                                 foo();
1387
  ///    } // namespace a                       }
1388
  /// \endcode
1389
  bool FixNamespaceComments;
1390
1391
  /// A vector of macros that should be interpreted as foreach loops
1392
  /// instead of as function calls.
1393
  ///
1394
  /// These are expected to be macros of the form:
1395
  /// \code
1396
  ///   FOREACH(<variable-declaration>, ...)
1397
  ///     <loop-body>
1398
  /// \endcode
1399
  ///
1400
  /// In the .clang-format configuration file, this can be configured like:
1401
  /// \code{.yaml}
1402
  ///   ForEachMacros: ['RANGES_FOR', 'FOREACH']
1403
  /// \endcode
1404
  ///
1405
  /// For example: BOOST_FOREACH.
1406
  std::vector<std::string> ForEachMacros;
1407
1408
  /// \brief A vector of macros that should be interpreted as type declarations
1409
  /// instead of as function calls.
1410
  ///
1411
  /// These are expected to be macros of the form:
1412
  /// \code
1413
  ///   STACK_OF(...)
1414
  /// \endcode
1415
  ///
1416
  /// In the .clang-format configuration file, this can be configured like:
1417
  /// \code{.yaml}
1418
  ///   TypenameMacros: ['STACK_OF', 'LIST']
1419
  /// \endcode
1420
  ///
1421
  /// For example: OpenSSL STACK_OF, BSD LIST_ENTRY.
1422
  std::vector<std::string> TypenameMacros;
1423
1424
  /// A vector of macros that should be interpreted as complete
1425
  /// statements.
1426
  ///
1427
  /// Typical macros are expressions, and require a semi-colon to be
1428
  /// added; sometimes this is not the case, and this allows to make
1429
  /// clang-format aware of such cases.
1430
  ///
1431
  /// For example: Q_UNUSED
1432
  std::vector<std::string> StatementMacros;
1433
1434
  /// A vector of macros which are used to open namespace blocks.
1435
  ///
1436
  /// These are expected to be macros of the form:
1437
  /// \code
1438
  ///   NAMESPACE(<namespace-name>, ...) {
1439
  ///     <namespace-content>
1440
  ///   }
1441
  /// \endcode
1442
  ///
1443
  /// For example: TESTSUITE
1444
  std::vector<std::string> NamespaceMacros;
1445
1446
  /// A vector of macros which are whitespace-sensitive and should not
1447
  /// be touched.
1448
  ///
1449
  /// These are expected to be macros of the form:
1450
  /// \code
1451
  ///   STRINGIZE(...)
1452
  /// \endcode
1453
  ///
1454
  /// In the .clang-format configuration file, this can be configured like:
1455
  /// \code{.yaml}
1456
  ///   WhitespaceSensitiveMacros: ['STRINGIZE', 'PP_STRINGIZE']
1457
  /// \endcode
1458
  ///
1459
  /// For example: BOOST_PP_STRINGIZE
1460
  std::vector<std::string> WhitespaceSensitiveMacros;
1461
1462
  tooling::IncludeStyle IncludeStyle;
1463
1464
  /// Indent case labels one level from the switch statement.
1465
  ///
1466
  /// When ``false``, use the same indentation level as for the switch
1467
  /// statement. Switch statement body is always indented one level more than
1468
  /// case labels (except the first block following the case label, which
1469
  /// itself indents the code - unless IndentCaseBlocks is enabled).
1470
  /// \code
1471
  ///    false:                                 true:
1472
  ///    switch (fool) {                vs.     switch (fool) {
1473
  ///    case 1:                                  case 1:
1474
  ///      bar();                                   bar();
1475
  ///      break;                                   break;
1476
  ///    default:                                 default:
1477
  ///      plop();                                  plop();
1478
  ///    }                                      }
1479
  /// \endcode
1480
  bool IndentCaseLabels;
1481
1482
  /// Indent case label blocks one level from the case label.
1483
  ///
1484
  /// When ``false``, the block following the case label uses the same
1485
  /// indentation level as for the case label, treating the case label the same
1486
  /// as an if-statement.
1487
  /// When ``true``, the block gets indented as a scope block.
1488
  /// \code
1489
  ///    false:                                 true:
1490
  ///    switch (fool) {                vs.     switch (fool) {
1491
  ///    case 1: {                              case 1:
1492
  ///      bar();                                 {
1493
  ///    } break;                                   bar();
1494
  ///    default: {                               }
1495
  ///      plop();                                break;
1496
  ///    }                                      default:
1497
  ///    }                                        {
1498
  ///                                               plop();
1499
  ///                                             }
1500
  ///                                           }
1501
  /// \endcode
1502
  bool IndentCaseBlocks;
1503
1504
  /// Indent goto labels.
1505
  ///
1506
  /// When ``false``, goto labels are flushed left.
1507
  /// \code
1508
  ///    true:                                  false:
1509
  ///    int f() {                      vs.     int f() {
1510
  ///      if (foo()) {                           if (foo()) {
1511
  ///      label1:                              label1:
1512
  ///        bar();                                 bar();
1513
  ///      }                                      }
1514
  ///    label2:                                label2:
1515
  ///      return 1;                              return 1;
1516
  ///    }                                      }
1517
  /// \endcode
1518
  bool IndentGotoLabels;
1519
1520
  /// Options for indenting preprocessor directives.
1521
  enum PPDirectiveIndentStyle {
1522
    /// Does not indent any directives.
1523
    /// \code
1524
    ///    #if FOO
1525
    ///    #if BAR
1526
    ///    #include <foo>
1527
    ///    #endif
1528
    ///    #endif
1529
    /// \endcode
1530
    PPDIS_None,
1531
    /// Indents directives after the hash.
1532
    /// \code
1533
    ///    #if FOO
1534
    ///    #  if BAR
1535
    ///    #    include <foo>
1536
    ///    #  endif
1537
    ///    #endif
1538
    /// \endcode
1539
    PPDIS_AfterHash,
1540
    /// Indents directives before the hash.
1541
    /// \code
1542
    ///    #if FOO
1543
    ///      #if BAR
1544
    ///        #include <foo>
1545
    ///      #endif
1546
    ///    #endif
1547
    /// \endcode
1548
    PPDIS_BeforeHash
1549
  };
1550
1551
  /// The preprocessor directive indenting style to use.
1552
  PPDirectiveIndentStyle IndentPPDirectives;
1553
1554
  /// Indents extern blocks
1555
  enum IndentExternBlockStyle {
1556
    /// Backwards compatible with AfterExternBlock's indenting.
1557
    /// \code
1558
    ///    IndentExternBlock: AfterExternBlock
1559
    ///    BraceWrapping.AfterExternBlock: true
1560
    ///    extern "C"
1561
    ///    {
1562
    ///        void foo();
1563
    ///    }
1564
    /// \endcode
1565
    ///
1566
    /// \code
1567
    ///    IndentExternBlock: AfterExternBlock
1568
    ///    BraceWrapping.AfterExternBlock: false
1569
    ///    extern "C" {
1570
    ///    void foo();
1571
    ///    }
1572
    /// \endcode
1573
    IEBS_AfterExternBlock,
1574
    /// Does not indent extern blocks.
1575
    /// \code
1576
    ///     extern "C" {
1577
    ///     void foo();
1578
    ///     }
1579
    /// \endcode
1580
    IEBS_NoIndent,
1581
    /// Indents extern blocks.
1582
    /// \code
1583
    ///     extern "C" {
1584
    ///       void foo();
1585
    ///     }
1586
    /// \endcode
1587
    IEBS_Indent,
1588
  };
1589
1590
  /// IndentExternBlockStyle is the type of indenting of extern blocks.
1591
  IndentExternBlockStyle IndentExternBlock;
1592
1593
  /// The number of columns to use for indentation.
1594
  /// \code
1595
  ///    IndentWidth: 3
1596
  ///
1597
  ///    void f() {
1598
  ///       someFunction();
1599
  ///       if (true, false) {
1600
  ///          f();
1601
  ///       }
1602
  ///    }
1603
  /// \endcode
1604
  unsigned IndentWidth;
1605
1606
  /// Indent if a function definition or declaration is wrapped after the
1607
  /// type.
1608
  /// \code
1609
  ///    true:
1610
  ///    LoooooooooooooooooooooooooooooooooooooooongReturnType
1611
  ///        LoooooooooooooooooooooooooooooooongFunctionDeclaration();
1612
  ///
1613
  ///    false:
1614
  ///    LoooooooooooooooooooooooooooooooooooooooongReturnType
1615
  ///    LoooooooooooooooooooooooooooooooongFunctionDeclaration();
1616
  /// \endcode
1617
  bool IndentWrappedFunctionNames;
1618
1619
  /// A vector of prefixes ordered by the desired groups for Java imports.
1620
  ///
1621
  /// One group's prefix can be a subset of another - the longest prefix is
1622
  /// always matched. Within a group, the imports are ordered lexicographically.
1623
  /// Static imports are grouped separately and follow the same group rules.
1624
  /// By default, static imports are placed before non-static imports,
1625
  /// but this behavior is changed by another option,
1626
  /// ``SortJavaStaticImport``.
1627
  ///
1628
  /// In the .clang-format configuration file, this can be configured like
1629
  /// in the following yaml example. This will result in imports being
1630
  /// formatted as in the Java example below.
1631
  /// \code{.yaml}
1632
  ///   JavaImportGroups: ['com.example', 'com', 'org']
1633
  /// \endcode
1634
  ///
1635
  /// \code{.java}
1636
  ///    import static com.example.function1;
1637
  ///
1638
  ///    import static com.test.function2;
1639
  ///
1640
  ///    import static org.example.function3;
1641
  ///
1642
  ///    import com.example.ClassA;
1643
  ///    import com.example.Test;
1644
  ///    import com.example.a.ClassB;
1645
  ///
1646
  ///    import com.test.ClassC;
1647
  ///
1648
  ///    import org.example.ClassD;
1649
  /// \endcode
1650
  std::vector<std::string> JavaImportGroups;
1651
1652
  /// Quotation styles for JavaScript strings. Does not affect template
1653
  /// strings.
1654
  enum JavaScriptQuoteStyle {
1655
    /// Leave string quotes as they are.
1656
    /// \code{.js}
1657
    ///    string1 = "foo";
1658
    ///    string2 = 'bar';
1659
    /// \endcode
1660
    JSQS_Leave,
1661
    /// Always use single quotes.
1662
    /// \code{.js}
1663
    ///    string1 = 'foo';
1664
    ///    string2 = 'bar';
1665
    /// \endcode
1666
    JSQS_Single,
1667
    /// Always use double quotes.
1668
    /// \code{.js}
1669
    ///    string1 = "foo";
1670
    ///    string2 = "bar";
1671
    /// \endcode
1672
    JSQS_Double
1673
  };
1674
1675
  /// The JavaScriptQuoteStyle to use for JavaScript strings.
1676
  JavaScriptQuoteStyle JavaScriptQuotes;
1677
1678
  // clang-format off
1679
  /// Whether to wrap JavaScript import/export statements.
1680
  /// \code{.js}
1681
  ///    true:
1682
  ///    import {
1683
  ///        VeryLongImportsAreAnnoying,
1684
  ///        VeryLongImportsAreAnnoying,
1685
  ///        VeryLongImportsAreAnnoying,
1686
  ///    } from 'some/module.js'
1687
  ///
1688
  ///    false:
1689
  ///    import {VeryLongImportsAreAnnoying, VeryLongImportsAreAnnoying, VeryLongImportsAreAnnoying,} from "some/module.js"
1690
  /// \endcode
1691
  bool JavaScriptWrapImports;
1692
  // clang-format on
1693
1694
  /// If true, the empty line at the start of blocks is kept.
1695
  /// \code
1696
  ///    true:                                  false:
1697
  ///    if (foo) {                     vs.     if (foo) {
1698
  ///                                             bar();
1699
  ///      bar();                               }
1700
  ///    }
1701
  /// \endcode
1702
  bool KeepEmptyLinesAtTheStartOfBlocks;
1703
1704
  /// Supported languages.
1705
  ///
1706
  /// When stored in a configuration file, specifies the language, that the
1707
  /// configuration targets. When passed to the ``reformat()`` function, enables
1708
  /// syntax features specific to the language.
1709
  enum LanguageKind {
1710
    /// Do not use.
1711
    LK_None,
1712
    /// Should be used for C, C++.
1713
    LK_Cpp,
1714
    /// Should be used for C#.
1715
    LK_CSharp,
1716
    /// Should be used for Java.
1717
    LK_Java,
1718
    /// Should be used for JavaScript.
1719
    LK_JavaScript,
1720
    /// Should be used for Objective-C, Objective-C++.
1721
    LK_ObjC,
1722
    /// Should be used for Protocol Buffers
1723
    /// (https://developers.google.com/protocol-buffers/).
1724
    LK_Proto,
1725
    /// Should be used for TableGen code.
1726
    LK_TableGen,
1727
    /// Should be used for Protocol Buffer messages in text format
1728
    /// (https://developers.google.com/protocol-buffers/).
1729
    LK_TextProto
1730
  };
1731
1.93M
  bool isCpp() const { return Language == LK_Cpp || 
Language == LK_ObjC461k
; }
1732
2.68M
  bool isCSharp() const { return Language == LK_CSharp; }
1733
1734
  /// Language, this format style is targeted at.
1735
  LanguageKind Language;
1736
1737
  /// A regular expression matching macros that start a block.
1738
  /// \code
1739
  ///    # With:
1740
  ///    MacroBlockBegin: "^NS_MAP_BEGIN|\
1741
  ///    NS_TABLE_HEAD$"
1742
  ///    MacroBlockEnd: "^\
1743
  ///    NS_MAP_END|\
1744
  ///    NS_TABLE_.*_END$"
1745
  ///
1746
  ///    NS_MAP_BEGIN
1747
  ///      foo();
1748
  ///    NS_MAP_END
1749
  ///
1750
  ///    NS_TABLE_HEAD
1751
  ///      bar();
1752
  ///    NS_TABLE_FOO_END
1753
  ///
1754
  ///    # Without:
1755
  ///    NS_MAP_BEGIN
1756
  ///    foo();
1757
  ///    NS_MAP_END
1758
  ///
1759
  ///    NS_TABLE_HEAD
1760
  ///    bar();
1761
  ///    NS_TABLE_FOO_END
1762
  /// \endcode
1763
  std::string MacroBlockBegin;
1764
1765
  /// A regular expression matching macros that end a block.
1766
  std::string MacroBlockEnd;
1767
1768
  /// The maximum number of consecutive empty lines to keep.
1769
  /// \code
1770
  ///    MaxEmptyLinesToKeep: 1         vs.     MaxEmptyLinesToKeep: 0
1771
  ///    int f() {                              int f() {
1772
  ///      int = 1;                                 int i = 1;
1773
  ///                                               i = foo();
1774
  ///      i = foo();                               return i;
1775
  ///                                           }
1776
  ///      return i;
1777
  ///    }
1778
  /// \endcode
1779
  unsigned MaxEmptyLinesToKeep;
1780
1781
  /// Different ways to indent namespace contents.
1782
  enum NamespaceIndentationKind {
1783
    /// Don't indent in namespaces.
1784
    /// \code
1785
    ///    namespace out {
1786
    ///    int i;
1787
    ///    namespace in {
1788
    ///    int i;
1789
    ///    }
1790
    ///    }
1791
    /// \endcode
1792
    NI_None,
1793
    /// Indent only in inner namespaces (nested in other namespaces).
1794
    /// \code
1795
    ///    namespace out {
1796
    ///    int i;
1797
    ///    namespace in {
1798
    ///      int i;
1799
    ///    }
1800
    ///    }
1801
    /// \endcode
1802
    NI_Inner,
1803
    /// Indent in all namespaces.
1804
    /// \code
1805
    ///    namespace out {
1806
    ///      int i;
1807
    ///      namespace in {
1808
    ///        int i;
1809
    ///      }
1810
    ///    }
1811
    /// \endcode
1812
    NI_All
1813
  };
1814
1815
  /// The indentation used for namespaces.
1816
  NamespaceIndentationKind NamespaceIndentation;
1817
1818
  /// Controls bin-packing Objective-C protocol conformance list
1819
  /// items into as few lines as possible when they go over ``ColumnLimit``.
1820
  ///
1821
  /// If ``Auto`` (the default), delegates to the value in
1822
  /// ``BinPackParameters``. If that is ``true``, bin-packs Objective-C
1823
  /// protocol conformance list items into as few lines as possible
1824
  /// whenever they go over ``ColumnLimit``.
1825
  ///
1826
  /// If ``Always``, always bin-packs Objective-C protocol conformance
1827
  /// list items into as few lines as possible whenever they go over
1828
  /// ``ColumnLimit``.
1829
  ///
1830
  /// If ``Never``, lays out Objective-C protocol conformance list items
1831
  /// onto individual lines whenever they go over ``ColumnLimit``.
1832
  ///
1833
  /// \code{.objc}
1834
  ///    Always (or Auto, if BinPackParameters=true):
1835
  ///    @interface ccccccccccccc () <
1836
  ///        ccccccccccccc, ccccccccccccc,
1837
  ///        ccccccccccccc, ccccccccccccc> {
1838
  ///    }
1839
  ///
1840
  ///    Never (or Auto, if BinPackParameters=false):
1841
  ///    @interface ddddddddddddd () <
1842
  ///        ddddddddddddd,
1843
  ///        ddddddddddddd,
1844
  ///        ddddddddddddd,
1845
  ///        ddddddddddddd> {
1846
  ///    }
1847
  /// \endcode
1848
  BinPackStyle ObjCBinPackProtocolList;
1849
1850
  /// The number of characters to use for indentation of ObjC blocks.
1851
  /// \code{.objc}
1852
  ///    ObjCBlockIndentWidth: 4
1853
  ///
1854
  ///    [operation setCompletionBlock:^{
1855
  ///        [self onOperationDone];
1856
  ///    }];
1857
  /// \endcode
1858
  unsigned ObjCBlockIndentWidth;
1859
1860
  /// Add a space after ``@property`` in Objective-C, i.e. use
1861
  /// ``@property (readonly)`` instead of ``@property(readonly)``.
1862
  bool ObjCSpaceAfterProperty;
1863
1864
  /// Break parameters list into lines when there is nested block
1865
  /// parameters in a function call.
1866
  /// \code
1867
  ///   false:
1868
  ///    - (void)_aMethod
1869
  ///    {
1870
  ///        [self.test1 t:self w:self callback:^(typeof(self) self, NSNumber
1871
  ///        *u, NSNumber *v) {
1872
  ///            u = c;
1873
  ///        }]
1874
  ///    }
1875
  ///    true:
1876
  ///    - (void)_aMethod
1877
  ///    {
1878
  ///       [self.test1 t:self
1879
  ///                    w:self
1880
  ///           callback:^(typeof(self) self, NSNumber *u, NSNumber *v) {
1881
  ///                u = c;
1882
  ///            }]
1883
  ///    }
1884
  /// \endcode
1885
  bool ObjCBreakBeforeNestedBlockParam;
1886
1887
  /// Add a space in front of an Objective-C protocol list, i.e. use
1888
  /// ``Foo <Protocol>`` instead of ``Foo<Protocol>``.
1889
  bool ObjCSpaceBeforeProtocolList;
1890
1891
  /// The penalty for breaking around an assignment operator.
1892
  unsigned PenaltyBreakAssignment;
1893
1894
  /// The penalty for breaking a function call after ``call(``.
1895
  unsigned PenaltyBreakBeforeFirstCallParameter;
1896
1897
  /// The penalty for each line break introduced inside a comment.
1898
  unsigned PenaltyBreakComment;
1899
1900
  /// The penalty for breaking before the first ``<<``.
1901
  unsigned PenaltyBreakFirstLessLess;
1902
1903
  /// The penalty for each line break introduced inside a string literal.
1904
  unsigned PenaltyBreakString;
1905
1906
  /// The penalty for breaking after template declaration.
1907
  unsigned PenaltyBreakTemplateDeclaration;
1908
1909
  /// The penalty for each character outside of the column limit.
1910
  unsigned PenaltyExcessCharacter;
1911
1912
  /// Penalty for putting the return type of a function onto its own
1913
  /// line.
1914
  unsigned PenaltyReturnTypeOnItsOwnLine;
1915
1916
  /// The ``&`` and ``*`` alignment style.
1917
  enum PointerAlignmentStyle {
1918
    /// Align pointer to the left.
1919
    /// \code
1920
    ///   int* a;
1921
    /// \endcode
1922
    PAS_Left,
1923
    /// Align pointer to the right.
1924
    /// \code
1925
    ///   int *a;
1926
    /// \endcode
1927
    PAS_Right,
1928
    /// Align pointer in the middle.
1929
    /// \code
1930
    ///   int * a;
1931
    /// \endcode
1932
    PAS_Middle
1933
  };
1934
1935
  /// Pointer and reference alignment style.
1936
  PointerAlignmentStyle PointerAlignment;
1937
1938
  /// See documentation of ``RawStringFormats``.
1939
  struct RawStringFormat {
1940
    /// The language of this raw string.
1941
    LanguageKind Language;
1942
    /// A list of raw string delimiters that match this language.
1943
    std::vector<std::string> Delimiters;
1944
    /// A list of enclosing function names that match this language.
1945
    std::vector<std::string> EnclosingFunctions;
1946
    /// The canonical delimiter for this language.
1947
    std::string CanonicalDelimiter;
1948
    /// The style name on which this raw string format is based on.
1949
    /// If not specified, the raw string format is based on the style that this
1950
    /// format is based on.
1951
    std::string BasedOnStyle;
1952
28
    bool operator==(const RawStringFormat &Other) const {
1953
28
      return Language == Other.Language && Delimiters == Other.Delimiters &&
1954
28
             EnclosingFunctions == Other.EnclosingFunctions &&
1955
28
             CanonicalDelimiter == Other.CanonicalDelimiter &&
1956
28
             BasedOnStyle == Other.BasedOnStyle;
1957
28
    }
1958
  };
1959
1960
  /// Defines hints for detecting supported languages code blocks in raw
1961
  /// strings.
1962
  ///
1963
  /// A raw string with a matching delimiter or a matching enclosing function
1964
  /// name will be reformatted assuming the specified language based on the
1965
  /// style for that language defined in the .clang-format file. If no style has
1966
  /// been defined in the .clang-format file for the specific language, a
1967
  /// predefined style given by 'BasedOnStyle' is used. If 'BasedOnStyle' is not
1968
  /// found, the formatting is based on llvm style. A matching delimiter takes
1969
  /// precedence over a matching enclosing function name for determining the
1970
  /// language of the raw string contents.
1971
  ///
1972
  /// If a canonical delimiter is specified, occurrences of other delimiters for
1973
  /// the same language will be updated to the canonical if possible.
1974
  ///
1975
  /// There should be at most one specification per language and each delimiter
1976
  /// and enclosing function should not occur in multiple specifications.
1977
  ///
1978
  /// To configure this in the .clang-format file, use:
1979
  /// \code{.yaml}
1980
  ///   RawStringFormats:
1981
  ///     - Language: TextProto
1982
  ///         Delimiters:
1983
  ///           - 'pb'
1984
  ///           - 'proto'
1985
  ///         EnclosingFunctions:
1986
  ///           - 'PARSE_TEXT_PROTO'
1987
  ///         BasedOnStyle: google
1988
  ///     - Language: Cpp
1989
  ///         Delimiters:
1990
  ///           - 'cc'
1991
  ///           - 'cpp'
1992
  ///         BasedOnStyle: llvm
1993
  ///         CanonicalDelimiter: 'cc'
1994
  /// \endcode
1995
  std::vector<RawStringFormat> RawStringFormats;
1996
1997
  // clang-format off
1998
  /// If ``true``, clang-format will attempt to re-flow comments.
1999
  /// \code
2000
  ///    false:
2001
  ///    // veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongComment with plenty of information
2002
  ///    /* second veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongComment with plenty of information */
2003
  ///
2004
  ///    true:
2005
  ///    // veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongComment with plenty of
2006
  ///    // information
2007
  ///    /* second veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongComment with plenty of
2008
  ///     * information */
2009
  /// \endcode
2010
  bool ReflowComments;
2011
  // clang-format on
2012
2013
  /// If ``true``, clang-format will sort ``#includes``.
2014
  /// \code
2015
  ///    false:                                 true:
2016
  ///    #include "b.h"                 vs.     #include "a.h"
2017
  ///    #include "a.h"                         #include "b.h"
2018
  /// \endcode
2019
  bool SortIncludes;
2020
2021
  /// Position for Java Static imports.
2022
  enum SortJavaStaticImportOptions {
2023
    /// Static imports are placed before non-static imports.
2024
    /// \code{.java}
2025
    ///   import static org.example.function1;
2026
    ///
2027
    ///   import org.example.ClassA;
2028
    /// \endcode
2029
    SJSIO_Before,
2030
    /// Static imports are placed after non-static imports.
2031
    /// \code{.java}
2032
    ///   import org.example.ClassA;
2033
    ///
2034
    ///   import static org.example.function1;
2035
    /// \endcode
2036
    SJSIO_After,
2037
  };
2038
2039
  /// When sorting Java imports, by default static imports are placed before
2040
  /// non-static imports. If ``JavaStaticImportAfterImport`` is ``After``,
2041
  /// static imports are placed after non-static imports.
2042
  SortJavaStaticImportOptions SortJavaStaticImport;
2043
2044
  /// If ``true``, clang-format will sort using declarations.
2045
  ///
2046
  /// The order of using declarations is defined as follows:
2047
  /// Split the strings by "::" and discard any initial empty strings. The last
2048
  /// element of each list is a non-namespace name; all others are namespace
2049
  /// names. Sort the lists of names lexicographically, where the sort order of
2050
  /// individual names is that all non-namespace names come before all namespace
2051
  /// names, and within those groups, names are in case-insensitive
2052
  /// lexicographic order.
2053
  /// \code
2054
  ///    false:                                 true:
2055
  ///    using std::cout;               vs.     using std::cin;
2056
  ///    using std::cin;                        using std::cout;
2057
  /// \endcode
2058
  bool SortUsingDeclarations;
2059
2060
  /// If ``true``, a space is inserted after C style casts.
2061
  /// \code
2062
  ///    true:                                  false:
2063
  ///    (int) i;                       vs.     (int)i;
2064
  /// \endcode
2065
  bool SpaceAfterCStyleCast;
2066
2067
  /// If ``true``, a space is inserted after the logical not operator (``!``).
2068
  /// \code
2069
  ///    true:                                  false:
2070
  ///    ! someExpression();            vs.     !someExpression();
2071
  /// \endcode
2072
  bool SpaceAfterLogicalNot;
2073
2074
  /// If \c true, a space will be inserted after the 'template' keyword.
2075
  /// \code
2076
  ///    true:                                  false:
2077
  ///    template <int> void foo();     vs.     template<int> void foo();
2078
  /// \endcode
2079
  bool SpaceAfterTemplateKeyword;
2080
2081
  /// If ``false``, spaces will be removed before assignment operators.
2082
  /// \code
2083
  ///    true:                                  false:
2084
  ///    int a = 5;                     vs.     int a= 5;
2085
  ///    a += 42;                               a+= 42;
2086
  /// \endcode
2087
  bool SpaceBeforeAssignmentOperators;
2088
2089
  /// If ``true``, a space will be inserted before a C++11 braced list
2090
  /// used to initialize an object (after the preceding identifier or type).
2091
  /// \code
2092
  ///    true:                                  false:
2093
  ///    Foo foo { bar };               vs.     Foo foo{ bar };
2094
  ///    Foo {};                                Foo{};
2095
  ///    vector<int> { 1, 2, 3 };               vector<int>{ 1, 2, 3 };
2096
  ///    new int[3] { 1, 2, 3 };                new int[3]{ 1, 2, 3 };
2097
  /// \endcode
2098
  bool SpaceBeforeCpp11BracedList;
2099
2100
  /// If ``false``, spaces will be removed before constructor initializer
2101
  /// colon.
2102
  /// \code
2103
  ///    true:                                  false:
2104
  ///    Foo::Foo() : a(a) {}                   Foo::Foo(): a(a) {}
2105
  /// \endcode
2106
  bool SpaceBeforeCtorInitializerColon;
2107
2108
  /// If ``false``, spaces will be removed before inheritance colon.
2109
  /// \code
2110
  ///    true:                                  false:
2111
  ///    class Foo : Bar {}             vs.     class Foo: Bar {}
2112
  /// \endcode
2113
  bool SpaceBeforeInheritanceColon;
2114
2115
  /// Different ways to put a space before opening parentheses.
2116
  enum SpaceBeforeParensOptions {
2117
    /// Never put a space before opening parentheses.
2118
    /// \code
2119
    ///    void f() {
2120
    ///      if(true) {
2121
    ///        f();
2122
    ///      }
2123
    ///    }
2124
    /// \endcode
2125
    SBPO_Never,
2126
    /// Put a space before opening parentheses only after control statement
2127
    /// keywords (``for/if/while...``).
2128
    /// \code
2129
    ///    void f() {
2130
    ///      if (true) {
2131
    ///        f();
2132
    ///      }
2133
    ///    }
2134
    /// \endcode
2135
    SBPO_ControlStatements,
2136
    /// Same as ``SBPO_ControlStatements`` except this option doesn't apply to
2137
    /// ForEach macros. This is useful in projects where ForEach macros are
2138
    /// treated as function calls instead of control statements.
2139
    /// \code
2140
    ///    void f() {
2141
    ///      Q_FOREACH(...) {
2142
    ///        f();
2143
    ///      }
2144
    ///    }
2145
    /// \endcode
2146
    SBPO_ControlStatementsExceptForEachMacros,
2147
    /// Put a space before opening parentheses only if the parentheses are not
2148
    /// empty i.e. '()'
2149
    /// \code
2150
    ///   void() {
2151
    ///     if (true) {
2152
    ///       f();
2153
    ///       g (x, y, z);
2154
    ///     }
2155
    ///   }
2156
    /// \endcode
2157
    SBPO_NonEmptyParentheses,
2158
    /// Always put a space before opening parentheses, except when it's
2159
    /// prohibited by the syntax rules (in function-like macro definitions) or
2160
    /// when determined by other style rules (after unary operators, opening
2161
    /// parentheses, etc.)
2162
    /// \code
2163
    ///    void f () {
2164
    ///      if (true) {
2165
    ///        f ();
2166
    ///      }
2167
    ///    }
2168
    /// \endcode
2169
    SBPO_Always
2170
  };
2171
2172
  /// Defines in which cases to put a space before opening parentheses.
2173
  SpaceBeforeParensOptions SpaceBeforeParens;
2174
2175
  /// If ``false``, spaces will be removed before range-based for loop
2176
  /// colon.
2177
  /// \code
2178
  ///    true:                                  false:
2179
  ///    for (auto v : values) {}       vs.     for(auto v: values) {}
2180
  /// \endcode
2181
  bool SpaceBeforeRangeBasedForLoopColon;
2182
2183
  /// If ``true``, spaces will be inserted into ``{}``.
2184
  /// \code
2185
  ///    true:                                false:
2186
  ///    void f() { }                   vs.   void f() {}
2187
  ///    while (true) { }                     while (true) {}
2188
  /// \endcode
2189
  bool SpaceInEmptyBlock;
2190
2191
  /// If ``true``, spaces may be inserted into ``()``.
2192
  /// \code
2193
  ///    true:                                false:
2194
  ///    void f( ) {                    vs.   void f() {
2195
  ///      int x[] = {foo( ), bar( )};          int x[] = {foo(), bar()};
2196
  ///      if (true) {                          if (true) {
2197
  ///        f( );                                f();
2198
  ///      }                                    }
2199
  ///    }                                    }
2200
  /// \endcode
2201
  bool SpaceInEmptyParentheses;
2202
2203
  /// The number of spaces before trailing line comments
2204
  /// (``//`` - comments).
2205
  ///
2206
  /// This does not affect trailing block comments (``/*`` - comments) as
2207
  /// those commonly have different usage patterns and a number of special
2208
  /// cases.
2209
  /// \code
2210
  ///    SpacesBeforeTrailingComments: 3
2211
  ///    void f() {
2212
  ///      if (true) {   // foo1
2213
  ///        f();        // bar
2214
  ///      }             // foo
2215
  ///    }
2216
  /// \endcode
2217
  unsigned SpacesBeforeTrailingComments;
2218
2219
  /// If ``true``, spaces will be inserted after ``<`` and before ``>``
2220
  /// in template argument lists.
2221
  /// \code
2222
  ///    true:                                  false:
2223
  ///    static_cast< int >(arg);       vs.     static_cast<int>(arg);
2224
  ///    std::function< void(int) > fct;        std::function<void(int)> fct;
2225
  /// \endcode
2226
  bool SpacesInAngles;
2227
2228
  /// If ``true``, spaces will be inserted around if/for/switch/while
2229
  /// conditions.
2230
  /// \code
2231
  ///    true:                                  false:
2232
  ///    if ( a )  { ... }              vs.     if (a) { ... }
2233
  ///    while ( i < 5 )  { ... }               while (i < 5) { ... }
2234
  /// \endcode
2235
  bool SpacesInConditionalStatement;
2236
2237
  /// If ``true``, spaces are inserted inside container literals (e.g.
2238
  /// ObjC and Javascript array and dict literals).
2239
  /// \code{.js}
2240
  ///    true:                                  false:
2241
  ///    var arr = [ 1, 2, 3 ];         vs.     var arr = [1, 2, 3];
2242
  ///    f({a : 1, b : 2, c : 3});              f({a: 1, b: 2, c: 3});
2243
  /// \endcode
2244
  bool SpacesInContainerLiterals;
2245
2246
  /// If ``true``, spaces may be inserted into C style casts.
2247
  /// \code
2248
  ///    true:                                  false:
2249
  ///    x = ( int32 )y                 vs.     x = (int32)y
2250
  /// \endcode
2251
  bool SpacesInCStyleCastParentheses;
2252
2253
  /// If ``true``, spaces will be inserted after ``(`` and before ``)``.
2254
  /// \code
2255
  ///    true:                                  false:
2256
  ///    t f( Deleted & ) & = delete;   vs.     t f(Deleted &) & = delete;
2257
  /// \endcode
2258
  bool SpacesInParentheses;
2259
2260
  /// If ``true``, spaces will be inserted after ``[`` and before ``]``.
2261
  /// Lambdas without arguments or unspecified size array declarations will not
2262
  /// be affected.
2263
  /// \code
2264
  ///    true:                                  false:
2265
  ///    int a[ 5 ];                    vs.     int a[5];
2266
  ///    std::unique_ptr<int[]> foo() {} // Won't be affected
2267
  /// \endcode
2268
  bool SpacesInSquareBrackets;
2269
2270
  /// If ``true``, spaces will be before  ``[``.
2271
  /// Lambdas will not be affected. Only the first ``[`` will get a space added.
2272
  /// \code
2273
  ///    true:                                  false:
2274
  ///    int a [5];                    vs.      int a[5];
2275
  ///    int a [5][5];                 vs.      int a[5][5];
2276
  /// \endcode
2277
  bool SpaceBeforeSquareBrackets;
2278
2279
  /// Styles for adding spacing around ``:`` in bitfield definitions.
2280
  enum BitFieldColonSpacingStyle {
2281
    /// Add one space on each side of the ``:``
2282
    /// \code
2283
    ///   unsigned bf : 2;
2284
    /// \endcode
2285
    BFCS_Both,
2286
    /// Add no space around the ``:`` (except when needed for
2287
    /// ``AlignConsecutiveBitFields``).
2288
    /// \code
2289
    ///   unsigned bf:2;
2290
    /// \endcode
2291
    BFCS_None,
2292
    /// Add space before the ``:`` only
2293
    /// \code
2294
    ///   unsigned bf :2;
2295
    /// \endcode
2296
    BFCS_Before,
2297
    /// Add space after the ``:`` only (space may be added before if
2298
    /// needed for ``AlignConsecutiveBitFields``).
2299
    /// \code
2300
    ///   unsigned bf: 2;
2301
    /// \endcode
2302
    BFCS_After
2303
  };
2304
  /// The BitFieldColonSpacingStyle to use for bitfields.
2305
  BitFieldColonSpacingStyle BitFieldColonSpacing;
2306
2307
  /// Supported language standards for parsing and formatting C++ constructs.
2308
  /// \code
2309
  ///    Latest:                                vector<set<int>>
2310
  ///    c++03                          vs.     vector<set<int> >
2311
  /// \endcode
2312
  ///
2313
  /// The correct way to spell a specific language version is e.g. ``c++11``.
2314
  /// The historical aliases ``Cpp03`` and ``Cpp11`` are deprecated.
2315
  enum LanguageStandard {
2316
    /// Parse and format as C++03.
2317
    /// ``Cpp03`` is a deprecated alias for ``c++03``
2318
    LS_Cpp03, // c++03
2319
    /// Parse and format as C++11.
2320
    LS_Cpp11, // c++11
2321
    /// Parse and format as C++14.
2322
    LS_Cpp14, // c++14
2323
    /// Parse and format as C++17.
2324
    LS_Cpp17, // c++17
2325
    /// Parse and format as C++20.
2326
    LS_Cpp20, // c++20
2327
    /// Parse and format using the latest supported language version.
2328
    /// ``Cpp11`` is a deprecated alias for ``Latest``
2329
    LS_Latest,
2330
    /// Automatic detection based on the input.
2331
    LS_Auto,
2332
  };
2333
2334
  /// Parse and format C++ constructs compatible with this standard.
2335
  /// \code
2336
  ///    c++03:                                 latest:
2337
  ///    vector<set<int> > x;           vs.     vector<set<int>> x;
2338
  /// \endcode
2339
  LanguageStandard Standard;
2340
2341
  /// The number of columns used for tab stops.
2342
  unsigned TabWidth;
2343
2344
  /// Different ways to use tab in formatting.
2345
  enum UseTabStyle {
2346
    /// Never use tab.
2347
    UT_Never,
2348
    /// Use tabs only for indentation.
2349
    UT_ForIndentation,
2350
    /// Fill all leading whitespace with tabs, and use spaces for alignment that
2351
    /// appears within a line (e.g. consecutive assignments and declarations).
2352
    UT_ForContinuationAndIndentation,
2353
    /// Use tabs for line continuation and indentation, and spaces for
2354
    /// alignment.
2355
    UT_AlignWithSpaces,
2356
    /// Use tabs whenever we need to fill whitespace that spans at least from
2357
    /// one tab stop to the next one.
2358
    UT_Always
2359
  };
2360
2361
  /// \brief Use ``\r\n`` instead of ``\n`` for line breaks.
2362
  /// Also used as fallback if ``DeriveLineEnding`` is true.
2363
  bool UseCRLF;
2364
2365
  /// The way to use tab characters in the resulting file.
2366
  UseTabStyle UseTab;
2367
2368
58
  bool operator==(const FormatStyle &R) const {
2369
58
    return AccessModifierOffset == R.AccessModifierOffset &&
2370
46
           AlignAfterOpenBracket == R.AlignAfterOpenBracket &&
2371
46
           AlignConsecutiveAssignments == R.AlignConsecutiveAssignments &&
2372
46
           AlignConsecutiveBitFields == R.AlignConsecutiveBitFields &&
2373
46
           AlignConsecutiveDeclarations == R.AlignConsecutiveDeclarations &&
2374
46
           AlignEscapedNewlines == R.AlignEscapedNewlines &&
2375
46
           AlignOperands == R.AlignOperands &&
2376
46
           AlignTrailingComments == R.AlignTrailingComments &&
2377
46
           AllowAllArgumentsOnNextLine == R.AllowAllArgumentsOnNextLine &&
2378
46
           AllowAllConstructorInitializersOnNextLine ==
2379
46
               R.AllowAllConstructorInitializersOnNextLine &&
2380
46
           AllowAllParametersOfDeclarationOnNextLine ==
2381
46
               R.AllowAllParametersOfDeclarationOnNextLine &&
2382
42
           AllowShortEnumsOnASingleLine == R.AllowShortEnumsOnASingleLine &&
2383
38
           AllowShortBlocksOnASingleLine == R.AllowShortBlocksOnASingleLine &&
2384
38
           AllowShortCaseLabelsOnASingleLine ==
2385
38
               R.AllowShortCaseLabelsOnASingleLine &&
2386
38
           AllowShortFunctionsOnASingleLine ==
2387
38
               R.AllowShortFunctionsOnASingleLine &&
2388
38
           AllowShortIfStatementsOnASingleLine ==
2389
38
               R.AllowShortIfStatementsOnASingleLine &&
2390
38
           AllowShortLambdasOnASingleLine == R.AllowShortLambdasOnASingleLine &&
2391
38
           AllowShortLoopsOnASingleLine == R.AllowShortLoopsOnASingleLine &&
2392
38
           AlwaysBreakAfterReturnType == R.AlwaysBreakAfterReturnType &&
2393
34
           AlwaysBreakBeforeMultilineStrings ==
2394
34
               R.AlwaysBreakBeforeMultilineStrings &&
2395
34
           AlwaysBreakTemplateDeclarations ==
2396
34
               R.AlwaysBreakTemplateDeclarations &&
2397
32
           AttributeMacros == R.AttributeMacros &&
2398
32
           BinPackArguments == R.BinPackArguments &&
2399
32
           BinPackParameters == R.BinPackParameters &&
2400
32
           BreakBeforeBinaryOperators == R.BreakBeforeBinaryOperators &&
2401
32
           BreakBeforeBraces == R.BreakBeforeBraces &&
2402
32
           BreakBeforeTernaryOperators == R.BreakBeforeTernaryOperators &&
2403
32
           BreakConstructorInitializers == R.BreakConstructorInitializers &&
2404
32
           CompactNamespaces == R.CompactNamespaces &&
2405
32
           BreakAfterJavaFieldAnnotations == R.BreakAfterJavaFieldAnnotations &&
2406
32
           BreakStringLiterals == R.BreakStringLiterals &&
2407
32
           ColumnLimit == R.ColumnLimit && CommentPragmas == R.CommentPragmas &&
2408
32
           BreakInheritanceList == R.BreakInheritanceList &&
2409
32
           ConstructorInitializerAllOnOneLineOrOnePerLine ==
2410
32
               R.ConstructorInitializerAllOnOneLineOrOnePerLine &&
2411
32
           ConstructorInitializerIndentWidth ==
2412
32
               R.ConstructorInitializerIndentWidth &&
2413
32
           ContinuationIndentWidth == R.ContinuationIndentWidth &&
2414
32
           Cpp11BracedListStyle == R.Cpp11BracedListStyle &&
2415
32
           DeriveLineEnding == R.DeriveLineEnding &&
2416
32
           DerivePointerAlignment == R.DerivePointerAlignment &&
2417
32
           DisableFormat == R.DisableFormat &&
2418
32
           ExperimentalAutoDetectBinPacking ==
2419
32
               R.ExperimentalAutoDetectBinPacking &&
2420
32
           FixNamespaceComments == R.FixNamespaceComments &&
2421
32
           ForEachMacros == R.ForEachMacros &&
2422
30
           IncludeStyle.IncludeBlocks == R.IncludeStyle.IncludeBlocks &&
2423
30
           IncludeStyle.IncludeCategories == R.IncludeStyle.IncludeCategories &&
2424
30
           IncludeStyle.IncludeIsMainRegex ==
2425
30
               R.IncludeStyle.IncludeIsMainRegex &&
2426
30
           IncludeStyle.IncludeIsMainSourceRegex ==
2427
30
               R.IncludeStyle.IncludeIsMainSourceRegex &&
2428
30
           IndentCaseLabels == R.IndentCaseLabels &&
2429
30
           IndentCaseBlocks == R.IndentCaseBlocks &&
2430
30
           IndentGotoLabels == R.IndentGotoLabels &&
2431
30
           IndentPPDirectives == R.IndentPPDirectives &&
2432
30
           IndentExternBlock == R.IndentExternBlock &&
2433
30
           IndentWidth == R.IndentWidth && Language == R.Language &&
2434
30
           IndentWrappedFunctionNames == R.IndentWrappedFunctionNames &&
2435
30
           JavaImportGroups == R.JavaImportGroups &&
2436
30
           JavaScriptQuotes == R.JavaScriptQuotes &&
2437
30
           JavaScriptWrapImports == R.JavaScriptWrapImports &&
2438
30
           KeepEmptyLinesAtTheStartOfBlocks ==
2439
30
               R.KeepEmptyLinesAtTheStartOfBlocks &&
2440
30
           MacroBlockBegin == R.MacroBlockBegin &&
2441
30
           MacroBlockEnd == R.MacroBlockEnd &&
2442
30
           MaxEmptyLinesToKeep == R.MaxEmptyLinesToKeep &&
2443
30
           NamespaceIndentation == R.NamespaceIndentation &&
2444
30
           NamespaceMacros == R.NamespaceMacros &&
2445
30
           ObjCBinPackProtocolList == R.ObjCBinPackProtocolList &&
2446
30
           ObjCBlockIndentWidth == R.ObjCBlockIndentWidth &&
2447
30
           ObjCBreakBeforeNestedBlockParam ==
2448
30
               R.ObjCBreakBeforeNestedBlockParam &&
2449
30
           ObjCSpaceAfterProperty == R.ObjCSpaceAfterProperty &&
2450
30
           ObjCSpaceBeforeProtocolList == R.ObjCSpaceBeforeProtocolList &&
2451
30
           PenaltyBreakAssignment == R.PenaltyBreakAssignment &&
2452
30
           PenaltyBreakBeforeFirstCallParameter ==
2453
30
               R.PenaltyBreakBeforeFirstCallParameter &&
2454
30
           PenaltyBreakComment == R.PenaltyBreakComment &&
2455
30
           PenaltyBreakFirstLessLess == R.PenaltyBreakFirstLessLess &&
2456
30
           PenaltyBreakString == R.PenaltyBreakString &&
2457
30
           PenaltyExcessCharacter == R.PenaltyExcessCharacter &&
2458
30
           PenaltyReturnTypeOnItsOwnLine == R.PenaltyReturnTypeOnItsOwnLine &&
2459
30
           PenaltyBreakTemplateDeclaration ==
2460
30
               R.PenaltyBreakTemplateDeclaration &&
2461
30
           PointerAlignment == R.PointerAlignment &&
2462
30
           RawStringFormats == R.RawStringFormats &&
2463
30
           SortJavaStaticImport == R.SortJavaStaticImport &&
2464
30
           SpaceAfterCStyleCast == R.SpaceAfterCStyleCast &&
2465
30
           SpaceAfterLogicalNot == R.SpaceAfterLogicalNot &&
2466
30
           SpaceAfterTemplateKeyword == R.SpaceAfterTemplateKeyword &&
2467
30
           SpaceBeforeAssignmentOperators == R.SpaceBeforeAssignmentOperators &&
2468
30
           SpaceBeforeCpp11BracedList == R.SpaceBeforeCpp11BracedList &&
2469
30
           SpaceBeforeCtorInitializerColon ==
2470
30
               R.SpaceBeforeCtorInitializerColon &&
2471
30
           SpaceBeforeInheritanceColon == R.SpaceBeforeInheritanceColon &&
2472
30
           SpaceBeforeParens == R.SpaceBeforeParens &&
2473
30
           SpaceBeforeRangeBasedForLoopColon ==
2474
30
               R.SpaceBeforeRangeBasedForLoopColon &&
2475
30
           SpaceInEmptyBlock == R.SpaceInEmptyBlock &&
2476
30
           SpaceInEmptyParentheses == R.SpaceInEmptyParentheses &&
2477
30
           SpacesBeforeTrailingComments == R.SpacesBeforeTrailingComments &&
2478
30
           SpacesInAngles == R.SpacesInAngles &&
2479
30
           SpacesInConditionalStatement == R.SpacesInConditionalStatement &&
2480
30
           SpacesInContainerLiterals == R.SpacesInContainerLiterals &&
2481
30
           SpacesInCStyleCastParentheses == R.SpacesInCStyleCastParentheses &&
2482
30
           SpacesInParentheses == R.SpacesInParentheses &&
2483
30
           SpacesInSquareBrackets == R.SpacesInSquareBrackets &&
2484
30
           SpaceBeforeSquareBrackets == R.SpaceBeforeSquareBrackets &&
2485
30
           BitFieldColonSpacing == R.BitFieldColonSpacing &&
2486
30
           Standard == R.Standard && TabWidth == R.TabWidth &&
2487
30
           StatementMacros == R.StatementMacros && UseTab == R.UseTab &&
2488
30
           UseCRLF == R.UseCRLF && TypenameMacros == R.TypenameMacros;
2489
58
  }
2490
2491
  llvm::Optional<FormatStyle> GetLanguageStyle(LanguageKind Language) const;
2492
2493
  // Stores per-language styles. A FormatStyle instance inside has an empty
2494
  // StyleSet. A FormatStyle instance returned by the Get method has its
2495
  // StyleSet set to a copy of the originating StyleSet, effectively keeping the
2496
  // internal representation of that StyleSet alive.
2497
  //
2498
  // The memory management and ownership reminds of a birds nest: chicks
2499
  // leaving the nest take photos of the nest with them.
2500
  struct FormatStyleSet {
2501
    typedef std::map<FormatStyle::LanguageKind, FormatStyle> MapType;
2502
2503
    llvm::Optional<FormatStyle> Get(FormatStyle::LanguageKind Language) const;
2504
2505
    // Adds \p Style to this FormatStyleSet. Style must not have an associated
2506
    // FormatStyleSet.
2507
    // Style.Language should be different than LK_None. If this FormatStyleSet
2508
    // already contains an entry for Style.Language, that gets replaced with the
2509
    // passed Style.
2510
    void Add(FormatStyle Style);
2511
2512
    // Clears this FormatStyleSet.
2513
    void Clear();
2514
2515
  private:
2516
    std::shared_ptr<MapType> Styles;
2517
  };
2518
2519
  static FormatStyleSet BuildStyleSetFromConfiguration(
2520
      const FormatStyle &MainStyle,
2521
      const std::vector<FormatStyle> &ConfigurationStyles);
2522
2523
private:
2524
  FormatStyleSet StyleSet;
2525
2526
  friend std::error_code parseConfiguration(StringRef Text, FormatStyle *Style,
2527
                                            bool AllowUnknownOptions);
2528
};
2529
2530
/// Returns a format style complying with the LLVM coding standards:
2531
/// http://llvm.org/docs/CodingStandards.html.
2532
FormatStyle getLLVMStyle(
2533
    FormatStyle::LanguageKind Language = FormatStyle::LanguageKind::LK_Cpp);
2534
2535
/// Returns a format style complying with one of Google's style guides:
2536
/// http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml.
2537
/// http://google-styleguide.googlecode.com/svn/trunk/javascriptguide.xml.
2538
/// https://developers.google.com/protocol-buffers/docs/style.
2539
FormatStyle getGoogleStyle(FormatStyle::LanguageKind Language);
2540
2541
/// Returns a format style complying with Chromium's style guide:
2542
/// http://www.chromium.org/developers/coding-style.
2543
FormatStyle getChromiumStyle(FormatStyle::LanguageKind Language);
2544
2545
/// Returns a format style complying with Mozilla's style guide:
2546
/// https://developer.mozilla.org/en-US/docs/Developer_Guide/Coding_Style.
2547
FormatStyle getMozillaStyle();
2548
2549
/// Returns a format style complying with Webkit's style guide:
2550
/// http://www.webkit.org/coding/coding-style.html
2551
FormatStyle getWebKitStyle();
2552
2553
/// Returns a format style complying with GNU Coding Standards:
2554
/// http://www.gnu.org/prep/standards/standards.html
2555
FormatStyle getGNUStyle();
2556
2557
/// Returns a format style complying with Microsoft style guide:
2558
/// https://docs.microsoft.com/en-us/visualstudio/ide/editorconfig-code-style-settings-reference?view=vs-2017
2559
FormatStyle getMicrosoftStyle(FormatStyle::LanguageKind Language);
2560
2561
/// Returns style indicating formatting should be not applied at all.
2562
FormatStyle getNoStyle();
2563
2564
/// Gets a predefined style for the specified language by name.
2565
///
2566
/// Currently supported names: LLVM, Google, Chromium, Mozilla. Names are
2567
/// compared case-insensitively.
2568
///
2569
/// Returns ``true`` if the Style has been set.
2570
bool getPredefinedStyle(StringRef Name, FormatStyle::LanguageKind Language,
2571
                        FormatStyle *Style);
2572
2573
/// Parse configuration from YAML-formatted text.
2574
///
2575
/// Style->Language is used to get the base style, if the ``BasedOnStyle``
2576
/// option is present.
2577
///
2578
/// The FormatStyleSet of Style is reset.
2579
///
2580
/// When ``BasedOnStyle`` is not present, options not present in the YAML
2581
/// document, are retained in \p Style.
2582
///
2583
/// If AllowUnknownOptions is true, no errors are emitted if unknown
2584
/// format options are occured.
2585
std::error_code parseConfiguration(StringRef Text, FormatStyle *Style,
2586
                                   bool AllowUnknownOptions = false);
2587
2588
/// Gets configuration in a YAML string.
2589
std::string configurationAsText(const FormatStyle &Style);
2590
2591
/// Returns the replacements necessary to sort all ``#include`` blocks
2592
/// that are affected by ``Ranges``.
2593
tooling::Replacements sortIncludes(const FormatStyle &Style, StringRef Code,
2594
                                   ArrayRef<tooling::Range> Ranges,
2595
                                   StringRef FileName,
2596
                                   unsigned *Cursor = nullptr);
2597
2598
/// Returns the replacements corresponding to applying and formatting
2599
/// \p Replaces on success; otheriwse, return an llvm::Error carrying
2600
/// llvm::StringError.
2601
llvm::Expected<tooling::Replacements>
2602
formatReplacements(StringRef Code, const tooling::Replacements &Replaces,
2603
                   const FormatStyle &Style);
2604
2605
/// Returns the replacements corresponding to applying \p Replaces and
2606
/// cleaning up the code after that on success; otherwise, return an llvm::Error
2607
/// carrying llvm::StringError.
2608
/// This also supports inserting/deleting C++ #include directives:
2609
/// - If a replacement has offset UINT_MAX, length 0, and a replacement text
2610
///   that is an #include directive, this will insert the #include into the
2611
///   correct block in the \p Code.
2612
/// - If a replacement has offset UINT_MAX, length 1, and a replacement text
2613
///   that is the name of the header to be removed, the header will be removed
2614
///   from \p Code if it exists.
2615
/// The include manipulation is done via `tooling::HeaderInclude`, see its
2616
/// documentation for more details on how include insertion points are found and
2617
/// what edits are produced.
2618
llvm::Expected<tooling::Replacements>
2619
cleanupAroundReplacements(StringRef Code, const tooling::Replacements &Replaces,
2620
                          const FormatStyle &Style);
2621
2622
/// Represents the status of a formatting attempt.
2623
struct FormattingAttemptStatus {
2624
  /// A value of ``false`` means that any of the affected ranges were not
2625
  /// formatted due to a non-recoverable syntax error.
2626
  bool FormatComplete = true;
2627
2628
  /// If ``FormatComplete`` is false, ``Line`` records a one-based
2629
  /// original line number at which a syntax error might have occurred. This is
2630
  /// based on a best-effort analysis and could be imprecise.
2631
  unsigned Line = 0;
2632
};
2633
2634
/// Reformats the given \p Ranges in \p Code.
2635
///
2636
/// Each range is extended on either end to its next bigger logic unit, i.e.
2637
/// everything that might influence its formatting or might be influenced by its
2638
/// formatting.
2639
///
2640
/// Returns the ``Replacements`` necessary to make all \p Ranges comply with
2641
/// \p Style.
2642
///
2643
/// If ``Status`` is non-null, its value will be populated with the status of
2644
/// this formatting attempt. See \c FormattingAttemptStatus.
2645
tooling::Replacements reformat(const FormatStyle &Style, StringRef Code,
2646
                               ArrayRef<tooling::Range> Ranges,
2647
                               StringRef FileName = "<stdin>",
2648
                               FormattingAttemptStatus *Status = nullptr);
2649
2650
/// Same as above, except if ``IncompleteFormat`` is non-null, its value
2651
/// will be set to true if any of the affected ranges were not formatted due to
2652
/// a non-recoverable syntax error.
2653
tooling::Replacements reformat(const FormatStyle &Style, StringRef Code,
2654
                               ArrayRef<tooling::Range> Ranges,
2655
                               StringRef FileName, bool *IncompleteFormat);
2656
2657
/// Clean up any erroneous/redundant code in the given \p Ranges in \p
2658
/// Code.
2659
///
2660
/// Returns the ``Replacements`` that clean up all \p Ranges in \p Code.
2661
tooling::Replacements cleanup(const FormatStyle &Style, StringRef Code,
2662
                              ArrayRef<tooling::Range> Ranges,
2663
                              StringRef FileName = "<stdin>");
2664
2665
/// Fix namespace end comments in the given \p Ranges in \p Code.
2666
///
2667
/// Returns the ``Replacements`` that fix the namespace comments in all
2668
/// \p Ranges in \p Code.
2669
tooling::Replacements fixNamespaceEndComments(const FormatStyle &Style,
2670
                                              StringRef Code,
2671
                                              ArrayRef<tooling::Range> Ranges,
2672
                                              StringRef FileName = "<stdin>");
2673
2674
/// Sort consecutive using declarations in the given \p Ranges in
2675
/// \p Code.
2676
///
2677
/// Returns the ``Replacements`` that sort the using declarations in all
2678
/// \p Ranges in \p Code.
2679
tooling::Replacements sortUsingDeclarations(const FormatStyle &Style,
2680
                                            StringRef Code,
2681
                                            ArrayRef<tooling::Range> Ranges,
2682
                                            StringRef FileName = "<stdin>");
2683
2684
/// Returns the ``LangOpts`` that the formatter expects you to set.
2685
///
2686
/// \param Style determines specific settings for lexing mode.
2687
LangOptions getFormattingLangOpts(const FormatStyle &Style = getLLVMStyle());
2688
2689
/// Description to be used for help text for a ``llvm::cl`` option for
2690
/// specifying format style. The description is closely related to the operation
2691
/// of ``getStyle()``.
2692
extern const char *StyleOptionHelpDescription;
2693
2694
/// The suggested format style to use by default. This allows tools using
2695
/// `getStyle` to have a consistent default style.
2696
/// Different builds can modify the value to the preferred styles.
2697
extern const char *DefaultFormatStyle;
2698
2699
/// The suggested predefined style to use as the fallback style in `getStyle`.
2700
/// Different builds can modify the value to the preferred styles.
2701
extern const char *DefaultFallbackStyle;
2702
2703
/// Construct a FormatStyle based on ``StyleName``.
2704
///
2705
/// ``StyleName`` can take several forms:
2706
/// * "{<key>: <value>, ...}" - Set specic style parameters.
2707
/// * "<style name>" - One of the style names supported by
2708
/// getPredefinedStyle().
2709
/// * "file" - Load style configuration from a file called ``.clang-format``
2710
/// located in one of the parent directories of ``FileName`` or the current
2711
/// directory if ``FileName`` is empty.
2712
///
2713
/// \param[in] StyleName Style name to interpret according to the description
2714
/// above.
2715
/// \param[in] FileName Path to start search for .clang-format if ``StyleName``
2716
/// == "file".
2717
/// \param[in] FallbackStyle The name of a predefined style used to fallback to
2718
/// in case \p StyleName is "file" and no file can be found.
2719
/// \param[in] Code The actual code to be formatted. Used to determine the
2720
/// language if the filename isn't sufficient.
2721
/// \param[in] FS The underlying file system, in which the file resides. By
2722
/// default, the file system is the real file system.
2723
/// \param[in] AllowUnknownOptions If true, unknown format options only
2724
///             emit a warning. If false, errors are emitted on unknown format
2725
///             options.
2726
///
2727
/// \returns FormatStyle as specified by ``StyleName``. If ``StyleName`` is
2728
/// "file" and no file is found, returns ``FallbackStyle``. If no style could be
2729
/// determined, returns an Error.
2730
llvm::Expected<FormatStyle> getStyle(StringRef StyleName, StringRef FileName,
2731
                                     StringRef FallbackStyle,
2732
                                     StringRef Code = "",
2733
                                     llvm::vfs::FileSystem *FS = nullptr,
2734
                                     bool AllowUnknownOptions = false);
2735
2736
// Guesses the language from the ``FileName`` and ``Code`` to be formatted.
2737
// Defaults to FormatStyle::LK_Cpp.
2738
FormatStyle::LanguageKind guessLanguage(StringRef FileName, StringRef Code);
2739
2740
// Returns a string representation of ``Language``.
2741
0
inline StringRef getLanguageName(FormatStyle::LanguageKind Language) {
2742
0
  switch (Language) {
2743
0
  case FormatStyle::LK_Cpp:
2744
0
    return "C++";
2745
0
  case FormatStyle::LK_CSharp:
2746
0
    return "CSharp";
2747
0
  case FormatStyle::LK_ObjC:
2748
0
    return "Objective-C";
2749
0
  case FormatStyle::LK_Java:
2750
0
    return "Java";
2751
0
  case FormatStyle::LK_JavaScript:
2752
0
    return "JavaScript";
2753
0
  case FormatStyle::LK_Proto:
2754
0
    return "Proto";
2755
0
  case FormatStyle::LK_TableGen:
2756
0
    return "TableGen";
2757
0
  case FormatStyle::LK_TextProto:
2758
0
    return "TextProto";
2759
0
  default:
2760
0
    return "Unknown";
2761
0
  }
2762
0
}
2763
2764
} // end namespace format
2765
} // end namespace clang
2766
2767
namespace std {
2768
template <>
2769
struct is_error_code_enum<clang::format::ParseError> : std::true_type {};
2770
} // namespace std
2771
2772
#endif // LLVM_CLANG_FORMAT_FORMAT_H