Coverage Report

Created: 2020-02-15 09:57

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