Coverage Report

Created: 2022-01-18 06:27

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/Format/UnwrappedLineFormatter.cpp
Line
Count
Source (jump to first uncovered line)
1
//===--- UnwrappedLineFormatter.cpp - Format C++ code ---------------------===//
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
#include "UnwrappedLineFormatter.h"
10
#include "NamespaceEndCommentsFixer.h"
11
#include "WhitespaceManager.h"
12
#include "llvm/Support/Debug.h"
13
#include <queue>
14
15
#define DEBUG_TYPE "format-formatter"
16
17
namespace clang {
18
namespace format {
19
20
namespace {
21
22
5.09k
bool startsExternCBlock(const AnnotatedLine &Line) {
23
5.09k
  const FormatToken *Next = Line.First->getNextNonComment();
24
5.09k
  const FormatToken *NextNext = Next ? 
Next->getNextNonComment()4.55k
:
nullptr537
;
25
5.09k
  return Line.startsWith(tok::kw_extern) && 
Next46
&&
Next->isStringLiteral()46
&&
26
5.09k
         
NextNext46
&&
NextNext->is(tok::l_brace)46
;
27
5.09k
}
28
29
/// Tracks the indent level of \c AnnotatedLines across levels.
30
///
31
/// \c nextLine must be called for each \c AnnotatedLine, after which \c
32
/// getIndent() will return the indent for the last line \c nextLine was called
33
/// with.
34
/// If the line is not formatted (and thus the indent does not change), calling
35
/// \c adjustToUnmodifiedLine after the call to \c nextLine will cause
36
/// subsequent lines on the same level to be indented at the same level as the
37
/// given line.
38
class LevelIndentTracker {
39
public:
40
  LevelIndentTracker(const FormatStyle &Style,
41
                     const AdditionalKeywords &Keywords, unsigned StartLevel,
42
                     int AdditionalIndent)
43
22.6k
      : Style(Style), Keywords(Keywords), AdditionalIndent(AdditionalIndent) {
44
24.6k
    for (unsigned i = 0; i != StartLevel; 
++i2.04k
)
45
2.04k
      IndentForLevel.push_back(Style.IndentWidth * i + AdditionalIndent);
46
22.6k
  }
47
48
  /// Returns the indent for the current line.
49
148k
  unsigned getIndent() const { return Indent; }
50
51
  /// Update the indent state given that \p Line is going to be formatted
52
  /// next.
53
74.2k
  void nextLine(const AnnotatedLine &Line) {
54
74.2k
    Offset = getIndentOffset(*Line.First);
55
    // Update the indent level cache size so that we can rely on it
56
    // having the right size in adjustToUnmodifiedline.
57
103k
    while (IndentForLevel.size() <= Line.Level)
58
29.5k
      IndentForLevel.push_back(-1);
59
74.2k
    if (Line.InPPDirective) {
60
4.40k
      unsigned IndentWidth =
61
4.40k
          (Style.PPIndentWidth >= 0) ? 
Style.PPIndentWidth27
:
Style.IndentWidth4.38k
;
62
4.40k
      Indent = Line.Level * IndentWidth + AdditionalIndent;
63
69.8k
    } else {
64
69.8k
      IndentForLevel.resize(Line.Level + 1);
65
69.8k
      Indent = getIndent(Line.Level);
66
69.8k
    }
67
74.2k
    if (static_cast<int>(Indent) + Offset >= 0)
68
74.2k
      Indent += Offset;
69
74.2k
    if (Line.First->is(TT_CSharpGenericTypeConstraint))
70
12
      Indent = Line.Level * Style.IndentWidth + Style.ContinuationIndentWidth;
71
74.2k
  }
72
73
  /// Update the indent state given that \p Line indent should be
74
  /// skipped.
75
23
  void skipLine(const AnnotatedLine &Line) {
76
26
    while (IndentForLevel.size() <= Line.Level)
77
3
      IndentForLevel.push_back(Indent);
78
23
  }
79
80
  /// Update the level indent to adapt to the given \p Line.
81
  ///
82
  /// When a line is not formatted, we move the subsequent lines on the same
83
  /// level to the same indent.
84
  /// Note that \c nextLine must have been called before this method.
85
5.19k
  void adjustToUnmodifiedLine(const AnnotatedLine &Line) {
86
5.19k
    unsigned LevelIndent = Line.First->OriginalColumn;
87
5.19k
    if (static_cast<int>(LevelIndent) - Offset >= 0)
88
5.19k
      LevelIndent -= Offset;
89
5.19k
    if ((!Line.First->is(tok::comment) || 
IndentForLevel[Line.Level] == -19
) &&
90
5.19k
        
!Line.InPPDirective5.18k
)
91
4.77k
      IndentForLevel[Line.Level] = LevelIndent;
92
5.19k
  }
93
94
private:
95
  /// Get the offset of the line relatively to the level.
96
  ///
97
  /// For example, 'public:' labels in classes are offset by 1 or 2
98
  /// characters to the left from their level.
99
74.2k
  int getIndentOffset(const FormatToken &RootToken) {
100
74.2k
    if (Style.Language == FormatStyle::LK_Java || 
Style.isJavaScript()73.3k
||
101
74.2k
        
Style.isCSharp()68.7k
)
102
8.10k
      return 0;
103
66.1k
    if (RootToken.isAccessSpecifier(false) ||
104
66.1k
        
RootToken.isObjCAccessSpecifier()65.5k
||
105
66.1k
        
(65.4k
RootToken.isOneOf(Keywords.kw_signals, Keywords.kw_qsignals)65.4k
&&
106
65.4k
         
RootToken.Next15
&&
RootToken.Next->is(tok::colon)15
)) {
107
      // The AccessModifierOffset may be overridden by IndentAccessModifiers,
108
      // in which case we take a negative value of the IndentWidth to simulate
109
      // the upper indent level.
110
720
      return Style.IndentAccessModifiers ? 
-Style.IndentWidth15
111
720
                                         : 
Style.AccessModifierOffset705
;
112
720
    }
113
65.4k
    return 0;
114
66.1k
  }
115
116
  /// Get the indent of \p Level from \p IndentForLevel.
117
  ///
118
  /// \p IndentForLevel must contain the indent for the level \c l
119
  /// at \p IndentForLevel[l], or a value < 0 if the indent for
120
  /// that level is unknown.
121
86.0k
  unsigned getIndent(unsigned Level) const {
122
86.0k
    if (IndentForLevel[Level] != -1)
123
8.65k
      return IndentForLevel[Level];
124
77.3k
    if (Level == 0)
125
61.2k
      return 0;
126
16.1k
    return getIndent(Level - 1) + Style.IndentWidth;
127
77.3k
  }
128
129
  const FormatStyle &Style;
130
  const AdditionalKeywords &Keywords;
131
  const unsigned AdditionalIndent;
132
133
  /// The indent in characters for each level.
134
  std::vector<int> IndentForLevel;
135
136
  /// Offset of the current line relative to the indent level.
137
  ///
138
  /// For example, the 'public' keywords is often indented with a negative
139
  /// offset.
140
  int Offset = 0;
141
142
  /// The current line's indent.
143
  unsigned Indent = 0;
144
};
145
146
const FormatToken *getMatchingNamespaceToken(
147
    const AnnotatedLine *Line,
148
77
    const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines) {
149
77
  if (!Line->startsWith(tok::r_brace))
150
30
    return nullptr;
151
47
  size_t StartLineIndex = Line->MatchingOpeningBlockLineIndex;
152
47
  if (StartLineIndex == UnwrappedLine::kInvalidIndex)
153
0
    return nullptr;
154
47
  assert(StartLineIndex < AnnotatedLines.size());
155
0
  return AnnotatedLines[StartLineIndex]->First->getNamespaceToken();
156
47
}
157
158
59
StringRef getNamespaceTokenText(const AnnotatedLine *Line) {
159
59
  const FormatToken *NamespaceToken = Line->First->getNamespaceToken();
160
59
  return NamespaceToken ? 
NamespaceToken->TokenText30
:
StringRef()29
;
161
59
}
162
163
StringRef getMatchingNamespaceTokenText(
164
    const AnnotatedLine *Line,
165
47
    const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines) {
166
47
  const FormatToken *NamespaceToken =
167
47
      getMatchingNamespaceToken(Line, AnnotatedLines);
168
47
  return NamespaceToken ? 
NamespaceToken->TokenText25
:
StringRef()22
;
169
47
}
170
171
class LineJoiner {
172
public:
173
  LineJoiner(const FormatStyle &Style, const AdditionalKeywords &Keywords,
174
             const SmallVectorImpl<AnnotatedLine *> &Lines)
175
      : Style(Style), Keywords(Keywords), End(Lines.end()), Next(Lines.begin()),
176
23.2k
        AnnotatedLines(Lines) {}
177
178
  /// Returns the next line, merging multiple lines into one if possible.
179
  const AnnotatedLine *getNextMergedLine(bool DryRun,
180
96.9k
                                         LevelIndentTracker &IndentTracker) {
181
96.9k
    if (Next == End)
182
22.6k
      return nullptr;
183
74.2k
    const AnnotatedLine *Current = *Next;
184
74.2k
    IndentTracker.nextLine(*Current);
185
74.2k
    unsigned MergedLines = tryFitMultipleLinesInOne(IndentTracker, Next, End);
186
74.2k
    if (MergedLines > 0 && 
Style.ColumnLimit == 05.27k
)
187
      // Disallow line merging if there is a break at the start of one of the
188
      // input lines.
189
97
      
for (unsigned i = 0; 42
i < MergedLines;
++i55
)
190
55
        if (Next[i + 1]->First->NewlinesBefore > 0)
191
2
          MergedLines = 0;
192
74.2k
    if (!DryRun)
193
79.1k
      
for (unsigned i = 0; 72.3k
i < MergedLines;
++i6.82k
)
194
6.82k
        join(*Next[0], *Next[i + 1]);
195
74.2k
    Next = Next + MergedLines + 1;
196
74.2k
    return Current;
197
96.9k
  }
198
199
private:
200
  /// Calculates how many lines can be merged into 1 starting at \p I.
201
  unsigned
202
  tryFitMultipleLinesInOne(LevelIndentTracker &IndentTracker,
203
                           SmallVectorImpl<AnnotatedLine *>::const_iterator I,
204
74.2k
                           SmallVectorImpl<AnnotatedLine *>::const_iterator E) {
205
74.2k
    const unsigned Indent = IndentTracker.getIndent();
206
207
    // Can't join the last line with anything.
208
74.2k
    if (I + 1 == E)
209
22.6k
      return 0;
210
    // We can never merge stuff if there are trailing line comments.
211
51.6k
    const AnnotatedLine *TheLine = *I;
212
51.6k
    if (TheLine->Last->is(TT_LineComment))
213
2.50k
      return 0;
214
49.1k
    if (I[1]->Type == LT_Invalid || 
I[1]->First->MustBreakBefore49.1k
)
215
1.19k
      return 0;
216
47.9k
    if (TheLine->InPPDirective &&
217
47.9k
        
(3.27k
!I[1]->InPPDirective3.27k
||
I[1]->First->HasUnescapedNewline1.85k
))
218
2.09k
      return 0;
219
220
45.8k
    if (Style.ColumnLimit > 0 && 
Indent > Style.ColumnLimit44.6k
)
221
0
      return 0;
222
223
45.8k
    unsigned Limit =
224
45.8k
        Style.ColumnLimit == 0 ? UINT_MAX : 
Style.ColumnLimit - Indent44.6k
;
225
    // If we already exceed the column limit, we set 'Limit' to 0. The different
226
    // tryMerge..() functions can then decide whether to still do merging.
227
45.8k
    Limit = TheLine->Last->TotalLength > Limit
228
45.8k
                ? 
05.72k
229
45.8k
                : 
Limit - TheLine->Last->TotalLength40.1k
;
230
231
45.8k
    if (TheLine->Last->is(TT_FunctionLBrace) &&
232
45.8k
        
TheLine->First == TheLine->Last4.68k
&&
233
45.8k
        
!Style.BraceWrapping.SplitEmptyFunction462
&&
234
45.8k
        
I[1]->First->is(tok::r_brace)27
)
235
12
      return tryMergeSimpleBlock(I, E, Limit);
236
237
    // Handle empty record blocks where the brace has already been wrapped
238
45.8k
    if (TheLine->Last->is(tok::l_brace) && 
TheLine->First == TheLine->Last11.5k
&&
239
45.8k
        
I != AnnotatedLines.begin()1.37k
) {
240
1.24k
      bool EmptyBlock = I[1]->First->is(tok::r_brace);
241
242
1.24k
      const FormatToken *Tok = I[-1]->First;
243
1.24k
      if (Tok && Tok->is(tok::comment))
244
24
        Tok = Tok->getNextNonComment();
245
246
1.24k
      if (Tok && 
Tok->getNamespaceToken()1.24k
)
247
80
        return !Style.BraceWrapping.SplitEmptyNamespace && 
EmptyBlock18
248
80
                   ? 
tryMergeSimpleBlock(I, E, Limit)15
249
80
                   : 
065
;
250
251
1.16k
      if (Tok && 
Tok->is(tok::kw_typedef)1.16k
)
252
21
        Tok = Tok->getNextNonComment();
253
1.16k
      if (Tok && Tok->isOneOf(tok::kw_class, tok::kw_struct, tok::kw_union,
254
1.16k
                              tok::kw_extern, Keywords.kw_interface))
255
159
        return !Style.BraceWrapping.SplitEmptyRecord && 
EmptyBlock60
256
159
                   ? 
tryMergeSimpleBlock(I, E, Limit)30
257
159
                   : 
0129
;
258
259
1.01k
      if (Tok && 
Tok->is(tok::kw_template)1.00k
&&
260
1.01k
          
Style.BraceWrapping.SplitEmptyRecord66
&&
EmptyBlock60
) {
261
9
        return 0;
262
9
      }
263
1.01k
    }
264
265
45.5k
    auto ShouldMergeShortFunctions =
266
45.5k
        [this, B = AnnotatedLines.begin()](
267
45.5k
            SmallVectorImpl<AnnotatedLine *>::const_iterator I) {
268
45.5k
          if (Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_All)
269
37.7k
            return true;
270
7.80k
          if (Style.AllowShortFunctionsOnASingleLine >=
271
7.80k
                  FormatStyle::SFS_Empty &&
272
7.80k
              
I[1]->First->is(tok::r_brace)5.99k
)
273
1.15k
            return true;
274
275
6.64k
          if (Style.AllowShortFunctionsOnASingleLine &
276
6.64k
              FormatStyle::SFS_InlineOnly) {
277
            // Just checking TheLine->Level != 0 is not enough, because it
278
            // provokes treating functions inside indented namespaces as short.
279
411
            if ((*I)->Level != 0) {
280
121
              if (I == B)
281
0
                return false;
282
283
              // TODO: Use IndentTracker to avoid loop?
284
              // Find the last line with lower level.
285
121
              auto J = I - 1;
286
133
              for (; J != B; 
--J12
)
287
42
                if ((*J)->Level < (*I)->Level)
288
30
                  break;
289
290
              // Check if the found line starts a record.
291
121
              auto *RecordTok = (*J)->First;
292
256
              while (RecordTok) {
293
                // TODO: Refactor to isRecord(RecordTok).
294
204
                if (RecordTok->isOneOf(tok::kw_class, tok::kw_struct))
295
54
                  return true;
296
150
                if (Style.isCpp() && 
RecordTok->is(tok::kw_union)126
)
297
3
                  return true;
298
147
                if (Style.isCSharp() && 
RecordTok->is(Keywords.kw_interface)16
)
299
4
                  return true;
300
143
                if (Style.Language == FormatStyle::LK_Java &&
301
143
                    
RecordTok->is(tok::kw_enum)6
)
302
6
                  return true;
303
137
                if (Style.isJavaScript() && 
RecordTok->is(Keywords.kw_function)2
)
304
2
                  return true;
305
306
135
                RecordTok = RecordTok->Next;
307
135
              }
308
309
52
              return false;
310
121
            }
311
411
          }
312
313
6.52k
          return false;
314
6.64k
        };
315
316
45.5k
    bool MergeShortFunctions = ShouldMergeShortFunctions(I);
317
318
45.5k
    if (Style.CompactNamespaces) {
319
66
      if (auto nsToken = TheLine->First->getNamespaceToken()) {
320
36
        int i = 0;
321
36
        unsigned closingLine = TheLine->MatchingClosingBlockLineIndex - 1;
322
59
        for (; I + 1 + i != E &&
323
59
               nsToken->TokenText == getNamespaceTokenText(I[i + 1]) &&
324
59
               
closingLine == I[i + 1]->MatchingClosingBlockLineIndex27
&&
325
59
               
I[i + 1]->Last->TotalLength < Limit25
;
326
36
             
i++, closingLine--23
) {
327
          // No extra indent for compacted namespaces
328
23
          IndentTracker.skipLine(*I[i + 1]);
329
330
23
          Limit -= I[i + 1]->Last->TotalLength;
331
23
        }
332
36
        return i;
333
36
      }
334
335
30
      if (auto nsToken = getMatchingNamespaceToken(TheLine, AnnotatedLines)) {
336
22
        int i = 0;
337
22
        unsigned openingLine = TheLine->MatchingOpeningBlockLineIndex - 1;
338
47
        for (; I + 1 + i != E &&
339
47
               nsToken->TokenText ==
340
47
                   getMatchingNamespaceTokenText(I[i + 1], AnnotatedLines) &&
341
47
               
openingLine == I[i + 1]->MatchingOpeningBlockLineIndex25
;
342
25
             i++, openingLine--) {
343
          // No space between consecutive braces
344
25
          I[i + 1]->First->SpacesRequiredBefore = !I[i]->Last->is(tok::r_brace);
345
346
          // Indent like the outer-most namespace
347
25
          IndentTracker.nextLine(*I[i + 1]);
348
25
        }
349
22
        return i;
350
22
      }
351
30
    }
352
353
    // Try to merge a function block with left brace unwrapped
354
45.5k
    if (TheLine->Last->is(TT_FunctionLBrace) &&
355
45.5k
        
TheLine->First != TheLine->Last4.66k
) {
356
4.22k
      return MergeShortFunctions ? 
tryMergeSimpleBlock(I, E, Limit)3.83k
:
0387
;
357
4.22k
    }
358
    // Try to merge a control statement block with left brace unwrapped
359
41.3k
    if (TheLine->Last->is(tok::l_brace) && 
TheLine->First != TheLine->Last7.02k
&&
360
41.3k
        TheLine->First->isOneOf(tok::kw_if, tok::kw_while, tok::kw_for,
361
5.89k
                                TT_ForEachMacro)) {
362
1.04k
      return Style.AllowShortBlocksOnASingleLine != FormatStyle::SBS_Never
363
1.04k
                 ? 
tryMergeSimpleBlock(I, E, Limit)137
364
1.04k
                 : 
0909
;
365
1.04k
    }
366
    // Try to merge a control statement block with left brace wrapped
367
40.2k
    if (I[1]->First->is(tok::l_brace) &&
368
40.2k
        
(1.41k
TheLine->First->isOneOf(tok::kw_if, tok::kw_else, tok::kw_while,
369
1.41k
                                 tok::kw_for, tok::kw_switch, tok::kw_try,
370
1.41k
                                 tok::kw_do, TT_ForEachMacro) ||
371
1.41k
         
(1.07k
TheLine->First->is(tok::r_brace)1.07k
&&
TheLine->First->Next31
&&
372
1.07k
          
TheLine->First->Next->isOneOf(tok::kw_else, tok::kw_catch)31
)) &&
373
40.2k
        Style.BraceWrapping.AfterControlStatement ==
374
370
            FormatStyle::BWACS_MultiLine) {
375
      // If possible, merge the next line's wrapped left brace with the current
376
      // line. Otherwise, leave it on the next line, as this is a multi-line
377
      // control statement.
378
34
      return (Style.ColumnLimit == 0 ||
379
34
              TheLine->Last->TotalLength <= Style.ColumnLimit)
380
34
                 ? 
124
381
34
                 : 
010
;
382
40.2k
    } else if (I[1]->First->is(tok::l_brace) &&
383
40.2k
               TheLine->First->isOneOf(tok::kw_if, tok::kw_else, tok::kw_while,
384
1.37k
                                       tok::kw_for, TT_ForEachMacro)) {
385
259
      return (Style.BraceWrapping.AfterControlStatement ==
386
259
              FormatStyle::BWACS_Always)
387
259
                 ? tryMergeSimpleBlock(I, E, Limit)
388
259
                 : 
00
;
389
39.9k
    } else if (I[1]->First->is(tok::l_brace) &&
390
39.9k
               
TheLine->First->isOneOf(tok::kw_else, tok::kw_catch)1.12k
&&
391
39.9k
               Style.BraceWrapping.AfterControlStatement ==
392
10
                   FormatStyle::BWACS_MultiLine) {
393
      // This case if different from the upper BWACS_MultiLine processing
394
      // in that a preceding r_brace is not on the same line as else/catch
395
      // most likely because of BeforeElse/BeforeCatch set to true.
396
      // If the line length doesn't fit ColumnLimit, leave l_brace on the
397
      // next line to respect the BWACS_MultiLine.
398
1
      return (Style.ColumnLimit == 0 ||
399
1
              TheLine->Last->TotalLength <= Style.ColumnLimit)
400
1
                 ? 1
401
1
                 : 
00
;
402
1
    }
403
    // Don't merge block with left brace wrapped after ObjC special blocks
404
39.9k
    if (TheLine->First->is(tok::l_brace) && 
I != AnnotatedLines.begin()1.14k
&&
405
39.9k
        
I[-1]->First->is(tok::at)1.01k
&&
I[-1]->First->Next17
) {
406
17
      tok::ObjCKeywordKind kwId = I[-1]->First->Next->Tok.getObjCKeywordID();
407
17
      if (kwId == clang::tok::objc_autoreleasepool ||
408
17
          
kwId == clang::tok::objc_synchronized13
)
409
8
        return 0;
410
17
    }
411
    // Don't merge block with left brace wrapped after case labels
412
39.9k
    if (TheLine->First->is(tok::l_brace) && 
I != AnnotatedLines.begin()1.13k
&&
413
39.9k
        
I[-1]->First->isOneOf(tok::kw_case, tok::kw_default)1.00k
)
414
50
      return 0;
415
416
    // Don't merge an empty template class or struct if SplitEmptyRecords
417
    // is defined.
418
39.9k
    if (Style.BraceWrapping.SplitEmptyRecord &&
419
39.9k
        
TheLine->Last->is(tok::l_brace)39.3k
&&
I != AnnotatedLines.begin()5.80k
&&
420
39.9k
        
I[-1]->Last3.82k
) {
421
3.82k
      const FormatToken *Previous = I[-1]->Last;
422
3.82k
      if (Previous) {
423
3.82k
        if (Previous->is(tok::comment))
424
306
          Previous = Previous->getPreviousNonComment();
425
3.82k
        if (Previous) {
426
3.74k
          if (Previous->is(tok::greater) && 
!I[-1]->InPPDirective24
)
427
17
            return 0;
428
3.72k
          if (Previous->is(tok::identifier)) {
429
294
            const FormatToken *PreviousPrevious =
430
294
                Previous->getPreviousNonComment();
431
294
            if (PreviousPrevious &&
432
294
                
PreviousPrevious->isOneOf(tok::kw_class, tok::kw_struct)291
)
433
46
              return 0;
434
294
          }
435
3.72k
        }
436
3.82k
      }
437
3.82k
    }
438
439
    // Try to merge a block with left brace unwrapped that wasn't yet covered
440
39.8k
    if (TheLine->Last->is(tok::l_brace)) {
441
5.85k
      const FormatToken *Tok = TheLine->First;
442
5.85k
      bool ShouldMerge = false;
443
5.85k
      if (Tok->is(tok::kw_typedef)) {
444
18
        Tok = Tok->getNextNonComment();
445
18
        assert(Tok);
446
18
      }
447
5.85k
      if (Tok->isOneOf(tok::kw_class, tok::kw_struct)) {
448
1.79k
        ShouldMerge = !Style.BraceWrapping.AfterClass ||
449
1.79k
                      
(6
I[1]->First->is(tok::r_brace)6
&&
450
6
                       
!Style.BraceWrapping.SplitEmptyRecord0
);
451
4.06k
      } else if (Tok->is(tok::kw_enum)) {
452
31
        ShouldMerge = Style.AllowShortEnumsOnASingleLine;
453
4.03k
      } else {
454
4.03k
        ShouldMerge = !Style.BraceWrapping.AfterFunction ||
455
4.03k
                      
(847
I[1]->First->is(tok::r_brace)847
&&
456
847
                       
!Style.BraceWrapping.SplitEmptyFunction133
);
457
4.03k
      }
458
5.85k
      return ShouldMerge ? 
tryMergeSimpleBlock(I, E, Limit)4.98k
:
0870
;
459
5.85k
    }
460
    // Try to merge a function block with left brace wrapped
461
33.9k
    if (I[1]->First->is(TT_FunctionLBrace) &&
462
33.9k
        
Style.BraceWrapping.AfterFunction546
) {
463
544
      if (I[1]->Last->is(TT_LineComment))
464
6
        return 0;
465
466
      // Check for Limit <= 2 to account for the " {".
467
538
      if (Limit <= 2 || 
(464
Style.ColumnLimit == 0464
&&
containsMustBreak(TheLine)97
))
468
93
        return 0;
469
445
      Limit -= 2;
470
471
445
      unsigned MergedLines = 0;
472
445
      if (MergeShortFunctions ||
473
445
          
(242
Style.AllowShortFunctionsOnASingleLine >= FormatStyle::SFS_Empty242
&&
474
242
           
I[1]->First == I[1]->Last90
&&
I + 2 != E90
&&
475
242
           
I[2]->First->is(tok::r_brace)90
)) {
476
221
        MergedLines = tryMergeSimpleBlock(I + 1, E, Limit);
477
        // If we managed to merge the block, count the function header, which is
478
        // on a separate line.
479
221
        if (MergedLines > 0)
480
129
          ++MergedLines;
481
221
      }
482
445
      return MergedLines;
483
538
    }
484
33.4k
    auto IsElseLine = [&TheLine]() -> bool {
485
32.6k
      const FormatToken *First = TheLine->First;
486
32.6k
      if (First->is(tok::kw_else))
487
316
        return true;
488
489
32.3k
      return First->is(tok::r_brace) && 
First->Next6.19k
&&
490
32.3k
             
First->Next->is(tok::kw_else)1.85k
;
491
32.6k
    };
492
33.4k
    if (TheLine->First->is(tok::kw_if) ||
493
33.4k
        
(32.6k
IsElseLine()32.6k
&& (Style.AllowShortIfStatementsOnASingleLine ==
494
895
                          FormatStyle::SIS_AllIfsAndElse))) {
495
895
      return Style.AllowShortIfStatementsOnASingleLine
496
895
                 ? 
tryMergeSimpleControlStatement(I, E, Limit)536
497
895
                 : 
0359
;
498
895
    }
499
32.5k
    if (TheLine->First->isOneOf(tok::kw_for, tok::kw_while, tok::kw_do,
500
32.5k
                                TT_ForEachMacro)) {
501
427
      return Style.AllowShortLoopsOnASingleLine
502
427
                 ? 
tryMergeSimpleControlStatement(I, E, Limit)91
503
427
                 : 
0336
;
504
427
    }
505
32.1k
    if (TheLine->First->isOneOf(tok::kw_case, tok::kw_default)) {
506
343
      return Style.AllowShortCaseLabelsOnASingleLine
507
343
                 ? 
tryMergeShortCaseLabels(I, E, Limit)87
508
343
                 : 
0256
;
509
343
    }
510
31.7k
    if (TheLine->InPPDirective &&
511
31.7k
        
(1.09k
TheLine->First->HasUnescapedNewline1.09k
||
TheLine->First->IsFirst621
)) {
512
876
      return tryMergeSimplePPDirective(I, E, Limit);
513
876
    }
514
30.9k
    return 0;
515
31.7k
  }
516
517
  unsigned
518
  tryMergeSimplePPDirective(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
519
                            SmallVectorImpl<AnnotatedLine *>::const_iterator E,
520
876
                            unsigned Limit) {
521
876
    if (Limit == 0)
522
3
      return 0;
523
873
    if (I + 2 != E && I[2]->InPPDirective && 
!I[2]->First->HasUnescapedNewline388
)
524
157
      return 0;
525
716
    if (1 + I[1]->Last->TotalLength > Limit)
526
70
      return 0;
527
646
    return 1;
528
716
  }
529
530
  unsigned tryMergeSimpleControlStatement(
531
      SmallVectorImpl<AnnotatedLine *>::const_iterator I,
532
627
      SmallVectorImpl<AnnotatedLine *>::const_iterator E, unsigned Limit) {
533
627
    if (Limit == 0)
534
10
      return 0;
535
617
    if (Style.BraceWrapping.AfterControlStatement ==
536
617
            FormatStyle::BWACS_Always &&
537
617
        
I[1]->First->is(tok::l_brace)12
&&
538
617
        
Style.AllowShortBlocksOnASingleLine == FormatStyle::SBS_Never0
)
539
0
      return 0;
540
617
    if (I[1]->InPPDirective != (*I)->InPPDirective ||
541
617
        
(614
I[1]->InPPDirective614
&&
I[1]->First->HasUnescapedNewline21
))
542
3
      return 0;
543
614
    Limit = limitConsideringMacros(I + 1, E, Limit);
544
614
    AnnotatedLine &Line = **I;
545
614
    if (!Line.First->is(tok::kw_do) && 
!Line.First->is(tok::kw_else)605
&&
546
614
        
!Line.Last->is(tok::kw_else)515
&&
Line.Last->isNot(tok::r_paren)488
)
547
34
      return 0;
548
    // Only merge `do while` if `do` is the only statement on the line.
549
580
    if (Line.First->is(tok::kw_do) && 
!Line.Last->is(tok::kw_do)9
)
550
3
      return 0;
551
577
    if (1 + I[1]->Last->TotalLength > Limit)
552
15
      return 0;
553
    // Don't merge with loops, ifs, a single semicolon or a line comment.
554
562
    if (I[1]->First->isOneOf(tok::semi, tok::kw_if, tok::kw_for, tok::kw_while,
555
562
                             TT_ForEachMacro, TT_LineComment))
556
78
      return 0;
557
    // Only inline simple if's (no nested if or else), unless specified
558
484
    if (Style.AllowShortIfStatementsOnASingleLine ==
559
484
        FormatStyle::SIS_WithoutElse) {
560
151
      if (I + 2 != E && 
Line.startsWith(tok::kw_if)139
&&
561
151
          
I[2]->First->is(tok::kw_else)135
)
562
62
        return 0;
563
151
    }
564
422
    return 1;
565
484
  }
566
567
  unsigned
568
  tryMergeShortCaseLabels(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
569
                          SmallVectorImpl<AnnotatedLine *>::const_iterator E,
570
87
                          unsigned Limit) {
571
87
    if (Limit == 0 || I + 1 == E ||
572
87
        I[1]->First->isOneOf(tok::kw_case, tok::kw_default))
573
12
      return 0;
574
75
    if (I[0]->Last->is(tok::l_brace) || I[1]->First->is(tok::l_brace))
575
2
      return 0;
576
73
    unsigned NumStmts = 0;
577
73
    unsigned Length = 0;
578
73
    bool EndsWithComment = false;
579
73
    bool InPPDirective = I[0]->InPPDirective;
580
73
    const unsigned Level = I[0]->Level;
581
155
    for (; NumStmts < 3; 
++NumStmts82
) {
582
155
      if (I + 1 + NumStmts == E)
583
0
        break;
584
155
      const AnnotatedLine *Line = I[1 + NumStmts];
585
155
      if (Line->InPPDirective != InPPDirective)
586
4
        break;
587
151
      if (Line->First->isOneOf(tok::kw_case, tok::kw_default, tok::r_brace))
588
43
        break;
589
108
      if (Line->First->isOneOf(tok::kw_if, tok::kw_for, tok::kw_switch,
590
108
                               tok::kw_while) ||
591
108
          
EndsWithComment105
)
592
11
        return 0;
593
97
      if (Line->First->is(tok::comment)) {
594
15
        if (Level != Line->Level)
595
7
          return 0;
596
8
        SmallVectorImpl<AnnotatedLine *>::const_iterator J = I + 2 + NumStmts;
597
8
        for (; J != E; 
++J0
) {
598
8
          Line = *J;
599
8
          if (Line->InPPDirective != InPPDirective)
600
1
            break;
601
7
          if (Line->First->isOneOf(tok::kw_case, tok::kw_default, tok::r_brace))
602
7
            break;
603
0
          if (Line->First->isNot(tok::comment) || Level != Line->Level)
604
0
            return 0;
605
0
        }
606
8
        break;
607
8
      }
608
82
      if (Line->Last->is(tok::comment))
609
21
        EndsWithComment = true;
610
82
      Length += I[1 + NumStmts]->Last->TotalLength + 1; // 1 for the space.
611
82
    }
612
55
    if (NumStmts == 0 || NumStmts == 3 || Length > Limit)
613
7
      return 0;
614
48
    return NumStmts;
615
55
  }
616
617
  unsigned
618
  tryMergeSimpleBlock(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
619
                      SmallVectorImpl<AnnotatedLine *>::const_iterator E,
620
9.59k
                      unsigned Limit) {
621
9.59k
    AnnotatedLine &Line = **I;
622
623
    // Don't merge ObjC @ keywords and methods.
624
    // FIXME: If an option to allow short exception handling clauses on a single
625
    // line is added, change this to not return for @try and friends.
626
9.59k
    if (Style.Language != FormatStyle::LK_Java &&
627
9.59k
        
Line.First->isOneOf(tok::at, tok::minus, tok::plus)9.42k
)
628
153
      return 0;
629
630
    // Check that the current line allows merging. This depends on whether we
631
    // are in a control flow statements as well as several style flags.
632
9.43k
    if (Line.First->is(tok::kw_case) ||
633
9.43k
        
(9.36k
Line.First->Next9.36k
&&
Line.First->Next->is(tok::kw_else)8.69k
))
634
337
      return 0;
635
    // default: in switch statement
636
9.10k
    if (Line.First->is(tok::kw_default)) {
637
28
      const FormatToken *Tok = Line.First->getNextNonComment();
638
28
      if (Tok && Tok->is(tok::colon))
639
26
        return 0;
640
28
    }
641
9.07k
    if (Line.First->isOneOf(tok::kw_if, tok::kw_else, tok::kw_while, tok::kw_do,
642
9.07k
                            tok::kw_try, tok::kw___try, tok::kw_catch,
643
9.07k
                            tok::kw___finally, tok::kw_for, TT_ForEachMacro,
644
9.07k
                            tok::r_brace, Keywords.kw___except)) {
645
797
      if (Style.AllowShortBlocksOnASingleLine == FormatStyle::SBS_Never)
646
510
        return 0;
647
287
      if (Style.AllowShortBlocksOnASingleLine == FormatStyle::SBS_Empty &&
648
287
          
!I[1]->First->is(tok::r_brace)40
)
649
21
        return 0;
650
      // Don't merge when we can't except the case when
651
      // the control statement block is empty
652
266
      if (!Style.AllowShortIfStatementsOnASingleLine &&
653
266
          
Line.First->isOneOf(tok::kw_if, tok::kw_else)103
&&
654
266
          
!Style.BraceWrapping.AfterControlStatement48
&&
655
266
          
!I[1]->First->is(tok::r_brace)30
)
656
12
        return 0;
657
254
      if (!Style.AllowShortIfStatementsOnASingleLine &&
658
254
          
Line.First->isOneOf(tok::kw_if, tok::kw_else)91
&&
659
254
          Style.BraceWrapping.AfterControlStatement ==
660
36
              FormatStyle::BWACS_Always &&
661
254
          
I + 2 != E18
&&
!I[2]->First->is(tok::r_brace)18
)
662
12
        return 0;
663
242
      if (!Style.AllowShortLoopsOnASingleLine &&
664
242
          Line.First->isOneOf(tok::kw_while, tok::kw_do, tok::kw_for,
665
62
                              TT_ForEachMacro) &&
666
242
          
!Style.BraceWrapping.AfterControlStatement44
&&
667
242
          
!I[1]->First->is(tok::r_brace)26
)
668
15
        return 0;
669
227
      if (!Style.AllowShortLoopsOnASingleLine &&
670
227
          Line.First->isOneOf(tok::kw_while, tok::kw_do, tok::kw_for,
671
47
                              TT_ForEachMacro) &&
672
227
          Style.BraceWrapping.AfterControlStatement ==
673
29
              FormatStyle::BWACS_Always &&
674
227
          
I + 2 != E18
&&
!I[2]->First->is(tok::r_brace)18
)
675
9
        return 0;
676
      // FIXME: Consider an option to allow short exception handling clauses on
677
      // a single line.
678
      // FIXME: This isn't covered by tests.
679
      // FIXME: For catch, __except, __finally the first token on the line
680
      // is '}', so this isn't correct here.
681
218
      if (Line.First->isOneOf(tok::kw_try, tok::kw___try, tok::kw_catch,
682
218
                              Keywords.kw___except, tok::kw___finally))
683
0
        return 0;
684
218
    }
685
686
8.49k
    if (Line.Last->is(tok::l_brace)) {
687
8.39k
      FormatToken *Tok = I[1]->First;
688
8.39k
      if (Tok->is(tok::r_brace) && 
!Tok->MustBreakBefore2.80k
&&
689
8.39k
          
(2.80k
Tok->getNextNonComment() == nullptr2.80k
||
690
2.80k
           
Tok->getNextNonComment()->is(tok::semi)702
)) {
691
        // We merge empty blocks even if the line exceeds the column limit.
692
2.73k
        Tok->SpacesRequiredBefore = Style.SpaceInEmptyBlock ? 
116
:
02.72k
;
693
2.73k
        Tok->CanBreakBefore = true;
694
2.73k
        return 1;
695
5.65k
      } else if (Limit != 0 && 
!Line.startsWithNamespace()5.53k
&&
696
5.65k
                 
!startsExternCBlock(Line)4.40k
) {
697
        // We don't merge short records.
698
4.37k
        FormatToken *RecordTok = Line.First;
699
        // Skip record modifiers.
700
4.51k
        while (RecordTok->Next &&
701
4.51k
               RecordTok->isOneOf(tok::kw_typedef, tok::kw_export,
702
4.02k
                                  Keywords.kw_declare, Keywords.kw_abstract,
703
4.02k
                                  tok::kw_default, Keywords.kw_override,
704
4.02k
                                  tok::kw_public, tok::kw_private,
705
4.02k
                                  tok::kw_protected, Keywords.kw_internal))
706
141
          RecordTok = RecordTok->Next;
707
4.37k
        if (RecordTok &&
708
4.37k
            RecordTok->isOneOf(tok::kw_class, tok::kw_union, tok::kw_struct,
709
4.37k
                               Keywords.kw_interface))
710
1.42k
          return 0;
711
712
        // Check that we still have three lines and they fit into the limit.
713
2.94k
        if (I + 2 == E || 
I[2]->Type == LT_Invalid2.93k
)
714
13
          return 0;
715
2.93k
        Limit = limitConsideringMacros(I + 2, E, Limit);
716
717
2.93k
        if (!nextTwoLinesFitInto(I, Limit))
718
559
          return 0;
719
720
        // Second, check that the next line does not contain any braces - if it
721
        // does, readability declines when putting it into a single line.
722
2.37k
        if (I[1]->Last->is(TT_LineComment))
723
78
          return 0;
724
13.3k
        
do 2.29k
{
725
13.3k
          if (Tok->is(tok::l_brace) && 
Tok->isNot(BK_BracedInit)195
)
726
166
            return 0;
727
13.1k
          Tok = Tok->Next;
728
13.1k
        } while (Tok);
729
730
        // Last, check that the third line starts with a closing brace.
731
2.13k
        Tok = I[2]->First;
732
2.13k
        if (Tok->isNot(tok::r_brace))
733
758
          return 0;
734
735
        // Don't merge "if (a) { .. } else {".
736
1.37k
        if (Tok->Next && 
Tok->Next->is(tok::kw_else)166
)
737
13
          return 0;
738
739
        // Don't merge a trailing multi-line control statement block like:
740
        // } else if (foo &&
741
        //            bar)
742
        // { <-- current Line
743
        //   baz();
744
        // }
745
1.35k
        if (Line.First == Line.Last && 
Line.First->isNot(TT_FunctionLBrace)174
&&
746
1.35k
            Style.BraceWrapping.AfterControlStatement ==
747
108
                FormatStyle::BWACS_MultiLine)
748
8
          return 0;
749
750
1.35k
        return 2;
751
1.35k
      }
752
8.39k
    } else 
if (100
I[1]->First->is(tok::l_brace)100
) {
753
100
      if (I[1]->Last->is(TT_LineComment))
754
6
        return 0;
755
756
      // Check for Limit <= 2 to account for the " {".
757
94
      if (Limit <= 2 || (Style.ColumnLimit == 0 && 
containsMustBreak(*I)0
))
758
0
        return 0;
759
94
      Limit -= 2;
760
94
      unsigned MergedLines = 0;
761
94
      if (Style.AllowShortBlocksOnASingleLine != FormatStyle::SBS_Never ||
762
94
          
(0
I[1]->First == I[1]->Last0
&&
I + 2 != E0
&&
763
94
           
I[2]->First->is(tok::r_brace)0
)) {
764
94
        MergedLines = tryMergeSimpleBlock(I + 1, E, Limit);
765
        // If we managed to merge the block, count the statement header, which
766
        // is on a separate line.
767
94
        if (MergedLines > 0)
768
69
          ++MergedLines;
769
94
      }
770
94
      return MergedLines;
771
94
    }
772
1.28k
    return 0;
773
8.49k
  }
774
775
  /// Returns the modified column limit for \p I if it is inside a macro and
776
  /// needs a trailing '\'.
777
  unsigned
778
  limitConsideringMacros(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
779
                         SmallVectorImpl<AnnotatedLine *>::const_iterator E,
780
3.54k
                         unsigned Limit) {
781
3.54k
    if (I[0]->InPPDirective && 
I + 1 != E82
&&
782
3.54k
        
!I[1]->First->HasUnescapedNewline82
&&
!I[1]->First->is(tok::eof)63
) {
783
34
      return Limit < 2 ? 
00
: Limit - 2;
784
34
    }
785
3.51k
    return Limit;
786
3.54k
  }
787
788
  bool nextTwoLinesFitInto(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
789
2.93k
                           unsigned Limit) {
790
2.93k
    if (I[1]->First->MustBreakBefore || I[2]->First->MustBreakBefore)
791
52
      return false;
792
2.88k
    return 1 + I[1]->Last->TotalLength + 1 + I[2]->Last->TotalLength <= Limit;
793
2.93k
  }
794
795
97
  bool containsMustBreak(const AnnotatedLine *Line) {
796
522
    for (const FormatToken *Tok = Line->First; Tok; 
Tok = Tok->Next425
) {
797
444
      if (Tok->MustBreakBefore)
798
19
        return true;
799
444
    }
800
78
    return false;
801
97
  }
802
803
6.82k
  void join(AnnotatedLine &A, const AnnotatedLine &B) {
804
6.82k
    assert(!A.Last->Next);
805
0
    assert(!B.First->Previous);
806
6.82k
    if (B.Affected)
807
5.90k
      A.Affected = true;
808
6.82k
    A.Last->Next = B.First;
809
6.82k
    B.First->Previous = A.Last;
810
6.82k
    B.First->CanBreakBefore = true;
811
6.82k
    unsigned LengthA = A.Last->TotalLength + B.First->SpacesRequiredBefore;
812
24.6k
    for (FormatToken *Tok = B.First; Tok; 
Tok = Tok->Next17.8k
) {
813
17.8k
      Tok->TotalLength += LengthA;
814
17.8k
      A.Last = Tok;
815
17.8k
    }
816
6.82k
  }
817
818
  const FormatStyle &Style;
819
  const AdditionalKeywords &Keywords;
820
  const SmallVectorImpl<AnnotatedLine *>::const_iterator End;
821
822
  SmallVectorImpl<AnnotatedLine *>::const_iterator Next;
823
  const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines;
824
};
825
826
73.9k
static void markFinalized(FormatToken *Tok) {
827
426k
  for (; Tok; 
Tok = Tok->Next352k
) {
828
352k
    Tok->Finalized = true;
829
352k
    for (AnnotatedLine *Child : Tok->Children)
830
1.64k
      markFinalized(Child->First);
831
352k
  }
832
73.9k
}
833
834
#ifndef NDEBUG
835
0
static void printLineState(const LineState &State) {
836
0
  llvm::dbgs() << "State: ";
837
0
  for (const ParenState &P : State.Stack) {
838
0
    llvm::dbgs() << (P.Tok ? P.Tok->TokenText : "F") << "|" << P.Indent << "|"
839
0
                 << P.LastSpace << "|" << P.NestedBlockIndent << " ";
840
0
  }
841
0
  llvm::dbgs() << State.NextToken->TokenText << "\n";
842
0
}
843
#endif
844
845
/// Base class for classes that format one \c AnnotatedLine.
846
class LineFormatter {
847
public:
848
  LineFormatter(ContinuationIndenter *Indenter, WhitespaceManager *Whitespaces,
849
                const FormatStyle &Style,
850
                UnwrappedLineFormatter *BlockFormatter)
851
      : Indenter(Indenter), Whitespaces(Whitespaces), Style(Style),
852
68.8k
        BlockFormatter(BlockFormatter) {}
853
68.8k
  virtual ~LineFormatter() {}
854
855
  /// Formats an \c AnnotatedLine and returns the penalty.
856
  ///
857
  /// If \p DryRun is \c false, directly applies the changes.
858
  virtual unsigned formatLine(const AnnotatedLine &Line, unsigned FirstIndent,
859
                              unsigned FirstStartColumn, bool DryRun) = 0;
860
861
protected:
862
  /// If the \p State's next token is an r_brace closing a nested block,
863
  /// format the nested block before it.
864
  ///
865
  /// Returns \c true if all children could be placed successfully and adapts
866
  /// \p Penalty as well as \p State. If \p DryRun is false, also directly
867
  /// creates changes using \c Whitespaces.
868
  ///
869
  /// The crucial idea here is that children always get formatted upon
870
  /// encountering the closing brace right after the nested block. Now, if we
871
  /// are currently trying to keep the "}" on the same line (i.e. \p NewLine is
872
  /// \c false), the entire block has to be kept on the same line (which is only
873
  /// possible if it fits on the line, only contains a single statement, etc.
874
  ///
875
  /// If \p NewLine is true, we format the nested block on separate lines, i.e.
876
  /// break after the "{", format all lines with correct indentation and the put
877
  /// the closing "}" on yet another new line.
878
  ///
879
  /// This enables us to keep the simple structure of the
880
  /// \c UnwrappedLineFormatter, where we only have two options for each token:
881
  /// break or don't break.
882
  bool formatChildren(LineState &State, bool NewLine, bool DryRun,
883
1.04M
                      unsigned &Penalty) {
884
1.04M
    const FormatToken *LBrace = State.NextToken->getPreviousNonComment();
885
1.04M
    FormatToken &Previous = *State.NextToken->Previous;
886
1.04M
    if (!LBrace || 
LBrace->isNot(tok::l_brace)1.04M
||
LBrace->isNot(BK_Block)26.0k
||
887
1.04M
        
Previous.Children.size() == 010.0k
)
888
      // The previous token does not open a block. Nothing to do. We don't
889
      // assert so that we can simply call this function for all tokens.
890
1.04M
      return true;
891
892
3.59k
    if (NewLine) {
893
2.35k
      const ParenState &P = State.Stack.back();
894
895
2.35k
      int AdditionalIndent =
896
2.35k
          P.Indent - Previous.Children[0]->Level * Style.IndentWidth;
897
898
2.35k
      if (Style.LambdaBodyIndentation == FormatStyle::LBI_OuterScope &&
899
2.35k
          
P.NestedBlockIndent == P.LastSpace76
) {
900
19
        if (State.NextToken->MatchingParen &&
901
19
            State.NextToken->MatchingParen->is(TT_LambdaLBrace)) {
902
19
          State.Stack.pop_back();
903
19
        }
904
19
        if (LBrace->is(TT_LambdaLBrace))
905
19
          AdditionalIndent = 0;
906
19
      }
907
908
2.35k
      Penalty +=
909
2.35k
          BlockFormatter->format(Previous.Children, DryRun, AdditionalIndent,
910
2.35k
                                 /*FixBadIndentation=*/true);
911
2.35k
      return true;
912
2.35k
    }
913
914
1.24k
    if (Previous.Children[0]->First->MustBreakBefore)
915
1
      return false;
916
917
    // Cannot merge into one line if this line ends on a comment.
918
1.24k
    if (Previous.is(tok::comment))
919
0
      return false;
920
921
    // Cannot merge multiple statements into a single line.
922
1.24k
    if (Previous.Children.size() > 1)
923
380
      return false;
924
925
863
    const AnnotatedLine *Child = Previous.Children[0];
926
    // We can't put the closing "}" on a line with a trailing comment.
927
863
    if (Child->Last->isTrailingComment())
928
135
      return false;
929
930
    // If the child line exceeds the column limit, we wouldn't want to merge it.
931
    // We add +2 for the trailing " }".
932
728
    if (Style.ColumnLimit > 0 &&
933
728
        
Child->Last->TotalLength + State.Column + 2 > Style.ColumnLimit727
)
934
127
      return false;
935
936
601
    if (!DryRun) {
937
455
      Whitespaces->replaceWhitespace(
938
455
          *Child->First, /*Newlines=*/0, /*Spaces=*/1,
939
455
          /*StartOfTokenColumn=*/State.Column, /*IsAligned=*/false,
940
455
          State.Line->InPPDirective);
941
455
    }
942
601
    Penalty +=
943
601
        formatLine(*Child, State.Column + 1, /*FirstStartColumn=*/0, DryRun);
944
945
601
    State.Column += 1 + Child->Last->TotalLength;
946
601
    return true;
947
728
  }
948
949
  ContinuationIndenter *Indenter;
950
951
private:
952
  WhitespaceManager *Whitespaces;
953
  const FormatStyle &Style;
954
  UnwrappedLineFormatter *BlockFormatter;
955
};
956
957
/// Formatter that keeps the existing line breaks.
958
class NoColumnLimitLineFormatter : public LineFormatter {
959
public:
960
  NoColumnLimitLineFormatter(ContinuationIndenter *Indenter,
961
                             WhitespaceManager *Whitespaces,
962
                             const FormatStyle &Style,
963
                             UnwrappedLineFormatter *BlockFormatter)
964
1.76k
      : LineFormatter(Indenter, Whitespaces, Style, BlockFormatter) {}
965
966
  /// Formats the line, simply keeping all of the input's line breaking
967
  /// decisions.
968
  unsigned formatLine(const AnnotatedLine &Line, unsigned FirstIndent,
969
1.76k
                      unsigned FirstStartColumn, bool DryRun) override {
970
1.76k
    assert(!DryRun);
971
0
    LineState State = Indenter->getInitialState(FirstIndent, FirstStartColumn,
972
1.76k
                                                &Line, /*DryRun=*/false);
973
6.02k
    while (State.NextToken) {
974
4.26k
      bool Newline =
975
4.26k
          Indenter->mustBreak(State) ||
976
4.26k
          
(3.91k
Indenter->canBreak(State)3.91k
&&
State.NextToken->NewlinesBefore > 01.10k
);
977
4.26k
      unsigned Penalty = 0;
978
4.26k
      formatChildren(State, Newline, /*DryRun=*/false, Penalty);
979
4.26k
      Indenter->addTokenToState(State, Newline, /*DryRun=*/false);
980
4.26k
    }
981
1.76k
    return 0;
982
1.76k
  }
983
};
984
985
/// Formatter that puts all tokens into a single line without breaks.
986
class NoLineBreakFormatter : public LineFormatter {
987
public:
988
  NoLineBreakFormatter(ContinuationIndenter *Indenter,
989
                       WhitespaceManager *Whitespaces, const FormatStyle &Style,
990
                       UnwrappedLineFormatter *BlockFormatter)
991
60.8k
      : LineFormatter(Indenter, Whitespaces, Style, BlockFormatter) {}
992
993
  /// Puts all tokens into a single line.
994
  unsigned formatLine(const AnnotatedLine &Line, unsigned FirstIndent,
995
61.2k
                      unsigned FirstStartColumn, bool DryRun) override {
996
61.2k
    unsigned Penalty = 0;
997
61.2k
    LineState State =
998
61.2k
        Indenter->getInitialState(FirstIndent, FirstStartColumn, &Line, DryRun);
999
234k
    while (State.NextToken) {
1000
173k
      formatChildren(State, /*NewLine=*/false, DryRun, Penalty);
1001
173k
      Indenter->addTokenToState(
1002
173k
          State, /*Newline=*/State.NextToken->MustBreakBefore, DryRun);
1003
173k
    }
1004
61.2k
    return Penalty;
1005
61.2k
  }
1006
};
1007
1008
/// Finds the best way to break lines.
1009
class OptimizingLineFormatter : public LineFormatter {
1010
public:
1011
  OptimizingLineFormatter(ContinuationIndenter *Indenter,
1012
                          WhitespaceManager *Whitespaces,
1013
                          const FormatStyle &Style,
1014
                          UnwrappedLineFormatter *BlockFormatter)
1015
6.22k
      : LineFormatter(Indenter, Whitespaces, Style, BlockFormatter) {}
1016
1017
  /// Formats the line by finding the best line breaks with line lengths
1018
  /// below the column limit.
1019
  unsigned formatLine(const AnnotatedLine &Line, unsigned FirstIndent,
1020
6.42k
                      unsigned FirstStartColumn, bool DryRun) override {
1021
6.42k
    LineState State =
1022
6.42k
        Indenter->getInitialState(FirstIndent, FirstStartColumn, &Line, DryRun);
1023
1024
    // If the ObjC method declaration does not fit on a line, we should format
1025
    // it with one arg per line.
1026
6.42k
    if (State.Line->Type == LT_ObjCMethodDecl)
1027
42
      State.Stack.back().BreakBeforeParameter = true;
1028
1029
    // Find best solution in solution space.
1030
6.42k
    return analyzeSolutionSpace(State, DryRun);
1031
6.42k
  }
1032
1033
private:
1034
  struct CompareLineStatePointers {
1035
14.4M
    bool operator()(LineState *obj1, LineState *obj2) const {
1036
14.4M
      return *obj1 < *obj2;
1037
14.4M
    }
1038
  };
1039
1040
  /// A pair of <penalty, count> that is used to prioritize the BFS on.
1041
  ///
1042
  /// In case of equal penalties, we want to prefer states that were inserted
1043
  /// first. During state generation we make sure that we insert states first
1044
  /// that break the line as late as possible.
1045
  typedef std::pair<unsigned, unsigned> OrderedPenalty;
1046
1047
  /// An edge in the solution space from \c Previous->State to \c State,
1048
  /// inserting a newline dependent on the \c NewLine.
1049
  struct StateNode {
1050
    StateNode(const LineState &State, bool NewLine, StateNode *Previous)
1051
795k
        : State(State), NewLine(NewLine), Previous(Previous) {}
1052
    LineState State;
1053
    bool NewLine;
1054
    StateNode *Previous;
1055
  };
1056
1057
  /// An item in the prioritized BFS search queue. The \c StateNode's
1058
  /// \c State has the given \c OrderedPenalty.
1059
  typedef std::pair<OrderedPenalty, StateNode *> QueueItem;
1060
1061
  /// The BFS queue type.
1062
  typedef std::priority_queue<QueueItem, std::vector<QueueItem>,
1063
                              std::greater<QueueItem>>
1064
      QueueType;
1065
1066
  /// Analyze the entire solution space starting from \p InitialState.
1067
  ///
1068
  /// This implements a variant of Dijkstra's algorithm on the graph that spans
1069
  /// the solution space (\c LineStates are the nodes). The algorithm tries to
1070
  /// find the shortest path (the one with lowest penalty) from \p InitialState
1071
  /// to a state where all tokens are placed. Returns the penalty.
1072
  ///
1073
  /// If \p DryRun is \c false, directly applies the changes.
1074
6.42k
  unsigned analyzeSolutionSpace(LineState &InitialState, bool DryRun) {
1075
6.42k
    std::set<LineState *, CompareLineStatePointers> Seen;
1076
1077
    // Increasing count of \c StateNode items we have created. This is used to
1078
    // create a deterministic order independent of the container.
1079
6.42k
    unsigned Count = 0;
1080
6.42k
    QueueType Queue;
1081
1082
    // Insert start element into queue.
1083
6.42k
    StateNode *RootNode =
1084
6.42k
        new (Allocator.Allocate()) StateNode(InitialState, false, nullptr);
1085
6.42k
    Queue.push(QueueItem(OrderedPenalty(0, Count), RootNode));
1086
6.42k
    ++Count;
1087
1088
6.42k
    unsigned Penalty = 0;
1089
1090
    // While not empty, take first element and follow edges.
1091
722k
    while (!Queue.empty()) {
1092
722k
      Penalty = Queue.top().first.first;
1093
722k
      StateNode *Node = Queue.top().second;
1094
722k
      if (!Node->State.NextToken) {
1095
6.42k
        LLVM_DEBUG(llvm::dbgs()
1096
6.42k
                   << "\n---\nPenalty for line: " << Penalty << "\n");
1097
6.42k
        break;
1098
6.42k
      }
1099
715k
      Queue.pop();
1100
1101
      // Cut off the analysis of certain solutions if the analysis gets too
1102
      // complex. See description of IgnoreStackForComparison.
1103
715k
      if (Count > 50000)
1104
134k
        Node->State.IgnoreStackForComparison = true;
1105
1106
715k
      if (!Seen.insert(&Node->State).second)
1107
        // State already examined with lower penalty.
1108
135k
        continue;
1109
1110
579k
      FormatDecision LastFormat = Node->State.NextToken->getDecision();
1111
579k
      if (LastFormat == FD_Unformatted || 
LastFormat == FD_Continue594
)
1112
579k
        addNextStateToQueue(Penalty, Node, /*NewLine=*/false, &Count, &Queue);
1113
579k
      if (LastFormat == FD_Unformatted || 
LastFormat == FD_Break594
)
1114
579k
        addNextStateToQueue(Penalty, Node, /*NewLine=*/true, &Count, &Queue);
1115
579k
    }
1116
1117
6.42k
    if (Queue.empty()) {
1118
      // We were unable to find a solution, do nothing.
1119
      // FIXME: Add diagnostic?
1120
0
      LLVM_DEBUG(llvm::dbgs() << "Could not find a solution.\n");
1121
0
      return 0;
1122
0
    }
1123
1124
    // Reconstruct the solution.
1125
6.42k
    if (!DryRun)
1126
6.18k
      reconstructPath(InitialState, Queue.top().second);
1127
1128
6.42k
    LLVM_DEBUG(llvm::dbgs()
1129
6.42k
               << "Total number of analyzed states: " << Count << "\n");
1130
6.42k
    LLVM_DEBUG(llvm::dbgs() << "---\n");
1131
1132
6.42k
    return Penalty;
1133
6.42k
  }
1134
1135
  /// Add the following state to the analysis queue \c Queue.
1136
  ///
1137
  /// Assume the current state is \p PreviousNode and has been reached with a
1138
  /// penalty of \p Penalty. Insert a line break if \p NewLine is \c true.
1139
  void addNextStateToQueue(unsigned Penalty, StateNode *PreviousNode,
1140
1.15M
                           bool NewLine, unsigned *Count, QueueType *Queue) {
1141
1.15M
    if (NewLine && 
!Indenter->canBreak(PreviousNode->State)579k
)
1142
333k
      return;
1143
825k
    if (!NewLine && 
Indenter->mustBreak(PreviousNode->State)579k
)
1144
36.3k
      return;
1145
1146
789k
    StateNode *Node = new (Allocator.Allocate())
1147
789k
        StateNode(PreviousNode->State, NewLine, PreviousNode);
1148
789k
    if (!formatChildren(Node->State, NewLine, /*DryRun=*/true, Penalty))
1149
643
      return;
1150
1151
788k
    Penalty += Indenter->addTokenToState(Node->State, NewLine, true);
1152
1153
788k
    Queue->push(QueueItem(OrderedPenalty(Penalty, *Count), Node));
1154
788k
    ++(*Count);
1155
788k
  }
1156
1157
  /// Applies the best formatting by reconstructing the path in the
1158
  /// solution space that leads to \c Best.
1159
6.18k
  void reconstructPath(LineState &State, StateNode *Best) {
1160
6.18k
    llvm::SmallVector<StateNode *> Path;
1161
    // We do not need a break before the initial token.
1162
86.3k
    while (Best->Previous) {
1163
80.1k
      Path.push_back(Best);
1164
80.1k
      Best = Best->Previous;
1165
80.1k
    }
1166
80.1k
    for (const auto &Node : llvm::reverse(Path)) {
1167
80.1k
      unsigned Penalty = 0;
1168
80.1k
      formatChildren(State, Node->NewLine, /*DryRun=*/false, Penalty);
1169
80.1k
      Penalty += Indenter->addTokenToState(State, Node->NewLine, false);
1170
1171
80.1k
      LLVM_DEBUG({
1172
80.1k
        printLineState(Node->Previous->State);
1173
80.1k
        if (Node->NewLine) {
1174
80.1k
          llvm::dbgs() << "Penalty for placing "
1175
80.1k
                       << Node->Previous->State.NextToken->Tok.getName()
1176
80.1k
                       << " on a new line: " << Penalty << "\n";
1177
80.1k
        }
1178
80.1k
      });
1179
80.1k
    }
1180
6.18k
  }
1181
1182
  llvm::SpecificBumpPtrAllocator<StateNode> Allocator;
1183
};
1184
1185
} // anonymous namespace
1186
1187
unsigned UnwrappedLineFormatter::format(
1188
    const SmallVectorImpl<AnnotatedLine *> &Lines, bool DryRun,
1189
    int AdditionalIndent, bool FixBadIndentation, unsigned FirstStartColumn,
1190
23.2k
    unsigned NextStartColumn, unsigned LastStartColumn) {
1191
23.2k
  LineJoiner Joiner(Style, Keywords, Lines);
1192
1193
  // Try to look up already computed penalty in DryRun-mode.
1194
23.2k
  std::pair<const SmallVectorImpl<AnnotatedLine *> *, unsigned> CacheKey(
1195
23.2k
      &Lines, AdditionalIndent);
1196
23.2k
  auto CacheIt = PenaltyCache.find(CacheKey);
1197
23.2k
  if (DryRun && 
CacheIt != PenaltyCache.end()1.70k
)
1198
584
    return CacheIt->second;
1199
1200
22.6k
  assert(!Lines.empty());
1201
0
  unsigned Penalty = 0;
1202
22.6k
  LevelIndentTracker IndentTracker(Style, Keywords, Lines[0]->Level,
1203
22.6k
                                   AdditionalIndent);
1204
22.6k
  const AnnotatedLine *PrevPrevLine = nullptr;
1205
22.6k
  const AnnotatedLine *PreviousLine = nullptr;
1206
22.6k
  const AnnotatedLine *NextLine = nullptr;
1207
1208
  // The minimum level of consecutive lines that have been formatted.
1209
22.6k
  unsigned RangeMinLevel = UINT_MAX;
1210
1211
22.6k
  bool FirstLine = true;
1212
22.6k
  for (const AnnotatedLine *Line =
1213
22.6k
           Joiner.getNextMergedLine(DryRun, IndentTracker);
1214
96.9k
       Line; PrevPrevLine = PreviousLine, PreviousLine = Line, Line = NextLine,
1215
74.2k
                           FirstLine = false) {
1216
74.2k
    const AnnotatedLine &TheLine = *Line;
1217
74.2k
    unsigned Indent = IndentTracker.getIndent();
1218
1219
    // We continue formatting unchanged lines to adjust their indent, e.g. if a
1220
    // scope was added. However, we need to carefully stop doing this when we
1221
    // exit the scope of affected lines to prevent indenting a the entire
1222
    // remaining file if it currently missing a closing brace.
1223
74.2k
    bool PreviousRBrace =
1224
74.2k
        PreviousLine && 
PreviousLine->startsWith(tok::r_brace)51.6k
;
1225
74.2k
    bool ContinueFormatting =
1226
74.2k
        TheLine.Level > RangeMinLevel ||
1227
74.2k
        
(63.2k
TheLine.Level == RangeMinLevel63.2k
&&
!PreviousRBrace35.4k
&&
1228
63.2k
         
!TheLine.startsWith(tok::r_brace)29.8k
);
1229
1230
74.2k
    bool FixIndentation = (FixBadIndentation || 
ContinueFormatting71.1k
) &&
1231
74.2k
                          
Indent != TheLine.First->OriginalColumn37.8k
;
1232
74.2k
    bool ShouldFormat = TheLine.Affected || 
FixIndentation5.80k
;
1233
    // We cannot format this line; if the reason is that the line had a
1234
    // parsing error, remember that.
1235
74.2k
    if (ShouldFormat && 
TheLine.Type == LT_Invalid68.8k
&&
Status25
) {
1236
19
      Status->FormatComplete = false;
1237
19
      Status->Line =
1238
19
          SourceMgr.getSpellingLineNumber(TheLine.First->Tok.getLocation());
1239
19
    }
1240
1241
74.2k
    if (ShouldFormat && 
TheLine.Type != LT_Invalid68.8k
) {
1242
68.8k
      if (!DryRun) {
1243
66.8k
        bool LastLine = Line->First->is(tok::eof);
1244
66.8k
        formatFirstToken(TheLine, PreviousLine, PrevPrevLine, Lines, Indent,
1245
66.8k
                         LastLine ? 
LastStartColumn20.5k
:
NextStartColumn + Indent46.3k
);
1246
66.8k
      }
1247
1248
68.8k
      NextLine = Joiner.getNextMergedLine(DryRun, IndentTracker);
1249
68.8k
      unsigned ColumnLimit = getColumnLimit(TheLine.InPPDirective, NextLine);
1250
68.8k
      bool FitsIntoOneLine =
1251
68.8k
          TheLine.Last->TotalLength + Indent <= ColumnLimit ||
1252
68.8k
          
(7.75k
TheLine.Type == LT_ImportStatement7.75k
&&
1253
7.75k
           
(64
!Style.isJavaScript()64
||
!Style.JavaScriptWrapImports26
)) ||
1254
68.8k
          
(7.70k
Style.isCSharp()7.70k
&&
1255
7.70k
           
TheLine.InPPDirective94
); // don't split #regions in C#
1256
68.8k
      if (Style.ColumnLimit == 0)
1257
1.76k
        NoColumnLimitLineFormatter(Indenter, Whitespaces, Style, this)
1258
1.76k
            .formatLine(TheLine, NextStartColumn + Indent,
1259
1.76k
                        FirstLine ? 
FirstStartColumn325
:
01.44k
, DryRun);
1260
67.0k
      else if (FitsIntoOneLine)
1261
60.8k
        Penalty += NoLineBreakFormatter(Indenter, Whitespaces, Style, this)
1262
60.8k
                       .formatLine(TheLine, NextStartColumn + Indent,
1263
60.8k
                                   FirstLine ? 
FirstStartColumn16.7k
:
044.0k
, DryRun);
1264
6.22k
      else
1265
6.22k
        Penalty += OptimizingLineFormatter(Indenter, Whitespaces, Style, this)
1266
6.22k
                       .formatLine(TheLine, NextStartColumn + Indent,
1267
6.22k
                                   FirstLine ? 
FirstStartColumn4.99k
:
01.22k
, DryRun);
1268
68.8k
      RangeMinLevel = std::min(RangeMinLevel, TheLine.Level);
1269
68.8k
    } else {
1270
      // If no token in the current line is affected, we still need to format
1271
      // affected children.
1272
5.42k
      if (TheLine.ChildrenAffected)
1273
93
        
for (const FormatToken *Tok = TheLine.First; 11
Tok;
Tok = Tok->Next82
)
1274
82
          if (!Tok->Children.empty())
1275
12
            format(Tok->Children, DryRun);
1276
1277
      // Adapt following lines on the current indent level to the same level
1278
      // unless the current \c AnnotatedLine is not at the beginning of a line.
1279
5.42k
      bool StartsNewLine =
1280
5.42k
          TheLine.First->NewlinesBefore > 0 || 
TheLine.First->IsFirst544
;
1281
5.42k
      if (StartsNewLine)
1282
5.19k
        IndentTracker.adjustToUnmodifiedLine(TheLine);
1283
5.42k
      if (!DryRun) {
1284
5.42k
        bool ReformatLeadingWhitespace =
1285
5.42k
            StartsNewLine && 
(5.18k
(5.18k
PreviousLine5.18k
&&
PreviousLine->Affected4.65k
) ||
1286
5.18k
                              
TheLine.LeadingEmptyLinesAffected4.75k
);
1287
        // Format the first token.
1288
5.42k
        if (ReformatLeadingWhitespace)
1289
447
          formatFirstToken(TheLine, PreviousLine, PrevPrevLine, Lines,
1290
447
                           TheLine.First->OriginalColumn,
1291
447
                           TheLine.First->OriginalColumn);
1292
4.97k
        else
1293
4.97k
          Whitespaces->addUntouchableToken(*TheLine.First,
1294
4.97k
                                           TheLine.InPPDirective);
1295
1296
        // Notify the WhitespaceManager about the unchanged whitespace.
1297
24.5k
        for (FormatToken *Tok = TheLine.First->Next; Tok; 
Tok = Tok->Next19.1k
)
1298
19.1k
          Whitespaces->addUntouchableToken(*Tok, TheLine.InPPDirective);
1299
5.42k
      }
1300
5.42k
      NextLine = Joiner.getNextMergedLine(DryRun, IndentTracker);
1301
5.42k
      RangeMinLevel = UINT_MAX;
1302
5.42k
    }
1303
74.2k
    if (!DryRun)
1304
72.3k
      markFinalized(TheLine.First);
1305
74.2k
  }
1306
22.6k
  PenaltyCache[CacheKey] = Penalty;
1307
22.6k
  return Penalty;
1308
23.2k
}
1309
1310
void UnwrappedLineFormatter::formatFirstToken(
1311
    const AnnotatedLine &Line, const AnnotatedLine *PreviousLine,
1312
    const AnnotatedLine *PrevPrevLine,
1313
    const SmallVectorImpl<AnnotatedLine *> &Lines, unsigned Indent,
1314
67.3k
    unsigned NewlineIndent) {
1315
67.3k
  FormatToken &RootToken = *Line.First;
1316
67.3k
  if (RootToken.is(tok::eof)) {
1317
20.5k
    unsigned Newlines = std::min(RootToken.NewlinesBefore, 1u);
1318
20.5k
    unsigned TokenIndent = Newlines ? 
NewlineIndent1.66k
:
018.8k
;
1319
20.5k
    Whitespaces->replaceWhitespace(RootToken, Newlines, TokenIndent,
1320
20.5k
                                   TokenIndent);
1321
20.5k
    return;
1322
20.5k
  }
1323
46.7k
  unsigned Newlines =
1324
46.7k
      std::min(RootToken.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1);
1325
  // Remove empty lines before "}" where applicable.
1326
46.7k
  if (RootToken.is(tok::r_brace) &&
1327
46.7k
      
(6.62k
!RootToken.Next6.62k
||
1328
6.62k
       
(2.31k
RootToken.Next->is(tok::semi)2.31k
&&
!RootToken.Next->Next1.02k
)) &&
1329
      // Do not remove empty lines before namespace closing "}".
1330
46.7k
      
!getNamespaceToken(&Line, Lines)5.33k
)
1331
5.15k
    Newlines = std::min(Newlines, 1u);
1332
  // Remove empty lines at the start of nested blocks (lambdas/arrow functions)
1333
46.7k
  if (PreviousLine == nullptr && 
Line.Level > 020.9k
)
1334
633
    Newlines = std::min(Newlines, 1u);
1335
46.7k
  if (Newlines == 0 && 
!RootToken.IsFirst30.9k
)
1336
10.9k
    Newlines = 1;
1337
46.7k
  if (RootToken.IsFirst && 
!RootToken.HasUnescapedNewline20.3k
)
1338
20.0k
    Newlines = 0;
1339
1340
  // Remove empty lines after "{".
1341
46.7k
  if (!Style.KeepEmptyLinesAtTheStartOfBlocks && 
PreviousLine6.19k
&&
1342
46.7k
      
PreviousLine->Last->is(tok::l_brace)2.45k
&&
1343
46.7k
      
!PreviousLine->startsWithNamespace()704
&&
1344
46.7k
      
!(697
PrevPrevLine697
&&
PrevPrevLine->startsWithNamespace()259
&&
1345
697
        
PreviousLine->startsWith(tok::l_brace)9
) &&
1346
46.7k
      
!startsExternCBlock(*PreviousLine)688
)
1347
681
    Newlines = 1;
1348
1349
  // Insert or remove empty line before access specifiers.
1350
46.7k
  if (PreviousLine && 
RootToken.isAccessSpecifier()25.8k
) {
1351
513
    switch (Style.EmptyLineBeforeAccessModifier) {
1352
64
    case FormatStyle::ELBAMS_Never:
1353
64
      if (Newlines > 1)
1354
13
        Newlines = 1;
1355
64
      break;
1356
38
    case FormatStyle::ELBAMS_Leave:
1357
38
      Newlines = std::max(RootToken.NewlinesBefore, 1u);
1358
38
      break;
1359
359
    case FormatStyle::ELBAMS_LogicalBlock:
1360
359
      if (PreviousLine->Last->isOneOf(tok::semi, tok::r_brace) && 
Newlines <= 198
)
1361
47
        Newlines = 2;
1362
359
      if (PreviousLine->First->isAccessSpecifier())
1363
44
        Newlines = 1; // Previous is an access modifier remove all new lines.
1364
359
      break;
1365
52
    case FormatStyle::ELBAMS_Always: {
1366
52
      const FormatToken *previousToken;
1367
52
      if (PreviousLine->Last->is(tok::comment))
1368
6
        previousToken = PreviousLine->Last->getPreviousNonComment();
1369
46
      else
1370
46
        previousToken = PreviousLine->Last;
1371
52
      if ((!previousToken || 
!previousToken->is(tok::l_brace)49
) &&
Newlines <= 135
)
1372
24
        Newlines = 2;
1373
52
    } break;
1374
513
    }
1375
513
  }
1376
1377
  // Insert or remove empty line after access specifiers.
1378
46.7k
  if (PreviousLine && 
PreviousLine->First->isAccessSpecifier()25.8k
&&
1379
46.7k
      
(515
!PreviousLine->InPPDirective515
||
!RootToken.HasUnescapedNewline5
)) {
1380
    // EmptyLineBeforeAccessModifier is handling the case when two access
1381
    // modifiers follow each other.
1382
515
    if (!RootToken.isAccessSpecifier()) {
1383
446
      switch (Style.EmptyLineAfterAccessModifier) {
1384
366
      case FormatStyle::ELAAMS_Never:
1385
366
        Newlines = 1;
1386
366
        break;
1387
34
      case FormatStyle::ELAAMS_Leave:
1388
34
        Newlines = std::max(Newlines, 1u);
1389
34
        break;
1390
46
      case FormatStyle::ELAAMS_Always:
1391
46
        if (RootToken.is(tok::r_brace)) // Do not add at end of class.
1392
10
          Newlines = 1u;
1393
36
        else
1394
36
          Newlines = std::max(Newlines, 2u);
1395
46
        break;
1396
446
      }
1397
446
    }
1398
515
  }
1399
1400
46.7k
  if (Newlines)
1401
26.7k
    Indent = NewlineIndent;
1402
1403
  // Preprocessor directives get indented before the hash only if specified
1404
46.7k
  if (Style.IndentPPDirectives != FormatStyle::PPDIS_BeforeHash &&
1405
46.7k
      
(46.6k
Line.Type == LT_PreprocessorDirective46.6k
||
1406
46.6k
       
Line.Type == LT_ImportStatement44.2k
))
1407
3.60k
    Indent = 0;
1408
1409
46.7k
  Whitespaces->replaceWhitespace(RootToken, Newlines, Indent, Indent,
1410
46.7k
                                 /*IsAligned=*/false,
1411
46.7k
                                 Line.InPPDirective &&
1412
46.7k
                                     
!RootToken.HasUnescapedNewline3.98k
);
1413
46.7k
}
1414
1415
unsigned
1416
UnwrappedLineFormatter::getColumnLimit(bool InPPDirective,
1417
68.8k
                                       const AnnotatedLine *NextLine) const {
1418
  // In preprocessor directives reserve two chars for trailing " \" if the
1419
  // next line continues the preprocessor directive.
1420
68.8k
  bool ContinuesPPDirective =
1421
68.8k
      InPPDirective &&
1422
      // If there is no next line, this is likely a child line and the parent
1423
      // continues the preprocessor directive.
1424
68.8k
      
(3.99k
!NextLine3.99k
||
1425
3.99k
       
(3.97k
NextLine->InPPDirective3.97k
&&
1426
        // If there is an unescaped newline between this line and the next, the
1427
        // next line starts a new preprocessor directive.
1428
3.97k
        
!NextLine->First->HasUnescapedNewline2.00k
));
1429
68.8k
  return Style.ColumnLimit - (ContinuesPPDirective ? 
2540
:
068.2k
);
1430
68.8k
}
1431
1432
} // namespace format
1433
} // namespace clang