Coverage Report

Created: 2024-01-17 10:31

/src/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 "FormatToken.h"
11
#include "NamespaceEndCommentsFixer.h"
12
#include "WhitespaceManager.h"
13
#include "llvm/Support/Debug.h"
14
#include <queue>
15
16
#define DEBUG_TYPE "format-formatter"
17
18
namespace clang {
19
namespace format {
20
21
namespace {
22
23
102k
bool startsExternCBlock(const AnnotatedLine &Line) {
24
102k
  const FormatToken *Next = Line.First->getNextNonComment();
25
102k
  const FormatToken *NextNext = Next ? Next->getNextNonComment() : nullptr;
26
102k
  return Line.startsWith(tok::kw_extern) && Next && Next->isStringLiteral() &&
27
102k
         NextNext && NextNext->is(tok::l_brace);
28
102k
}
29
30
20.0k
bool isRecordLBrace(const FormatToken &Tok) {
31
20.0k
  return Tok.isOneOf(TT_ClassLBrace, TT_EnumLBrace, TT_RecordLBrace,
32
20.0k
                     TT_StructLBrace, TT_UnionLBrace);
33
20.0k
}
34
35
/// Tracks the indent level of \c AnnotatedLines across levels.
36
///
37
/// \c nextLine must be called for each \c AnnotatedLine, after which \c
38
/// getIndent() will return the indent for the last line \c nextLine was called
39
/// with.
40
/// If the line is not formatted (and thus the indent does not change), calling
41
/// \c adjustToUnmodifiedLine after the call to \c nextLine will cause
42
/// subsequent lines on the same level to be indented at the same level as the
43
/// given line.
44
class LevelIndentTracker {
45
public:
46
  LevelIndentTracker(const FormatStyle &Style,
47
                     const AdditionalKeywords &Keywords, unsigned StartLevel,
48
                     int AdditionalIndent)
49
3.04k
      : Style(Style), Keywords(Keywords), AdditionalIndent(AdditionalIndent) {
50
246k
    for (unsigned i = 0; i != StartLevel; ++i)
51
243k
      IndentForLevel.push_back(Style.IndentWidth * i + AdditionalIndent);
52
3.04k
  }
53
54
  /// Returns the indent for the current line.
55
847k
  unsigned getIndent() const { return Indent; }
56
57
  /// Update the indent state given that \p Line is going to be formatted
58
  /// next.
59
423k
  void nextLine(const AnnotatedLine &Line) {
60
423k
    Offset = getIndentOffset(*Line.First);
61
    // Update the indent level cache size so that we can rely on it
62
    // having the right size in adjustToUnmodifiedline.
63
423k
    if (Line.Level >= IndentForLevel.size())
64
35.6k
      IndentForLevel.resize(Line.Level + 1, -1);
65
423k
    if (Style.IndentPPDirectives != FormatStyle::PPDIS_None &&
66
423k
        (Line.InPPDirective ||
67
0
         (Style.IndentPPDirectives == FormatStyle::PPDIS_BeforeHash &&
68
0
          Line.Type == LT_CommentAbovePPDirective))) {
69
0
      unsigned PPIndentWidth =
70
0
          (Style.PPIndentWidth >= 0) ? Style.PPIndentWidth : Style.IndentWidth;
71
0
      Indent = Line.InMacroBody
72
0
                   ? Line.PPLevel * PPIndentWidth +
73
0
                         (Line.Level - Line.PPLevel) * Style.IndentWidth
74
0
                   : Line.Level * PPIndentWidth;
75
0
      Indent += AdditionalIndent;
76
423k
    } else {
77
      // When going to lower levels, forget previous higher levels so that we
78
      // recompute future higher levels. But don't forget them if we enter a PP
79
      // directive, since these do not terminate a C++ code block.
80
423k
      if (!Line.InPPDirective) {
81
338k
        assert(Line.Level <= IndentForLevel.size());
82
0
        IndentForLevel.resize(Line.Level + 1);
83
338k
      }
84
0
      Indent = getIndent(Line.Level);
85
423k
    }
86
423k
    if (static_cast<int>(Indent) + Offset >= 0)
87
423k
      Indent += Offset;
88
423k
    if (Line.IsContinuation)
89
0
      Indent = Line.Level * Style.IndentWidth + Style.ContinuationIndentWidth;
90
423k
  }
91
92
  /// Update the level indent to adapt to the given \p Line.
93
  ///
94
  /// When a line is not formatted, we move the subsequent lines on the same
95
  /// level to the same indent.
96
  /// Note that \c nextLine must have been called before this method.
97
3.67k
  void adjustToUnmodifiedLine(const AnnotatedLine &Line) {
98
3.67k
    if (Line.InPPDirective || Line.IsContinuation)
99
24
      return;
100
3.65k
    assert(Line.Level < IndentForLevel.size());
101
3.65k
    if (Line.First->is(tok::comment) && IndentForLevel[Line.Level] != -1)
102
0
      return;
103
3.65k
    unsigned LevelIndent = Line.First->OriginalColumn;
104
3.65k
    if (static_cast<int>(LevelIndent) - Offset >= 0)
105
3.65k
      LevelIndent -= Offset;
106
3.65k
    IndentForLevel[Line.Level] = LevelIndent;
107
3.65k
  }
108
109
private:
110
  /// Get the offset of the line relatively to the level.
111
  ///
112
  /// For example, 'public:' labels in classes are offset by 1 or 2
113
  /// characters to the left from their level.
114
423k
  int getIndentOffset(const FormatToken &RootToken) {
115
423k
    if (Style.Language == FormatStyle::LK_Java || Style.isJavaScript() ||
116
423k
        Style.isCSharp()) {
117
0
      return 0;
118
0
    }
119
120
423k
    auto IsAccessModifier = [this, &RootToken]() {
121
423k
      if (RootToken.isAccessSpecifier(Style.isCpp())) {
122
0
        return true;
123
423k
      } else if (RootToken.isObjCAccessSpecifier()) {
124
0
        return true;
125
0
      }
126
      // Handle Qt signals.
127
423k
      else if (RootToken.isOneOf(Keywords.kw_signals, Keywords.kw_qsignals) &&
128
423k
               RootToken.Next && RootToken.Next->is(tok::colon)) {
129
0
        return true;
130
423k
      } else if (RootToken.Next &&
131
423k
                 RootToken.Next->isOneOf(Keywords.kw_slots,
132
205k
                                         Keywords.kw_qslots) &&
133
423k
                 RootToken.Next->Next && RootToken.Next->Next->is(tok::colon)) {
134
0
        return true;
135
0
      }
136
      // Handle malformed access specifier e.g. 'private' without trailing ':'.
137
423k
      else if (!RootToken.Next && RootToken.isAccessSpecifier(false)) {
138
0
        return true;
139
0
      }
140
423k
      return false;
141
423k
    };
142
143
423k
    if (IsAccessModifier()) {
144
      // The AccessModifierOffset may be overridden by IndentAccessModifiers,
145
      // in which case we take a negative value of the IndentWidth to simulate
146
      // the upper indent level.
147
0
      return Style.IndentAccessModifiers ? -Style.IndentWidth
148
0
                                         : Style.AccessModifierOffset;
149
0
    }
150
423k
    return 0;
151
423k
  }
152
153
  /// Get the indent of \p Level from \p IndentForLevel.
154
  ///
155
  /// \p IndentForLevel must contain the indent for the level \c l
156
  /// at \p IndentForLevel[l], or a value < 0 if the indent for
157
  /// that level is unknown.
158
15.8M
  unsigned getIndent(unsigned Level) const {
159
15.8M
    assert(Level < IndentForLevel.size());
160
15.8M
    if (IndentForLevel[Level] != -1)
161
164k
      return IndentForLevel[Level];
162
15.6M
    if (Level == 0)
163
259k
      return 0;
164
15.3M
    return getIndent(Level - 1) + Style.IndentWidth;
165
15.6M
  }
166
167
  const FormatStyle &Style;
168
  const AdditionalKeywords &Keywords;
169
  const unsigned AdditionalIndent;
170
171
  /// The indent in characters for each level. It remembers the indent of
172
  /// previous lines (that are not PP directives) of equal or lower levels. This
173
  /// is used to align formatted lines to the indent of previous non-formatted
174
  /// lines. Think about the --lines parameter of clang-format.
175
  SmallVector<int> IndentForLevel;
176
177
  /// Offset of the current line relative to the indent level.
178
  ///
179
  /// For example, the 'public' keywords is often indented with a negative
180
  /// offset.
181
  int Offset = 0;
182
183
  /// The current line's indent.
184
  unsigned Indent = 0;
185
};
186
187
const FormatToken *getMatchingNamespaceToken(
188
    const AnnotatedLine *Line,
189
0
    const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines) {
190
0
  if (!Line->startsWith(tok::r_brace))
191
0
    return nullptr;
192
0
  size_t StartLineIndex = Line->MatchingOpeningBlockLineIndex;
193
0
  if (StartLineIndex == UnwrappedLine::kInvalidIndex)
194
0
    return nullptr;
195
0
  assert(StartLineIndex < AnnotatedLines.size());
196
0
  return AnnotatedLines[StartLineIndex]->First->getNamespaceToken();
197
0
}
198
199
0
StringRef getNamespaceTokenText(const AnnotatedLine *Line) {
200
0
  const FormatToken *NamespaceToken = Line->First->getNamespaceToken();
201
0
  return NamespaceToken ? NamespaceToken->TokenText : StringRef();
202
0
}
203
204
StringRef getMatchingNamespaceTokenText(
205
    const AnnotatedLine *Line,
206
0
    const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines) {
207
0
  const FormatToken *NamespaceToken =
208
0
      getMatchingNamespaceToken(Line, AnnotatedLines);
209
0
  return NamespaceToken ? NamespaceToken->TokenText : StringRef();
210
0
}
211
212
class LineJoiner {
213
public:
214
  LineJoiner(const FormatStyle &Style, const AdditionalKeywords &Keywords,
215
             const SmallVectorImpl<AnnotatedLine *> &Lines)
216
      : Style(Style), Keywords(Keywords), End(Lines.end()), Next(Lines.begin()),
217
3.06k
        AnnotatedLines(Lines) {}
218
219
  /// Returns the next line, merging multiple lines into one if possible.
220
  const AnnotatedLine *getNextMergedLine(bool DryRun,
221
426k
                                         LevelIndentTracker &IndentTracker) {
222
426k
    if (Next == End)
223
3.04k
      return nullptr;
224
423k
    const AnnotatedLine *Current = *Next;
225
423k
    IndentTracker.nextLine(*Current);
226
423k
    unsigned MergedLines = tryFitMultipleLinesInOne(IndentTracker, Next, End);
227
423k
    if (MergedLines > 0 && Style.ColumnLimit == 0) {
228
      // Disallow line merging if there is a break at the start of one of the
229
      // input lines.
230
0
      for (unsigned i = 0; i < MergedLines; ++i)
231
0
        if (Next[i + 1]->First->NewlinesBefore > 0)
232
0
          MergedLines = 0;
233
0
    }
234
423k
    if (!DryRun)
235
471k
      for (unsigned i = 0; i < MergedLines; ++i)
236
48.5k
        join(*Next[0], *Next[i + 1]);
237
423k
    Next = Next + MergedLines + 1;
238
423k
    return Current;
239
426k
  }
240
241
private:
242
  /// Calculates how many lines can be merged into 1 starting at \p I.
243
  unsigned
244
  tryFitMultipleLinesInOne(LevelIndentTracker &IndentTracker,
245
                           SmallVectorImpl<AnnotatedLine *>::const_iterator I,
246
423k
                           SmallVectorImpl<AnnotatedLine *>::const_iterator E) {
247
423k
    const unsigned Indent = IndentTracker.getIndent();
248
249
    // Can't join the last line with anything.
250
423k
    if (I + 1 == E)
251
3.04k
      return 0;
252
    // We can never merge stuff if there are trailing line comments.
253
420k
    const AnnotatedLine *TheLine = *I;
254
420k
    if (TheLine->Last->is(TT_LineComment))
255
117
      return 0;
256
420k
    const auto &NextLine = *I[1];
257
420k
    if (NextLine.Type == LT_Invalid || NextLine.First->MustBreakBefore)
258
101k
      return 0;
259
318k
    if (TheLine->InPPDirective &&
260
318k
        (!NextLine.InPPDirective || NextLine.First->HasUnescapedNewline)) {
261
8.33k
      return 0;
262
8.33k
    }
263
264
310k
    if (Style.ColumnLimit > 0 && Indent > Style.ColumnLimit)
265
54.0k
      return 0;
266
267
256k
    unsigned Limit =
268
256k
        Style.ColumnLimit == 0 ? UINT_MAX : Style.ColumnLimit - Indent;
269
    // If we already exceed the column limit, we set 'Limit' to 0. The different
270
    // tryMerge..() functions can then decide whether to still do merging.
271
256k
    Limit = TheLine->Last->TotalLength > Limit
272
256k
                ? 0
273
256k
                : Limit - TheLine->Last->TotalLength;
274
275
256k
    if (TheLine->Last->is(TT_FunctionLBrace) &&
276
256k
        TheLine->First == TheLine->Last &&
277
256k
        !Style.BraceWrapping.SplitEmptyFunction &&
278
256k
        NextLine.First->is(tok::r_brace)) {
279
0
      return tryMergeSimpleBlock(I, E, Limit);
280
0
    }
281
282
256k
    const auto *PreviousLine = I != AnnotatedLines.begin() ? I[-1] : nullptr;
283
    // Handle empty record blocks where the brace has already been wrapped.
284
256k
    if (PreviousLine && TheLine->Last->is(tok::l_brace) &&
285
256k
        TheLine->First == TheLine->Last) {
286
1.16k
      bool EmptyBlock = NextLine.First->is(tok::r_brace);
287
288
1.16k
      const FormatToken *Tok = PreviousLine->First;
289
1.16k
      if (Tok && Tok->is(tok::comment))
290
0
        Tok = Tok->getNextNonComment();
291
292
1.16k
      if (Tok && Tok->getNamespaceToken()) {
293
0
        return !Style.BraceWrapping.SplitEmptyNamespace && EmptyBlock
294
0
                   ? tryMergeSimpleBlock(I, E, Limit)
295
0
                   : 0;
296
0
      }
297
298
1.16k
      if (Tok && Tok->is(tok::kw_typedef))
299
0
        Tok = Tok->getNextNonComment();
300
1.16k
      if (Tok && Tok->isOneOf(tok::kw_class, tok::kw_struct, tok::kw_union,
301
1.16k
                              tok::kw_extern, Keywords.kw_interface)) {
302
3
        return !Style.BraceWrapping.SplitEmptyRecord && EmptyBlock
303
3
                   ? tryMergeSimpleBlock(I, E, Limit)
304
3
                   : 0;
305
3
      }
306
307
1.15k
      if (Tok && Tok->is(tok::kw_template) &&
308
1.15k
          Style.BraceWrapping.SplitEmptyRecord && EmptyBlock) {
309
0
        return 0;
310
0
      }
311
1.15k
    }
312
313
256k
    auto ShouldMergeShortFunctions = [this, &I, &NextLine, PreviousLine,
314
256k
                                      TheLine]() {
315
256k
      if (Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_All)
316
256k
        return true;
317
0
      if (Style.AllowShortFunctionsOnASingleLine >= FormatStyle::SFS_Empty &&
318
0
          NextLine.First->is(tok::r_brace)) {
319
0
        return true;
320
0
      }
321
322
0
      if (Style.AllowShortFunctionsOnASingleLine &
323
0
          FormatStyle::SFS_InlineOnly) {
324
        // Just checking TheLine->Level != 0 is not enough, because it
325
        // provokes treating functions inside indented namespaces as short.
326
0
        if (Style.isJavaScript() && TheLine->Last->is(TT_FunctionLBrace))
327
0
          return true;
328
329
0
        if (TheLine->Level != 0) {
330
0
          if (!PreviousLine)
331
0
            return false;
332
333
          // TODO: Use IndentTracker to avoid loop?
334
          // Find the last line with lower level.
335
0
          const AnnotatedLine *Line = nullptr;
336
0
          for (auto J = I - 1; J >= AnnotatedLines.begin(); --J) {
337
0
            assert(*J);
338
0
            if (!(*J)->InPPDirective && !(*J)->isComment() &&
339
0
                (*J)->Level < TheLine->Level) {
340
0
              Line = *J;
341
0
              break;
342
0
            }
343
0
          }
344
345
0
          if (!Line)
346
0
            return false;
347
348
          // Check if the found line starts a record.
349
0
          const auto *LastNonComment = Line->getLastNonComment();
350
          // There must be another token (usually `{`), because we chose a
351
          // non-PPDirective and non-comment line that has a smaller level.
352
0
          assert(LastNonComment);
353
0
          return isRecordLBrace(*LastNonComment);
354
0
        }
355
0
      }
356
357
0
      return false;
358
0
    };
359
360
256k
    bool MergeShortFunctions = ShouldMergeShortFunctions();
361
362
256k
    const auto *FirstNonComment = TheLine->getFirstNonComment();
363
256k
    if (!FirstNonComment)
364
1.45k
      return 0;
365
    // FIXME: There are probably cases where we should use FirstNonComment
366
    // instead of TheLine->First.
367
368
255k
    if (Style.CompactNamespaces) {
369
0
      if (const auto *NSToken = TheLine->First->getNamespaceToken()) {
370
0
        int J = 1;
371
0
        assert(TheLine->MatchingClosingBlockLineIndex > 0);
372
0
        for (auto ClosingLineIndex = TheLine->MatchingClosingBlockLineIndex - 1;
373
0
             I + J != E && NSToken->TokenText == getNamespaceTokenText(I[J]) &&
374
0
             ClosingLineIndex == I[J]->MatchingClosingBlockLineIndex &&
375
0
             I[J]->Last->TotalLength < Limit;
376
0
             ++J, --ClosingLineIndex) {
377
0
          Limit -= I[J]->Last->TotalLength;
378
379
          // Reduce indent level for bodies of namespaces which were compacted,
380
          // but only if their content was indented in the first place.
381
0
          auto *ClosingLine = AnnotatedLines.begin() + ClosingLineIndex + 1;
382
0
          const int OutdentBy = I[J]->Level - TheLine->Level;
383
0
          assert(OutdentBy >= 0);
384
0
          for (auto *CompactedLine = I + J; CompactedLine <= ClosingLine;
385
0
               ++CompactedLine) {
386
0
            if (!(*CompactedLine)->InPPDirective) {
387
0
              const int Level = (*CompactedLine)->Level;
388
0
              (*CompactedLine)->Level = std::max(Level - OutdentBy, 0);
389
0
            }
390
0
          }
391
0
        }
392
0
        return J - 1;
393
0
      }
394
395
0
      if (auto nsToken = getMatchingNamespaceToken(TheLine, AnnotatedLines)) {
396
0
        int i = 0;
397
0
        unsigned openingLine = TheLine->MatchingOpeningBlockLineIndex - 1;
398
0
        for (; I + 1 + i != E &&
399
0
               nsToken->TokenText ==
400
0
                   getMatchingNamespaceTokenText(I[i + 1], AnnotatedLines) &&
401
0
               openingLine == I[i + 1]->MatchingOpeningBlockLineIndex;
402
0
             i++, --openingLine) {
403
          // No space between consecutive braces.
404
0
          I[i + 1]->First->SpacesRequiredBefore =
405
0
              I[i]->Last->isNot(tok::r_brace);
406
407
          // Indent like the outer-most namespace.
408
0
          IndentTracker.nextLine(*I[i + 1]);
409
0
        }
410
0
        return i;
411
0
      }
412
0
    }
413
414
255k
    const auto *LastNonComment = TheLine->getLastNonComment();
415
255k
    assert(LastNonComment);
416
    // FIXME: There are probably cases where we should use LastNonComment
417
    // instead of TheLine->Last.
418
419
    // Try to merge a function block with left brace unwrapped.
420
255k
    if (LastNonComment->is(TT_FunctionLBrace) &&
421
255k
        TheLine->First != LastNonComment) {
422
64.8k
      return MergeShortFunctions ? tryMergeSimpleBlock(I, E, Limit) : 0;
423
64.8k
    }
424
    // Try to merge a control statement block with left brace unwrapped.
425
190k
    if (TheLine->Last->is(tok::l_brace) && FirstNonComment != TheLine->Last &&
426
190k
        FirstNonComment->isOneOf(tok::kw_if, tok::kw_while, tok::kw_for,
427
1.31k
                                 TT_ForEachMacro)) {
428
943
      return Style.AllowShortBlocksOnASingleLine != FormatStyle::SBS_Never
429
943
                 ? tryMergeSimpleBlock(I, E, Limit)
430
943
                 : 0;
431
943
    }
432
    // Try to merge a control statement block with left brace wrapped.
433
189k
    if (NextLine.First->is(tok::l_brace)) {
434
1.14k
      if ((TheLine->First->isOneOf(tok::kw_if, tok::kw_else, tok::kw_while,
435
1.14k
                                   tok::kw_for, tok::kw_switch, tok::kw_try,
436
1.14k
                                   tok::kw_do, TT_ForEachMacro) ||
437
1.14k
           (TheLine->First->is(tok::r_brace) && TheLine->First->Next &&
438
1.14k
            TheLine->First->Next->isOneOf(tok::kw_else, tok::kw_catch))) &&
439
1.14k
          Style.BraceWrapping.AfterControlStatement ==
440
0
              FormatStyle::BWACS_MultiLine) {
441
        // If possible, merge the next line's wrapped left brace with the
442
        // current line. Otherwise, leave it on the next line, as this is a
443
        // multi-line control statement.
444
0
        return (Style.ColumnLimit == 0 || TheLine->Level * Style.IndentWidth +
445
0
                                                  TheLine->Last->TotalLength <=
446
0
                                              Style.ColumnLimit)
447
0
                   ? 1
448
0
                   : 0;
449
0
      }
450
1.14k
      if (TheLine->First->isOneOf(tok::kw_if, tok::kw_else, tok::kw_while,
451
1.14k
                                  tok::kw_for, TT_ForEachMacro)) {
452
0
        return (Style.BraceWrapping.AfterControlStatement ==
453
0
                FormatStyle::BWACS_Always)
454
0
                   ? tryMergeSimpleBlock(I, E, Limit)
455
0
                   : 0;
456
0
      }
457
1.14k
      if (TheLine->First->isOneOf(tok::kw_else, tok::kw_catch) &&
458
1.14k
          Style.BraceWrapping.AfterControlStatement ==
459
0
              FormatStyle::BWACS_MultiLine) {
460
        // This case if different from the upper BWACS_MultiLine processing
461
        // in that a preceding r_brace is not on the same line as else/catch
462
        // most likely because of BeforeElse/BeforeCatch set to true.
463
        // If the line length doesn't fit ColumnLimit, leave l_brace on the
464
        // next line to respect the BWACS_MultiLine.
465
0
        return (Style.ColumnLimit == 0 ||
466
0
                TheLine->Last->TotalLength <= Style.ColumnLimit)
467
0
                   ? 1
468
0
                   : 0;
469
0
      }
470
1.14k
    }
471
189k
    if (PreviousLine && TheLine->First->is(tok::l_brace)) {
472
1.53k
      switch (PreviousLine->First->Tok.getKind()) {
473
0
      case tok::at:
474
        // Don't merge block with left brace wrapped after ObjC special blocks.
475
0
        if (PreviousLine->First->Next) {
476
0
          tok::ObjCKeywordKind kwId =
477
0
              PreviousLine->First->Next->Tok.getObjCKeywordID();
478
0
          if (kwId == tok::objc_autoreleasepool ||
479
0
              kwId == tok::objc_synchronized) {
480
0
            return 0;
481
0
          }
482
0
        }
483
0
        break;
484
485
0
      case tok::kw_case:
486
0
      case tok::kw_default:
487
        // Don't merge block with left brace wrapped after case labels.
488
0
        return 0;
489
490
1.53k
      default:
491
1.53k
        break;
492
1.53k
      }
493
1.53k
    }
494
495
    // Don't merge an empty template class or struct if SplitEmptyRecords
496
    // is defined.
497
189k
    if (PreviousLine && Style.BraceWrapping.SplitEmptyRecord &&
498
189k
        TheLine->Last->is(tok::l_brace) && PreviousLine->Last) {
499
1.50k
      const FormatToken *Previous = PreviousLine->Last;
500
1.50k
      if (Previous) {
501
1.50k
        if (Previous->is(tok::comment))
502
11
          Previous = Previous->getPreviousNonComment();
503
1.50k
        if (Previous) {
504
1.49k
          if (Previous->is(tok::greater) && !PreviousLine->InPPDirective)
505
0
            return 0;
506
1.49k
          if (Previous->is(tok::identifier)) {
507
3
            const FormatToken *PreviousPrevious =
508
3
                Previous->getPreviousNonComment();
509
3
            if (PreviousPrevious &&
510
3
                PreviousPrevious->isOneOf(tok::kw_class, tok::kw_struct)) {
511
0
              return 0;
512
0
            }
513
3
          }
514
1.49k
        }
515
1.50k
      }
516
1.50k
    }
517
518
189k
    if (TheLine->Last->is(tok::l_brace)) {
519
1.55k
      bool ShouldMerge = false;
520
      // Try to merge records.
521
1.55k
      if (TheLine->Last->is(TT_EnumLBrace)) {
522
0
        ShouldMerge = Style.AllowShortEnumsOnASingleLine;
523
1.55k
      } else if (TheLine->Last->is(TT_RequiresExpressionLBrace)) {
524
0
        ShouldMerge = Style.AllowShortCompoundRequirementOnASingleLine;
525
1.55k
      } else if (TheLine->Last->isOneOf(TT_ClassLBrace, TT_StructLBrace)) {
526
        // NOTE: We use AfterClass (whereas AfterStruct exists) for both classes
527
        // and structs, but it seems that wrapping is still handled correctly
528
        // elsewhere.
529
56
        ShouldMerge = !Style.BraceWrapping.AfterClass ||
530
56
                      (NextLine.First->is(tok::r_brace) &&
531
0
                       !Style.BraceWrapping.SplitEmptyRecord);
532
1.50k
      } else if (TheLine->InPPDirective ||
533
1.50k
                 !TheLine->First->isOneOf(tok::kw_class, tok::kw_enum,
534
1.50k
                                          tok::kw_struct)) {
535
        // Try to merge a block with left brace unwrapped that wasn't yet
536
        // covered.
537
1.50k
        ShouldMerge = !Style.BraceWrapping.AfterFunction ||
538
1.50k
                      (NextLine.First->is(tok::r_brace) &&
539
0
                       !Style.BraceWrapping.SplitEmptyFunction);
540
1.50k
      }
541
1.55k
      return ShouldMerge ? tryMergeSimpleBlock(I, E, Limit) : 0;
542
1.55k
    }
543
544
    // Try to merge a function block with left brace wrapped.
545
187k
    if (NextLine.First->is(TT_FunctionLBrace) &&
546
187k
        Style.BraceWrapping.AfterFunction) {
547
0
      if (NextLine.Last->is(TT_LineComment))
548
0
        return 0;
549
550
      // Check for Limit <= 2 to account for the " {".
551
0
      if (Limit <= 2 || (Style.ColumnLimit == 0 && containsMustBreak(TheLine)))
552
0
        return 0;
553
0
      Limit -= 2;
554
555
0
      unsigned MergedLines = 0;
556
0
      if (MergeShortFunctions ||
557
0
          (Style.AllowShortFunctionsOnASingleLine >= FormatStyle::SFS_Empty &&
558
0
           NextLine.First == NextLine.Last && I + 2 != E &&
559
0
           I[2]->First->is(tok::r_brace))) {
560
0
        MergedLines = tryMergeSimpleBlock(I + 1, E, Limit);
561
        // If we managed to merge the block, count the function header, which is
562
        // on a separate line.
563
0
        if (MergedLines > 0)
564
0
          ++MergedLines;
565
0
      }
566
0
      return MergedLines;
567
0
    }
568
187k
    auto IsElseLine = [&TheLine]() -> bool {
569
186k
      const FormatToken *First = TheLine->First;
570
186k
      if (First->is(tok::kw_else))
571
12
        return true;
572
573
186k
      return First->is(tok::r_brace) && First->Next &&
574
186k
             First->Next->is(tok::kw_else);
575
186k
    };
576
187k
    if (TheLine->First->is(tok::kw_if) ||
577
187k
        (IsElseLine() && (Style.AllowShortIfStatementsOnASingleLine ==
578
1.07k
                          FormatStyle::SIS_AllIfsAndElse))) {
579
1.07k
      return Style.AllowShortIfStatementsOnASingleLine
580
1.07k
                 ? tryMergeSimpleControlStatement(I, E, Limit)
581
1.07k
                 : 0;
582
1.07k
    }
583
186k
    if (TheLine->First->isOneOf(tok::kw_for, tok::kw_while, tok::kw_do,
584
186k
                                TT_ForEachMacro)) {
585
43
      return Style.AllowShortLoopsOnASingleLine
586
43
                 ? tryMergeSimpleControlStatement(I, E, Limit)
587
43
                 : 0;
588
43
    }
589
186k
    if (TheLine->First->isOneOf(tok::kw_case, tok::kw_default)) {
590
0
      return Style.AllowShortCaseLabelsOnASingleLine
591
0
                 ? tryMergeShortCaseLabels(I, E, Limit)
592
0
                 : 0;
593
0
    }
594
186k
    if (TheLine->InPPDirective &&
595
186k
        (TheLine->First->HasUnescapedNewline || TheLine->First->IsFirst)) {
596
664
      return tryMergeSimplePPDirective(I, E, Limit);
597
664
    }
598
186k
    return 0;
599
186k
  }
600
601
  unsigned
602
  tryMergeSimplePPDirective(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
603
                            SmallVectorImpl<AnnotatedLine *>::const_iterator E,
604
664
                            unsigned Limit) {
605
664
    if (Limit == 0)
606
0
      return 0;
607
664
    if (I + 2 != E && I[2]->InPPDirective && !I[2]->First->HasUnescapedNewline)
608
24
      return 0;
609
640
    if (1 + I[1]->Last->TotalLength > Limit)
610
92
      return 0;
611
548
    return 1;
612
640
  }
613
614
  unsigned tryMergeSimpleControlStatement(
615
      SmallVectorImpl<AnnotatedLine *>::const_iterator I,
616
1.12k
      SmallVectorImpl<AnnotatedLine *>::const_iterator E, unsigned Limit) {
617
1.12k
    if (Limit == 0)
618
563
      return 0;
619
558
    if (Style.BraceWrapping.AfterControlStatement ==
620
558
            FormatStyle::BWACS_Always &&
621
558
        I[1]->First->is(tok::l_brace) &&
622
558
        Style.AllowShortBlocksOnASingleLine == FormatStyle::SBS_Never) {
623
0
      return 0;
624
0
    }
625
558
    if (I[1]->InPPDirective != (*I)->InPPDirective ||
626
558
        (I[1]->InPPDirective && I[1]->First->HasUnescapedNewline)) {
627
0
      return 0;
628
0
    }
629
558
    Limit = limitConsideringMacros(I + 1, E, Limit);
630
558
    AnnotatedLine &Line = **I;
631
558
    if (Line.First->isNot(tok::kw_do) && Line.First->isNot(tok::kw_else) &&
632
558
        Line.Last->isNot(tok::kw_else) && Line.Last->isNot(tok::r_paren)) {
633
101
      return 0;
634
101
    }
635
    // Only merge `do while` if `do` is the only statement on the line.
636
457
    if (Line.First->is(tok::kw_do) && Line.Last->isNot(tok::kw_do))
637
0
      return 0;
638
457
    if (1 + I[1]->Last->TotalLength > Limit)
639
345
      return 0;
640
    // Don't merge with loops, ifs, a single semicolon or a line comment.
641
112
    if (I[1]->First->isOneOf(tok::semi, tok::kw_if, tok::kw_for, tok::kw_while,
642
112
                             TT_ForEachMacro, TT_LineComment)) {
643
0
      return 0;
644
0
    }
645
    // Only inline simple if's (no nested if or else), unless specified
646
112
    if (Style.AllowShortIfStatementsOnASingleLine ==
647
112
        FormatStyle::SIS_WithoutElse) {
648
112
      if (I + 2 != E && Line.startsWith(tok::kw_if) &&
649
112
          I[2]->First->is(tok::kw_else)) {
650
8
        return 0;
651
8
      }
652
112
    }
653
104
    return 1;
654
112
  }
655
656
  unsigned
657
  tryMergeShortCaseLabels(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
658
                          SmallVectorImpl<AnnotatedLine *>::const_iterator E,
659
0
                          unsigned Limit) {
660
0
    if (Limit == 0 || I + 1 == E ||
661
0
        I[1]->First->isOneOf(tok::kw_case, tok::kw_default)) {
662
0
      return 0;
663
0
    }
664
0
    if (I[0]->Last->is(tok::l_brace) || I[1]->First->is(tok::l_brace))
665
0
      return 0;
666
0
    unsigned NumStmts = 0;
667
0
    unsigned Length = 0;
668
0
    bool EndsWithComment = false;
669
0
    bool InPPDirective = I[0]->InPPDirective;
670
0
    bool InMacroBody = I[0]->InMacroBody;
671
0
    const unsigned Level = I[0]->Level;
672
0
    for (; NumStmts < 3; ++NumStmts) {
673
0
      if (I + 1 + NumStmts == E)
674
0
        break;
675
0
      const AnnotatedLine *Line = I[1 + NumStmts];
676
0
      if (Line->InPPDirective != InPPDirective)
677
0
        break;
678
0
      if (Line->InMacroBody != InMacroBody)
679
0
        break;
680
0
      if (Line->First->isOneOf(tok::kw_case, tok::kw_default, tok::r_brace))
681
0
        break;
682
0
      if (Line->First->isOneOf(tok::kw_if, tok::kw_for, tok::kw_switch,
683
0
                               tok::kw_while) ||
684
0
          EndsWithComment) {
685
0
        return 0;
686
0
      }
687
0
      if (Line->First->is(tok::comment)) {
688
0
        if (Level != Line->Level)
689
0
          return 0;
690
0
        SmallVectorImpl<AnnotatedLine *>::const_iterator J = I + 2 + NumStmts;
691
0
        for (; J != E; ++J) {
692
0
          Line = *J;
693
0
          if (Line->InPPDirective != InPPDirective)
694
0
            break;
695
0
          if (Line->First->isOneOf(tok::kw_case, tok::kw_default, tok::r_brace))
696
0
            break;
697
0
          if (Line->First->isNot(tok::comment) || Level != Line->Level)
698
0
            return 0;
699
0
        }
700
0
        break;
701
0
      }
702
0
      if (Line->Last->is(tok::comment))
703
0
        EndsWithComment = true;
704
0
      Length += I[1 + NumStmts]->Last->TotalLength + 1; // 1 for the space.
705
0
    }
706
0
    if (NumStmts == 0 || NumStmts == 3 || Length > Limit)
707
0
      return 0;
708
0
    return NumStmts;
709
0
  }
710
711
  unsigned
712
  tryMergeSimpleBlock(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
713
                      SmallVectorImpl<AnnotatedLine *>::const_iterator E,
714
66.3k
                      unsigned Limit) {
715
    // Don't merge with a preprocessor directive.
716
66.3k
    if (I[1]->Type == LT_PreprocessorDirective)
717
29
      return 0;
718
719
66.3k
    AnnotatedLine &Line = **I;
720
721
    // Don't merge ObjC @ keywords and methods.
722
    // FIXME: If an option to allow short exception handling clauses on a single
723
    // line is added, change this to not return for @try and friends.
724
66.3k
    if (Style.Language != FormatStyle::LK_Java &&
725
66.3k
        Line.First->isOneOf(tok::at, tok::minus, tok::plus)) {
726
12
      return 0;
727
12
    }
728
729
    // Check that the current line allows merging. This depends on whether we
730
    // are in a control flow statements as well as several style flags.
731
66.3k
    if (Line.First->is(tok::kw_case) ||
732
66.3k
        (Line.First->Next && Line.First->Next->is(tok::kw_else))) {
733
173
      return 0;
734
173
    }
735
    // default: in switch statement
736
66.1k
    if (Line.First->is(tok::kw_default)) {
737
0
      const FormatToken *Tok = Line.First->getNextNonComment();
738
0
      if (Tok && Tok->is(tok::colon))
739
0
        return 0;
740
0
    }
741
742
67.3k
    auto IsCtrlStmt = [](const auto &Line) {
743
67.3k
      return Line.First->isOneOf(tok::kw_if, tok::kw_else, tok::kw_while,
744
67.3k
                                 tok::kw_do, tok::kw_for, TT_ForEachMacro);
745
67.3k
    };
746
747
66.1k
    const bool IsSplitBlock =
748
66.1k
        Style.AllowShortBlocksOnASingleLine == FormatStyle::SBS_Never ||
749
66.1k
        (Style.AllowShortBlocksOnASingleLine == FormatStyle::SBS_Empty &&
750
0
         I[1]->First->isNot(tok::r_brace));
751
752
66.1k
    if (IsCtrlStmt(Line) ||
753
66.1k
        Line.First->isOneOf(tok::kw_try, tok::kw___try, tok::kw_catch,
754
66.1k
                            tok::kw___finally, tok::r_brace,
755
66.1k
                            Keywords.kw___except)) {
756
37
      if (IsSplitBlock)
757
37
        return 0;
758
      // Don't merge when we can't except the case when
759
      // the control statement block is empty
760
0
      if (!Style.AllowShortIfStatementsOnASingleLine &&
761
0
          Line.First->isOneOf(tok::kw_if, tok::kw_else) &&
762
0
          !Style.BraceWrapping.AfterControlStatement &&
763
0
          I[1]->First->isNot(tok::r_brace)) {
764
0
        return 0;
765
0
      }
766
0
      if (!Style.AllowShortIfStatementsOnASingleLine &&
767
0
          Line.First->isOneOf(tok::kw_if, tok::kw_else) &&
768
0
          Style.BraceWrapping.AfterControlStatement ==
769
0
              FormatStyle::BWACS_Always &&
770
0
          I + 2 != E && I[2]->First->isNot(tok::r_brace)) {
771
0
        return 0;
772
0
      }
773
0
      if (!Style.AllowShortLoopsOnASingleLine &&
774
0
          Line.First->isOneOf(tok::kw_while, tok::kw_do, tok::kw_for,
775
0
                              TT_ForEachMacro) &&
776
0
          !Style.BraceWrapping.AfterControlStatement &&
777
0
          I[1]->First->isNot(tok::r_brace)) {
778
0
        return 0;
779
0
      }
780
0
      if (!Style.AllowShortLoopsOnASingleLine &&
781
0
          Line.First->isOneOf(tok::kw_while, tok::kw_do, tok::kw_for,
782
0
                              TT_ForEachMacro) &&
783
0
          Style.BraceWrapping.AfterControlStatement ==
784
0
              FormatStyle::BWACS_Always &&
785
0
          I + 2 != E && I[2]->First->isNot(tok::r_brace)) {
786
0
        return 0;
787
0
      }
788
      // FIXME: Consider an option to allow short exception handling clauses on
789
      // a single line.
790
      // FIXME: This isn't covered by tests.
791
      // FIXME: For catch, __except, __finally the first token on the line
792
      // is '}', so this isn't correct here.
793
0
      if (Line.First->isOneOf(tok::kw_try, tok::kw___try, tok::kw_catch,
794
0
                              Keywords.kw___except, tok::kw___finally)) {
795
0
        return 0;
796
0
      }
797
0
    }
798
799
66.1k
    if (const auto *LastNonComment = Line.getLastNonComment();
800
66.1k
        LastNonComment && LastNonComment->is(tok::l_brace)) {
801
66.1k
      if (IsSplitBlock && Line.First == Line.Last &&
802
66.1k
          I > AnnotatedLines.begin() &&
803
66.1k
          (I[-1]->endsWith(tok::kw_else) || IsCtrlStmt(*I[-1]))) {
804
0
        return 0;
805
0
      }
806
66.1k
      FormatToken *Tok = I[1]->First;
807
66.1k
      auto ShouldMerge = [Tok]() {
808
66.1k
        if (Tok->isNot(tok::r_brace) || Tok->MustBreakBefore)
809
21.2k
          return false;
810
44.8k
        const FormatToken *Next = Tok->getNextNonComment();
811
44.8k
        return !Next || Next->is(tok::semi);
812
66.1k
      };
813
814
66.1k
      if (ShouldMerge()) {
815
        // We merge empty blocks even if the line exceeds the column limit.
816
44.8k
        Tok->SpacesRequiredBefore =
817
44.8k
            (Style.SpaceInEmptyBlock || Line.Last->is(tok::comment)) ? 1 : 0;
818
44.8k
        Tok->CanBreakBefore = true;
819
44.8k
        return 1;
820
44.8k
      } else if (Limit != 0 && !Line.startsWithNamespace() &&
821
21.2k
                 !startsExternCBlock(Line)) {
822
        // We don't merge short records.
823
20.0k
        if (isRecordLBrace(*Line.Last))
824
40
          return 0;
825
826
        // Check that we still have three lines and they fit into the limit.
827
20.0k
        if (I + 2 == E || I[2]->Type == LT_Invalid)
828
34
          return 0;
829
20.0k
        Limit = limitConsideringMacros(I + 2, E, Limit);
830
831
20.0k
        if (!nextTwoLinesFitInto(I, Limit))
832
4.95k
          return 0;
833
834
        // Second, check that the next line does not contain any braces - if it
835
        // does, readability declines when putting it into a single line.
836
15.0k
        if (I[1]->Last->is(TT_LineComment))
837
0
          return 0;
838
80.8k
        do {
839
80.8k
          if (Tok->is(tok::l_brace) && Tok->isNot(BK_BracedInit))
840
13.5k
            return 0;
841
67.2k
          Tok = Tok->Next;
842
67.2k
        } while (Tok);
843
844
        // Last, check that the third line starts with a closing brace.
845
1.50k
        Tok = I[2]->First;
846
1.50k
        if (Tok->isNot(tok::r_brace))
847
12
          return 0;
848
849
        // Don't merge "if (a) { .. } else {".
850
1.49k
        if (Tok->Next && Tok->Next->is(tok::kw_else))
851
0
          return 0;
852
853
        // Don't merge a trailing multi-line control statement block like:
854
        // } else if (foo &&
855
        //            bar)
856
        // { <-- current Line
857
        //   baz();
858
        // }
859
1.49k
        if (Line.First == Line.Last && Line.First->isNot(TT_FunctionLBrace) &&
860
1.49k
            Style.BraceWrapping.AfterControlStatement ==
861
772
                FormatStyle::BWACS_MultiLine) {
862
0
          return 0;
863
0
        }
864
865
1.49k
        return 2;
866
1.49k
      }
867
66.1k
    } else if (I[1]->First->is(tok::l_brace)) {
868
0
      if (I[1]->Last->is(TT_LineComment))
869
0
        return 0;
870
871
      // Check for Limit <= 2 to account for the " {".
872
0
      if (Limit <= 2 || (Style.ColumnLimit == 0 && containsMustBreak(*I)))
873
0
        return 0;
874
0
      Limit -= 2;
875
0
      unsigned MergedLines = 0;
876
0
      if (Style.AllowShortBlocksOnASingleLine != FormatStyle::SBS_Never ||
877
0
          (I[1]->First == I[1]->Last && I + 2 != E &&
878
0
           I[2]->First->is(tok::r_brace))) {
879
0
        MergedLines = tryMergeSimpleBlock(I + 1, E, Limit);
880
        // If we managed to merge the block, count the statement header, which
881
        // is on a separate line.
882
0
        if (MergedLines > 0)
883
0
          ++MergedLines;
884
0
      }
885
0
      return MergedLines;
886
0
    }
887
1.15k
    return 0;
888
66.1k
  }
889
890
  /// Returns the modified column limit for \p I if it is inside a macro and
891
  /// needs a trailing '\'.
892
  unsigned
893
  limitConsideringMacros(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
894
                         SmallVectorImpl<AnnotatedLine *>::const_iterator E,
895
20.5k
                         unsigned Limit) {
896
20.5k
    if (I[0]->InPPDirective && I + 1 != E &&
897
20.5k
        !I[1]->First->HasUnescapedNewline && I[1]->First->isNot(tok::eof)) {
898
8
      return Limit < 2 ? 0 : Limit - 2;
899
8
    }
900
20.5k
    return Limit;
901
20.5k
  }
902
903
  bool nextTwoLinesFitInto(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
904
20.0k
                           unsigned Limit) {
905
20.0k
    if (I[1]->First->MustBreakBefore || I[2]->First->MustBreakBefore)
906
2.79k
      return false;
907
17.2k
    return 1 + I[1]->Last->TotalLength + 1 + I[2]->Last->TotalLength <= Limit;
908
20.0k
  }
909
910
0
  bool containsMustBreak(const AnnotatedLine *Line) {
911
0
    assert(Line->First);
912
    // Ignore the first token, because in this situation, it applies more to the
913
    // last token of the previous line.
914
0
    for (const FormatToken *Tok = Line->First->Next; Tok; Tok = Tok->Next)
915
0
      if (Tok->MustBreakBefore)
916
0
        return true;
917
0
    return false;
918
0
  }
919
920
48.5k
  void join(AnnotatedLine &A, const AnnotatedLine &B) {
921
48.5k
    assert(!A.Last->Next);
922
0
    assert(!B.First->Previous);
923
48.5k
    if (B.Affected)
924
48.5k
      A.Affected = true;
925
48.5k
    A.Last->Next = B.First;
926
48.5k
    B.First->Previous = A.Last;
927
48.5k
    B.First->CanBreakBefore = true;
928
48.5k
    unsigned LengthA = A.Last->TotalLength + B.First->SpacesRequiredBefore;
929
101k
    for (FormatToken *Tok = B.First; Tok; Tok = Tok->Next) {
930
53.0k
      Tok->TotalLength += LengthA;
931
53.0k
      A.Last = Tok;
932
53.0k
    }
933
48.5k
  }
934
935
  const FormatStyle &Style;
936
  const AdditionalKeywords &Keywords;
937
  const SmallVectorImpl<AnnotatedLine *>::const_iterator End;
938
939
  SmallVectorImpl<AnnotatedLine *>::const_iterator Next;
940
  const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines;
941
};
942
943
422k
static void markFinalized(FormatToken *Tok) {
944
422k
  if (Tok->is(tok::hash) && !Tok->Previous && Tok->Next &&
945
422k
      Tok->Next->isOneOf(tok::pp_if, tok::pp_ifdef, tok::pp_ifndef,
946
11.5k
                         tok::pp_elif, tok::pp_elifdef, tok::pp_elifndef,
947
11.5k
                         tok::pp_else, tok::pp_endif)) {
948
513
    Tok = Tok->Next;
949
513
  }
950
16.4M
  for (; Tok; Tok = Tok->Next) {
951
15.9M
    if (Tok->MacroCtx && Tok->MacroCtx->Role == MR_ExpandedArg) {
952
      // In the first pass we format all macro arguments in the expanded token
953
      // stream. Instead of finalizing the macro arguments, we mark that they
954
      // will be modified as unexpanded arguments (as part of the macro call
955
      // formatting) in the next pass.
956
0
      Tok->MacroCtx->Role = MR_UnexpandedArg;
957
      // Reset whether spaces or a line break are required before this token, as
958
      // that is context dependent, and that context may change when formatting
959
      // the macro call.  For example, given M(x) -> 2 * x, and the macro call
960
      // M(var), the token 'var' will have SpacesRequiredBefore = 1 after being
961
      // formatted as part of the expanded macro, but SpacesRequiredBefore = 0
962
      // for its position within the macro call.
963
0
      Tok->SpacesRequiredBefore = 0;
964
0
      if (!Tok->MustBreakBeforeFinalized)
965
0
        Tok->MustBreakBefore = 0;
966
15.9M
    } else {
967
15.9M
      Tok->Finalized = true;
968
15.9M
    }
969
15.9M
  }
970
422k
}
971
972
#ifndef NDEBUG
973
0
static void printLineState(const LineState &State) {
974
0
  llvm::dbgs() << "State: ";
975
0
  for (const ParenState &P : State.Stack) {
976
0
    llvm::dbgs() << (P.Tok ? P.Tok->TokenText : "F") << "|" << P.Indent << "|"
977
0
                 << P.LastSpace << "|" << P.NestedBlockIndent << " ";
978
0
  }
979
0
  llvm::dbgs() << State.NextToken->TokenText << "\n";
980
0
}
981
#endif
982
983
/// Base class for classes that format one \c AnnotatedLine.
984
class LineFormatter {
985
public:
986
  LineFormatter(ContinuationIndenter *Indenter, WhitespaceManager *Whitespaces,
987
                const FormatStyle &Style,
988
                UnwrappedLineFormatter *BlockFormatter)
989
      : Indenter(Indenter), Whitespaces(Whitespaces), Style(Style),
990
409k
        BlockFormatter(BlockFormatter) {}
991
409k
  virtual ~LineFormatter() {}
992
993
  /// Formats an \c AnnotatedLine and returns the penalty.
994
  ///
995
  /// If \p DryRun is \c false, directly applies the changes.
996
  virtual unsigned formatLine(const AnnotatedLine &Line, unsigned FirstIndent,
997
                              unsigned FirstStartColumn, bool DryRun) = 0;
998
999
protected:
1000
  /// If the \p State's next token is an r_brace closing a nested block,
1001
  /// format the nested block before it.
1002
  ///
1003
  /// Returns \c true if all children could be placed successfully and adapts
1004
  /// \p Penalty as well as \p State. If \p DryRun is false, also directly
1005
  /// creates changes using \c Whitespaces.
1006
  ///
1007
  /// The crucial idea here is that children always get formatted upon
1008
  /// encountering the closing brace right after the nested block. Now, if we
1009
  /// are currently trying to keep the "}" on the same line (i.e. \p NewLine is
1010
  /// \c false), the entire block has to be kept on the same line (which is only
1011
  /// possible if it fits on the line, only contains a single statement, etc.
1012
  ///
1013
  /// If \p NewLine is true, we format the nested block on separate lines, i.e.
1014
  /// break after the "{", format all lines with correct indentation and the put
1015
  /// the closing "}" on yet another new line.
1016
  ///
1017
  /// This enables us to keep the simple structure of the
1018
  /// \c UnwrappedLineFormatter, where we only have two options for each token:
1019
  /// break or don't break.
1020
  bool formatChildren(LineState &State, bool NewLine, bool DryRun,
1021
6.61M
                      unsigned &Penalty) {
1022
6.61M
    const FormatToken *LBrace = State.NextToken->getPreviousNonComment();
1023
6.61M
    bool HasLBrace = LBrace && LBrace->is(tok::l_brace) && LBrace->is(BK_Block);
1024
6.61M
    FormatToken &Previous = *State.NextToken->Previous;
1025
6.61M
    if (Previous.Children.size() == 0 || (!HasLBrace && !LBrace->MacroParent)) {
1026
      // The previous token does not open a block. Nothing to do. We don't
1027
      // assert so that we can simply call this function for all tokens.
1028
6.61M
      return true;
1029
6.61M
    }
1030
1031
51
    if (NewLine || Previous.MacroParent) {
1032
30
      const ParenState &P = State.Stack.back();
1033
1034
30
      int AdditionalIndent =
1035
30
          P.Indent - Previous.Children[0]->Level * Style.IndentWidth;
1036
30
      Penalty +=
1037
30
          BlockFormatter->format(Previous.Children, DryRun, AdditionalIndent,
1038
30
                                 /*FixBadIndentation=*/true);
1039
30
      return true;
1040
30
    }
1041
1042
21
    if (Previous.Children[0]->First->MustBreakBefore)
1043
18
      return false;
1044
1045
    // Cannot merge into one line if this line ends on a comment.
1046
3
    if (Previous.is(tok::comment))
1047
0
      return false;
1048
1049
    // Cannot merge multiple statements into a single line.
1050
3
    if (Previous.Children.size() > 1)
1051
0
      return false;
1052
1053
3
    const AnnotatedLine *Child = Previous.Children[0];
1054
    // We can't put the closing "}" on a line with a trailing comment.
1055
3
    if (Child->Last->isTrailingComment())
1056
0
      return false;
1057
1058
    // If the child line exceeds the column limit, we wouldn't want to merge it.
1059
    // We add +2 for the trailing " }".
1060
3
    if (Style.ColumnLimit > 0 &&
1061
3
        Child->Last->TotalLength + State.Column + 2 > Style.ColumnLimit) {
1062
3
      return false;
1063
3
    }
1064
1065
0
    if (!DryRun) {
1066
0
      Whitespaces->replaceWhitespace(
1067
0
          *Child->First, /*Newlines=*/0, /*Spaces=*/1,
1068
0
          /*StartOfTokenColumn=*/State.Column, /*IsAligned=*/false,
1069
0
          State.Line->InPPDirective);
1070
0
    }
1071
0
    Penalty +=
1072
0
        formatLine(*Child, State.Column + 1, /*FirstStartColumn=*/0, DryRun);
1073
0
    if (!DryRun)
1074
0
      markFinalized(Child->First);
1075
1076
0
    State.Column += 1 + Child->Last->TotalLength;
1077
0
    return true;
1078
3
  }
1079
1080
  ContinuationIndenter *Indenter;
1081
1082
private:
1083
  WhitespaceManager *Whitespaces;
1084
  const FormatStyle &Style;
1085
  UnwrappedLineFormatter *BlockFormatter;
1086
};
1087
1088
/// Formatter that keeps the existing line breaks.
1089
class NoColumnLimitLineFormatter : public LineFormatter {
1090
public:
1091
  NoColumnLimitLineFormatter(ContinuationIndenter *Indenter,
1092
                             WhitespaceManager *Whitespaces,
1093
                             const FormatStyle &Style,
1094
                             UnwrappedLineFormatter *BlockFormatter)
1095
0
      : LineFormatter(Indenter, Whitespaces, Style, BlockFormatter) {}
1096
1097
  /// Formats the line, simply keeping all of the input's line breaking
1098
  /// decisions.
1099
  unsigned formatLine(const AnnotatedLine &Line, unsigned FirstIndent,
1100
0
                      unsigned FirstStartColumn, bool DryRun) override {
1101
0
    assert(!DryRun);
1102
0
    LineState State = Indenter->getInitialState(FirstIndent, FirstStartColumn,
1103
0
                                                &Line, /*DryRun=*/false);
1104
0
    while (State.NextToken) {
1105
0
      bool Newline =
1106
0
          Indenter->mustBreak(State) ||
1107
0
          (Indenter->canBreak(State) && State.NextToken->NewlinesBefore > 0);
1108
0
      unsigned Penalty = 0;
1109
0
      formatChildren(State, Newline, /*DryRun=*/false, Penalty);
1110
0
      Indenter->addTokenToState(State, Newline, /*DryRun=*/false);
1111
0
    }
1112
0
    return 0;
1113
0
  }
1114
};
1115
1116
/// Formatter that puts all tokens into a single line without breaks.
1117
class NoLineBreakFormatter : public LineFormatter {
1118
public:
1119
  NoLineBreakFormatter(ContinuationIndenter *Indenter,
1120
                       WhitespaceManager *Whitespaces, const FormatStyle &Style,
1121
                       UnwrappedLineFormatter *BlockFormatter)
1122
318k
      : LineFormatter(Indenter, Whitespaces, Style, BlockFormatter) {}
1123
1124
  /// Puts all tokens into a single line.
1125
  unsigned formatLine(const AnnotatedLine &Line, unsigned FirstIndent,
1126
318k
                      unsigned FirstStartColumn, bool DryRun) override {
1127
318k
    unsigned Penalty = 0;
1128
318k
    LineState State =
1129
318k
        Indenter->getInitialState(FirstIndent, FirstStartColumn, &Line, DryRun);
1130
758k
    while (State.NextToken) {
1131
439k
      formatChildren(State, /*NewLine=*/false, DryRun, Penalty);
1132
439k
      Indenter->addTokenToState(
1133
439k
          State, /*Newline=*/State.NextToken->MustBreakBefore, DryRun);
1134
439k
    }
1135
318k
    return Penalty;
1136
318k
  }
1137
};
1138
1139
/// Finds the best way to break lines.
1140
class OptimizingLineFormatter : public LineFormatter {
1141
public:
1142
  OptimizingLineFormatter(ContinuationIndenter *Indenter,
1143
                          WhitespaceManager *Whitespaces,
1144
                          const FormatStyle &Style,
1145
                          UnwrappedLineFormatter *BlockFormatter)
1146
91.3k
      : LineFormatter(Indenter, Whitespaces, Style, BlockFormatter) {}
1147
1148
  /// Formats the line by finding the best line breaks with line lengths
1149
  /// below the column limit.
1150
  unsigned formatLine(const AnnotatedLine &Line, unsigned FirstIndent,
1151
91.3k
                      unsigned FirstStartColumn, bool DryRun) override {
1152
91.3k
    LineState State =
1153
91.3k
        Indenter->getInitialState(FirstIndent, FirstStartColumn, &Line, DryRun);
1154
1155
    // If the ObjC method declaration does not fit on a line, we should format
1156
    // it with one arg per line.
1157
91.3k
    if (State.Line->Type == LT_ObjCMethodDecl)
1158
12
      State.Stack.back().BreakBeforeParameter = true;
1159
1160
    // Find best solution in solution space.
1161
91.3k
    return analyzeSolutionSpace(State, DryRun);
1162
91.3k
  }
1163
1164
private:
1165
  struct CompareLineStatePointers {
1166
99.6M
    bool operator()(LineState *obj1, LineState *obj2) const {
1167
99.6M
      return *obj1 < *obj2;
1168
99.6M
    }
1169
  };
1170
1171
  /// A pair of <penalty, count> that is used to prioritize the BFS on.
1172
  ///
1173
  /// In case of equal penalties, we want to prefer states that were inserted
1174
  /// first. During state generation we make sure that we insert states first
1175
  /// that break the line as late as possible.
1176
  typedef std::pair<unsigned, unsigned> OrderedPenalty;
1177
1178
  /// An edge in the solution space from \c Previous->State to \c State,
1179
  /// inserting a newline dependent on the \c NewLine.
1180
  struct StateNode {
1181
    StateNode(const LineState &State, bool NewLine, StateNode *Previous)
1182
4.87M
        : State(State), NewLine(NewLine), Previous(Previous) {}
1183
    LineState State;
1184
    bool NewLine;
1185
    StateNode *Previous;
1186
  };
1187
1188
  /// An item in the prioritized BFS search queue. The \c StateNode's
1189
  /// \c State has the given \c OrderedPenalty.
1190
  typedef std::pair<OrderedPenalty, StateNode *> QueueItem;
1191
1192
  /// The BFS queue type.
1193
  typedef std::priority_queue<QueueItem, SmallVector<QueueItem>,
1194
                              std::greater<QueueItem>>
1195
      QueueType;
1196
1197
  /// Analyze the entire solution space starting from \p InitialState.
1198
  ///
1199
  /// This implements a variant of Dijkstra's algorithm on the graph that spans
1200
  /// the solution space (\c LineStates are the nodes). The algorithm tries to
1201
  /// find the shortest path (the one with lowest penalty) from \p InitialState
1202
  /// to a state where all tokens are placed. Returns the penalty.
1203
  ///
1204
  /// If \p DryRun is \c false, directly applies the changes.
1205
91.3k
  unsigned analyzeSolutionSpace(LineState &InitialState, bool DryRun) {
1206
91.3k
    std::set<LineState *, CompareLineStatePointers> Seen;
1207
1208
    // Increasing count of \c StateNode items we have created. This is used to
1209
    // create a deterministic order independent of the container.
1210
91.3k
    unsigned Count = 0;
1211
91.3k
    QueueType Queue;
1212
1213
    // Insert start element into queue.
1214
91.3k
    StateNode *RootNode =
1215
91.3k
        new (Allocator.Allocate()) StateNode(InitialState, false, nullptr);
1216
91.3k
    Queue.push(QueueItem(OrderedPenalty(0, Count), RootNode));
1217
91.3k
    ++Count;
1218
1219
91.3k
    unsigned Penalty = 0;
1220
1221
    // While not empty, take first element and follow edges.
1222
4.67M
    while (!Queue.empty()) {
1223
      // Quit if we still haven't found a solution by now.
1224
4.67M
      if (Count > 25000000)
1225
0
        return 0;
1226
1227
4.67M
      Penalty = Queue.top().first.first;
1228
4.67M
      StateNode *Node = Queue.top().second;
1229
4.67M
      if (!Node->State.NextToken) {
1230
90.8k
        LLVM_DEBUG(llvm::dbgs()
1231
90.8k
                   << "\n---\nPenalty for line: " << Penalty << "\n");
1232
90.8k
        break;
1233
90.8k
      }
1234
4.58M
      Queue.pop();
1235
1236
      // Cut off the analysis of certain solutions if the analysis gets too
1237
      // complex. See description of IgnoreStackForComparison.
1238
4.58M
      if (Count > 50000)
1239
749k
        Node->State.IgnoreStackForComparison = true;
1240
1241
4.58M
      if (!Seen.insert(&Node->State).second) {
1242
        // State already examined with lower penalty.
1243
399k
        continue;
1244
399k
      }
1245
1246
4.18M
      FormatDecision LastFormat = Node->State.NextToken->getDecision();
1247
4.18M
      if (LastFormat == FD_Unformatted || LastFormat == FD_Continue)
1248
4.18M
        addNextStateToQueue(Penalty, Node, /*NewLine=*/false, &Count, &Queue);
1249
4.18M
      if (LastFormat == FD_Unformatted || LastFormat == FD_Break)
1250
4.15M
        addNextStateToQueue(Penalty, Node, /*NewLine=*/true, &Count, &Queue);
1251
4.18M
    }
1252
1253
91.3k
    if (Queue.empty()) {
1254
      // We were unable to find a solution, do nothing.
1255
      // FIXME: Add diagnostic?
1256
485
      LLVM_DEBUG(llvm::dbgs() << "Could not find a solution.\n");
1257
485
      return 0;
1258
485
    }
1259
1260
    // Reconstruct the solution.
1261
90.8k
    if (!DryRun)
1262
90.6k
      reconstructPath(InitialState, Queue.top().second);
1263
1264
90.8k
    LLVM_DEBUG(llvm::dbgs()
1265
90.8k
               << "Total number of analyzed states: " << Count << "\n");
1266
90.8k
    LLVM_DEBUG(llvm::dbgs() << "---\n");
1267
1268
90.8k
    return Penalty;
1269
91.3k
  }
1270
1271
  /// Add the following state to the analysis queue \c Queue.
1272
  ///
1273
  /// Assume the current state is \p PreviousNode and has been reached with a
1274
  /// penalty of \p Penalty. Insert a line break if \p NewLine is \c true.
1275
  void addNextStateToQueue(unsigned Penalty, StateNode *PreviousNode,
1276
8.33M
                           bool NewLine, unsigned *Count, QueueType *Queue) {
1277
8.33M
    if (NewLine && !Indenter->canBreak(PreviousNode->State))
1278
3.30M
      return;
1279
5.03M
    if (!NewLine && Indenter->mustBreak(PreviousNode->State))
1280
258k
      return;
1281
1282
4.78M
    StateNode *Node = new (Allocator.Allocate())
1283
4.78M
        StateNode(PreviousNode->State, NewLine, PreviousNode);
1284
4.78M
    if (!formatChildren(Node->State, NewLine, /*DryRun=*/true, Penalty))
1285
21
      return;
1286
1287
4.78M
    Penalty += Indenter->addTokenToState(Node->State, NewLine, true);
1288
1289
4.78M
    Queue->push(QueueItem(OrderedPenalty(Penalty, *Count), Node));
1290
4.78M
    ++(*Count);
1291
4.78M
  }
1292
1293
  /// Applies the best formatting by reconstructing the path in the
1294
  /// solution space that leads to \c Best.
1295
90.6k
  void reconstructPath(LineState &State, StateNode *Best) {
1296
90.6k
    llvm::SmallVector<StateNode *> Path;
1297
    // We do not need a break before the initial token.
1298
1.48M
    while (Best->Previous) {
1299
1.39M
      Path.push_back(Best);
1300
1.39M
      Best = Best->Previous;
1301
1.39M
    }
1302
1.39M
    for (const auto &Node : llvm::reverse(Path)) {
1303
1.39M
      unsigned Penalty = 0;
1304
1.39M
      formatChildren(State, Node->NewLine, /*DryRun=*/false, Penalty);
1305
1.39M
      Penalty += Indenter->addTokenToState(State, Node->NewLine, false);
1306
1307
1.39M
      LLVM_DEBUG({
1308
1.39M
        printLineState(Node->Previous->State);
1309
1.39M
        if (Node->NewLine) {
1310
1.39M
          llvm::dbgs() << "Penalty for placing "
1311
1.39M
                       << Node->Previous->State.NextToken->Tok.getName()
1312
1.39M
                       << " on a new line: " << Penalty << "\n";
1313
1.39M
        }
1314
1.39M
      });
1315
1.39M
    }
1316
90.6k
  }
1317
1318
  llvm::SpecificBumpPtrAllocator<StateNode> Allocator;
1319
};
1320
1321
} // anonymous namespace
1322
1323
unsigned UnwrappedLineFormatter::format(
1324
    const SmallVectorImpl<AnnotatedLine *> &Lines, bool DryRun,
1325
    int AdditionalIndent, bool FixBadIndentation, unsigned FirstStartColumn,
1326
3.06k
    unsigned NextStartColumn, unsigned LastStartColumn) {
1327
3.06k
  LineJoiner Joiner(Style, Keywords, Lines);
1328
1329
  // Try to look up already computed penalty in DryRun-mode.
1330
3.06k
  std::pair<const SmallVectorImpl<AnnotatedLine *> *, unsigned> CacheKey(
1331
3.06k
      &Lines, AdditionalIndent);
1332
3.06k
  auto CacheIt = PenaltyCache.find(CacheKey);
1333
3.06k
  if (DryRun && CacheIt != PenaltyCache.end())
1334
17
    return CacheIt->second;
1335
1336
3.04k
  assert(!Lines.empty());
1337
0
  unsigned Penalty = 0;
1338
3.04k
  LevelIndentTracker IndentTracker(Style, Keywords, Lines[0]->Level,
1339
3.04k
                                   AdditionalIndent);
1340
3.04k
  const AnnotatedLine *PrevPrevLine = nullptr;
1341
3.04k
  const AnnotatedLine *PreviousLine = nullptr;
1342
3.04k
  const AnnotatedLine *NextLine = nullptr;
1343
1344
  // The minimum level of consecutive lines that have been formatted.
1345
3.04k
  unsigned RangeMinLevel = UINT_MAX;
1346
1347
3.04k
  bool FirstLine = true;
1348
3.04k
  for (const AnnotatedLine *Line =
1349
3.04k
           Joiner.getNextMergedLine(DryRun, IndentTracker);
1350
426k
       Line; PrevPrevLine = PreviousLine, PreviousLine = Line, Line = NextLine,
1351
423k
                           FirstLine = false) {
1352
423k
    assert(Line->First);
1353
0
    const AnnotatedLine &TheLine = *Line;
1354
423k
    unsigned Indent = IndentTracker.getIndent();
1355
1356
    // We continue formatting unchanged lines to adjust their indent, e.g. if a
1357
    // scope was added. However, we need to carefully stop doing this when we
1358
    // exit the scope of affected lines to prevent indenting the entire
1359
    // remaining file if it currently missing a closing brace.
1360
423k
    bool PreviousRBrace =
1361
423k
        PreviousLine && PreviousLine->startsWith(tok::r_brace);
1362
423k
    bool ContinueFormatting =
1363
423k
        TheLine.Level > RangeMinLevel ||
1364
423k
        (TheLine.Level == RangeMinLevel && !PreviousRBrace &&
1365
309k
         !TheLine.startsWith(tok::r_brace));
1366
1367
423k
    bool FixIndentation = (FixBadIndentation || ContinueFormatting) &&
1368
423k
                          Indent != TheLine.First->OriginalColumn;
1369
423k
    bool ShouldFormat = TheLine.Affected || FixIndentation;
1370
    // We cannot format this line; if the reason is that the line had a
1371
    // parsing error, remember that.
1372
423k
    if (ShouldFormat && TheLine.Type == LT_Invalid && Status) {
1373
0
      Status->FormatComplete = false;
1374
0
      Status->Line =
1375
0
          SourceMgr.getSpellingLineNumber(TheLine.First->Tok.getLocation());
1376
0
    }
1377
1378
423k
    if (ShouldFormat && TheLine.Type != LT_Invalid) {
1379
409k
      if (!DryRun) {
1380
409k
        bool LastLine = TheLine.First->is(tok::eof);
1381
409k
        formatFirstToken(TheLine, PreviousLine, PrevPrevLine, Lines, Indent,
1382
409k
                         LastLine ? LastStartColumn : NextStartColumn + Indent);
1383
409k
      }
1384
1385
409k
      NextLine = Joiner.getNextMergedLine(DryRun, IndentTracker);
1386
409k
      unsigned ColumnLimit = getColumnLimit(TheLine.InPPDirective, NextLine);
1387
409k
      bool FitsIntoOneLine =
1388
409k
          !TheLine.ContainsMacroCall &&
1389
409k
          (TheLine.Last->TotalLength + Indent <= ColumnLimit ||
1390
409k
           (TheLine.Type == LT_ImportStatement &&
1391
91.5k
            (!Style.isJavaScript() || !Style.JavaScriptWrapImports)) ||
1392
409k
           (Style.isCSharp() &&
1393
91.3k
            TheLine.InPPDirective)); // don't split #regions in C#
1394
409k
      if (Style.ColumnLimit == 0) {
1395
0
        NoColumnLimitLineFormatter(Indenter, Whitespaces, Style, this)
1396
0
            .formatLine(TheLine, NextStartColumn + Indent,
1397
0
                        FirstLine ? FirstStartColumn : 0, DryRun);
1398
409k
      } else if (FitsIntoOneLine) {
1399
318k
        Penalty += NoLineBreakFormatter(Indenter, Whitespaces, Style, this)
1400
318k
                       .formatLine(TheLine, NextStartColumn + Indent,
1401
318k
                                   FirstLine ? FirstStartColumn : 0, DryRun);
1402
318k
      } else {
1403
91.3k
        Penalty += OptimizingLineFormatter(Indenter, Whitespaces, Style, this)
1404
91.3k
                       .formatLine(TheLine, NextStartColumn + Indent,
1405
91.3k
                                   FirstLine ? FirstStartColumn : 0, DryRun);
1406
91.3k
      }
1407
409k
      RangeMinLevel = std::min(RangeMinLevel, TheLine.Level);
1408
409k
    } else {
1409
      // If no token in the current line is affected, we still need to format
1410
      // affected children.
1411
13.6k
      if (TheLine.ChildrenAffected) {
1412
2.34M
        for (const FormatToken *Tok = TheLine.First; Tok; Tok = Tok->Next)
1413
2.34M
          if (!Tok->Children.empty())
1414
2.68k
            format(Tok->Children, DryRun);
1415
2.01k
      }
1416
1417
      // Adapt following lines on the current indent level to the same level
1418
      // unless the current \c AnnotatedLine is not at the beginning of a line.
1419
13.6k
      bool StartsNewLine =
1420
13.6k
          TheLine.First->NewlinesBefore > 0 || TheLine.First->IsFirst;
1421
13.6k
      if (StartsNewLine)
1422
3.67k
        IndentTracker.adjustToUnmodifiedLine(TheLine);
1423
13.6k
      if (!DryRun) {
1424
13.6k
        bool ReformatLeadingWhitespace =
1425
13.6k
            StartsNewLine && ((PreviousLine && PreviousLine->Affected) ||
1426
3.67k
                              TheLine.LeadingEmptyLinesAffected);
1427
        // Format the first token.
1428
13.6k
        if (ReformatLeadingWhitespace) {
1429
3.67k
          formatFirstToken(TheLine, PreviousLine, PrevPrevLine, Lines,
1430
3.67k
                           TheLine.First->OriginalColumn,
1431
3.67k
                           TheLine.First->OriginalColumn);
1432
10.0k
        } else {
1433
10.0k
          Whitespaces->addUntouchableToken(*TheLine.First,
1434
10.0k
                                           TheLine.InPPDirective);
1435
10.0k
        }
1436
1437
        // Notify the WhitespaceManager about the unchanged whitespace.
1438
13.6M
        for (FormatToken *Tok = TheLine.First->Next; Tok; Tok = Tok->Next)
1439
13.6M
          Whitespaces->addUntouchableToken(*Tok, TheLine.InPPDirective);
1440
13.6k
      }
1441
13.6k
      NextLine = Joiner.getNextMergedLine(DryRun, IndentTracker);
1442
13.6k
      RangeMinLevel = UINT_MAX;
1443
13.6k
    }
1444
423k
    if (!DryRun)
1445
422k
      markFinalized(TheLine.First);
1446
423k
  }
1447
3.04k
  PenaltyCache[CacheKey] = Penalty;
1448
3.04k
  return Penalty;
1449
3.06k
}
1450
1451
static auto computeNewlines(const AnnotatedLine &Line,
1452
                            const AnnotatedLine *PreviousLine,
1453
                            const AnnotatedLine *PrevPrevLine,
1454
                            const SmallVectorImpl<AnnotatedLine *> &Lines,
1455
398k
                            const FormatStyle &Style) {
1456
398k
  const auto &RootToken = *Line.First;
1457
398k
  auto Newlines =
1458
398k
      std::min(RootToken.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1);
1459
  // Remove empty lines before "}" where applicable.
1460
398k
  if (RootToken.is(tok::r_brace) &&
1461
398k
      (!RootToken.Next ||
1462
87.0k
       (RootToken.Next->is(tok::semi) && !RootToken.Next->Next)) &&
1463
      // Do not remove empty lines before namespace closing "}".
1464
398k
      !getNamespaceToken(&Line, Lines)) {
1465
86.8k
    Newlines = std::min(Newlines, 1u);
1466
86.8k
  }
1467
  // Remove empty lines at the start of nested blocks (lambdas/arrow functions)
1468
398k
  if (!PreviousLine && Line.Level > 0)
1469
1.27k
    Newlines = std::min(Newlines, 1u);
1470
398k
  if (Newlines == 0 && !RootToken.IsFirst)
1471
243k
    Newlines = 1;
1472
398k
  if (RootToken.IsFirst && !RootToken.HasUnescapedNewline)
1473
323
    Newlines = 0;
1474
1475
  // Remove empty lines after "{".
1476
398k
  if (!Style.KeepEmptyLinesAtTheStartOfBlocks && PreviousLine &&
1477
398k
      PreviousLine->Last->is(tok::l_brace) &&
1478
398k
      !PreviousLine->startsWithNamespace() &&
1479
398k
      !(PrevPrevLine && PrevPrevLine->startsWithNamespace() &&
1480
82.1k
        PreviousLine->startsWith(tok::l_brace)) &&
1481
398k
      !startsExternCBlock(*PreviousLine)) {
1482
82.1k
    Newlines = 1;
1483
82.1k
  }
1484
1485
  // Insert or remove empty line before access specifiers.
1486
398k
  if (PreviousLine && RootToken.isAccessSpecifier()) {
1487
0
    switch (Style.EmptyLineBeforeAccessModifier) {
1488
0
    case FormatStyle::ELBAMS_Never:
1489
0
      if (Newlines > 1)
1490
0
        Newlines = 1;
1491
0
      break;
1492
0
    case FormatStyle::ELBAMS_Leave:
1493
0
      Newlines = std::max(RootToken.NewlinesBefore, 1u);
1494
0
      break;
1495
0
    case FormatStyle::ELBAMS_LogicalBlock:
1496
0
      if (PreviousLine->Last->isOneOf(tok::semi, tok::r_brace) && Newlines <= 1)
1497
0
        Newlines = 2;
1498
0
      if (PreviousLine->First->isAccessSpecifier())
1499
0
        Newlines = 1; // Previous is an access modifier remove all new lines.
1500
0
      break;
1501
0
    case FormatStyle::ELBAMS_Always: {
1502
0
      const FormatToken *previousToken;
1503
0
      if (PreviousLine->Last->is(tok::comment))
1504
0
        previousToken = PreviousLine->Last->getPreviousNonComment();
1505
0
      else
1506
0
        previousToken = PreviousLine->Last;
1507
0
      if ((!previousToken || previousToken->isNot(tok::l_brace)) &&
1508
0
          Newlines <= 1) {
1509
0
        Newlines = 2;
1510
0
      }
1511
0
    } break;
1512
0
    }
1513
0
  }
1514
1515
  // Insert or remove empty line after access specifiers.
1516
398k
  if (PreviousLine && PreviousLine->First->isAccessSpecifier() &&
1517
398k
      (!PreviousLine->InPPDirective || !RootToken.HasUnescapedNewline)) {
1518
    // EmptyLineBeforeAccessModifier is handling the case when two access
1519
    // modifiers follow each other.
1520
0
    if (!RootToken.isAccessSpecifier()) {
1521
0
      switch (Style.EmptyLineAfterAccessModifier) {
1522
0
      case FormatStyle::ELAAMS_Never:
1523
0
        Newlines = 1;
1524
0
        break;
1525
0
      case FormatStyle::ELAAMS_Leave:
1526
0
        Newlines = std::max(Newlines, 1u);
1527
0
        break;
1528
0
      case FormatStyle::ELAAMS_Always:
1529
0
        if (RootToken.is(tok::r_brace)) // Do not add at end of class.
1530
0
          Newlines = 1u;
1531
0
        else
1532
0
          Newlines = std::max(Newlines, 2u);
1533
0
        break;
1534
0
      }
1535
0
    }
1536
0
  }
1537
1538
398k
  return Newlines;
1539
398k
}
1540
1541
void UnwrappedLineFormatter::formatFirstToken(
1542
    const AnnotatedLine &Line, const AnnotatedLine *PreviousLine,
1543
    const AnnotatedLine *PrevPrevLine,
1544
    const SmallVectorImpl<AnnotatedLine *> &Lines, unsigned Indent,
1545
412k
    unsigned NewlineIndent) {
1546
412k
  FormatToken &RootToken = *Line.First;
1547
412k
  if (RootToken.is(tok::eof)) {
1548
351
    unsigned Newlines =
1549
351
        std::min(RootToken.NewlinesBefore,
1550
351
                 Style.KeepEmptyLinesAtEOF ? Style.MaxEmptyLinesToKeep + 1 : 1);
1551
351
    unsigned TokenIndent = Newlines ? NewlineIndent : 0;
1552
351
    Whitespaces->replaceWhitespace(RootToken, Newlines, TokenIndent,
1553
351
                                   TokenIndent);
1554
351
    return;
1555
351
  }
1556
1557
412k
  if (RootToken.Newlines < 0) {
1558
398k
    RootToken.Newlines =
1559
398k
        computeNewlines(Line, PreviousLine, PrevPrevLine, Lines, Style);
1560
398k
    assert(RootToken.Newlines >= 0);
1561
398k
  }
1562
1563
412k
  if (RootToken.Newlines > 0)
1564
412k
    Indent = NewlineIndent;
1565
1566
  // Preprocessor directives get indented before the hash only if specified. In
1567
  // Javascript import statements are indented like normal statements.
1568
412k
  if (!Style.isJavaScript() &&
1569
412k
      Style.IndentPPDirectives != FormatStyle::PPDIS_BeforeHash &&
1570
412k
      (Line.Type == LT_PreprocessorDirective ||
1571
412k
       Line.Type == LT_ImportStatement)) {
1572
84.7k
    Indent = 0;
1573
84.7k
  }
1574
1575
412k
  Whitespaces->replaceWhitespace(RootToken, RootToken.Newlines, Indent, Indent,
1576
412k
                                 /*IsAligned=*/false,
1577
412k
                                 Line.InPPDirective &&
1578
412k
                                     !RootToken.HasUnescapedNewline);
1579
412k
}
1580
1581
unsigned
1582
UnwrappedLineFormatter::getColumnLimit(bool InPPDirective,
1583
409k
                                       const AnnotatedLine *NextLine) const {
1584
  // In preprocessor directives reserve two chars for trailing " \" if the
1585
  // next line continues the preprocessor directive.
1586
409k
  bool ContinuesPPDirective =
1587
409k
      InPPDirective &&
1588
      // If there is no next line, this is likely a child line and the parent
1589
      // continues the preprocessor directive.
1590
409k
      (!NextLine ||
1591
84.7k
       (NextLine->InPPDirective &&
1592
        // If there is an unescaped newline between this line and the next, the
1593
        // next line starts a new preprocessor directive.
1594
84.7k
        !NextLine->First->HasUnescapedNewline));
1595
409k
  return Style.ColumnLimit - (ContinuesPPDirective ? 2 : 0);
1596
409k
}
1597
1598
} // namespace format
1599
} // namespace clang