Coverage Report

Created: 2021-09-21 08:58

/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
4.67k
bool startsExternCBlock(const AnnotatedLine &Line) {
23
4.67k
  const FormatToken *Next = Line.First->getNextNonComment();
24
4.67k
  const FormatToken *NextNext = Next ? 
Next->getNextNonComment()4.20k
:
nullptr477
;
25
4.67k
  return Line.startsWith(tok::kw_extern) && 
Next40
&&
Next->isStringLiteral()40
&&
26
4.67k
         
NextNext40
&&
NextNext->is(tok::l_brace)40
;
27
4.67k
}
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
20.2k
      : Style(Style), Keywords(Keywords), AdditionalIndent(AdditionalIndent) {
44
22.3k
    for (unsigned i = 0; i != StartLevel; 
++i2.03k
)
45
2.03k
      IndentForLevel.push_back(Style.IndentWidth * i + AdditionalIndent);
46
20.2k
  }
47
48
  /// Returns the indent for the current line.
49
133k
  unsigned getIndent() const { return Indent; }
50
51
  /// Update the indent state given that \p Line is going to be formatted
52
  /// next.
53
66.5k
  void nextLine(const AnnotatedLine &Line) {
54
66.5k
    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
93.0k
    while (IndentForLevel.size() <= Line.Level)
58
26.4k
      IndentForLevel.push_back(-1);
59
66.5k
    if (Line.InPPDirective) {
60
3.84k
      unsigned IndentWidth =
61
3.84k
          (Style.PPIndentWidth >= 0) ? 
Style.PPIndentWidth27
:
Style.IndentWidth3.81k
;
62
3.84k
      Indent = Line.Level * IndentWidth + AdditionalIndent;
63
62.6k
    } else {
64
62.6k
      IndentForLevel.resize(Line.Level + 1);
65
62.6k
      Indent = getIndent(IndentForLevel, Line.Level);
66
62.6k
    }
67
66.5k
    if (static_cast<int>(Indent) + Offset >= 0)
68
66.5k
      Indent += Offset;
69
66.5k
    if (Line.First->is(TT_CSharpGenericTypeConstraint))
70
12
      Indent = Line.Level * Style.IndentWidth + Style.ContinuationIndentWidth;
71
66.5k
  }
72
73
  /// Update the indent state given that \p Line indent should be
74
  /// skipped.
75
19
  void skipLine(const AnnotatedLine &Line) {
76
22
    while (IndentForLevel.size() <= Line.Level)
77
3
      IndentForLevel.push_back(Indent);
78
19
  }
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
66.5k
  int getIndentOffset(const FormatToken &RootToken) {
100
66.5k
    if (Style.Language == FormatStyle::LK_Java ||
101
66.5k
        
Style.Language == FormatStyle::LK_JavaScript65.5k
||
Style.isCSharp()61.2k
)
102
7.47k
      return 0;
103
59.0k
    if (RootToken.isAccessSpecifier(false) ||
104
59.0k
        
RootToken.isObjCAccessSpecifier()58.3k
||
105
59.0k
        
(58.3k
RootToken.isOneOf(Keywords.kw_signals, Keywords.kw_qsignals)58.3k
&&
106
58.3k
         
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
58.3k
    return 0;
114
59.0k
  }
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
77.3k
  unsigned getIndent(ArrayRef<int> IndentForLevel, unsigned Level) {
122
77.3k
    if (IndentForLevel[Level] != -1)
123
8.62k
      return IndentForLevel[Level];
124
68.7k
    if (Level == 0)
125
54.0k
      return 0;
126
14.6k
    return getIndent(IndentForLevel, Level - 1) + Style.IndentWidth;
127
68.7k
  }
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
65
    const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines) {
149
65
  if (!Line->startsWith(tok::r_brace))
150
26
    return nullptr;
151
39
  size_t StartLineIndex = Line->MatchingOpeningBlockLineIndex;
152
39
  if (StartLineIndex == UnwrappedLine::kInvalidIndex)
153
0
    return nullptr;
154
39
  assert(StartLineIndex < AnnotatedLines.size());
155
0
  return AnnotatedLines[StartLineIndex]->First->getNamespaceToken();
156
39
}
157
158
51
StringRef getNamespaceTokenText(const AnnotatedLine *Line) {
159
51
  const FormatToken *NamespaceToken = Line->First->getNamespaceToken();
160
51
  return NamespaceToken ? 
NamespaceToken->TokenText26
:
StringRef()25
;
161
51
}
162
163
StringRef getMatchingNamespaceTokenText(
164
    const AnnotatedLine *Line,
165
39
    const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines) {
166
39
  const FormatToken *NamespaceToken =
167
39
      getMatchingNamespaceToken(Line, AnnotatedLines);
168
39
  return NamespaceToken ? 
NamespaceToken->TokenText21
:
StringRef()18
;
169
39
}
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
20.8k
        AnnotatedLines(Lines) {}
177
178
  /// Returns the next line, merging multiple lines into one if possible.
179
  const AnnotatedLine *getNextMergedLine(bool DryRun,
180
86.8k
                                         LevelIndentTracker &IndentTracker) {
181
86.8k
    if (Next == End)
182
20.2k
      return nullptr;
183
66.5k
    const AnnotatedLine *Current = *Next;
184
66.5k
    IndentTracker.nextLine(*Current);
185
66.5k
    unsigned MergedLines = tryFitMultipleLinesInOne(IndentTracker, Next, End);
186
66.5k
    if (MergedLines > 0 && 
Style.ColumnLimit == 05.04k
)
187
      // Disallow line merging if there is a break at the start of one of the
188
      // input lines.
189
91
      
for (unsigned i = 0; 39
i < MergedLines;
++i52
)
190
52
        if (Next[i + 1]->First->NewlinesBefore > 0)
191
2
          MergedLines = 0;
192
66.5k
    if (!DryRun)
193
71.1k
      
for (unsigned i = 0; 64.5k
i < MergedLines;
++i6.53k
)
194
6.53k
        join(*Next[0], *Next[i + 1]);
195
66.5k
    Next = Next + MergedLines + 1;
196
66.5k
    return Current;
197
86.8k
  }
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
66.5k
                           SmallVectorImpl<AnnotatedLine *>::const_iterator E) {
205
66.5k
    const unsigned Indent = IndentTracker.getIndent();
206
207
    // Can't join the last line with anything.
208
66.5k
    if (I + 1 == E)
209
20.2k
      return 0;
210
    // We can never merge stuff if there are trailing line comments.
211
46.2k
    const AnnotatedLine *TheLine = *I;
212
46.2k
    if (TheLine->Last->is(TT_LineComment))
213
2.27k
      return 0;
214
43.9k
    if (I[1]->Type == LT_Invalid || 
I[1]->First->MustBreakBefore43.9k
)
215
774
      return 0;
216
43.2k
    if (TheLine->InPPDirective &&
217
43.2k
        
(3.11k
!I[1]->InPPDirective3.11k
||
I[1]->First->HasUnescapedNewline1.76k
))
218
1.99k
      return 0;
219
220
41.2k
    if (Style.ColumnLimit > 0 && 
Indent > Style.ColumnLimit39.9k
)
221
0
      return 0;
222
223
41.2k
    unsigned Limit =
224
41.2k
        Style.ColumnLimit == 0 ? UINT_MAX : 
Style.ColumnLimit - Indent39.9k
;
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
41.2k
    Limit = TheLine->Last->TotalLength > Limit
228
41.2k
                ? 
05.55k
229
41.2k
                : 
Limit - TheLine->Last->TotalLength35.6k
;
230
231
41.2k
    if (TheLine->Last->is(TT_FunctionLBrace) &&
232
41.2k
        
TheLine->First == TheLine->Last4.30k
&&
233
41.2k
        
!Style.BraceWrapping.SplitEmptyFunction430
&&
234
41.2k
        
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
41.2k
    if (TheLine->Last->is(tok::l_brace) && 
TheLine->First == TheLine->Last10.6k
&&
239
41.2k
        
I != AnnotatedLines.begin()1.27k
) {
240
1.14k
      bool EmptyBlock = I[1]->First->is(tok::r_brace);
241
242
1.14k
      const FormatToken *Tok = I[-1]->First;
243
1.14k
      if (Tok && Tok->is(tok::comment))
244
20
        Tok = Tok->getNextNonComment();
245
246
1.14k
      if (Tok && 
Tok->getNamespaceToken()1.14k
)
247
63
        return !Style.BraceWrapping.SplitEmptyNamespace && 
EmptyBlock18
248
63
                   ? 
tryMergeSimpleBlock(I, E, Limit)15
249
63
                   : 
048
;
250
251
1.08k
      if (Tok && 
Tok->is(tok::kw_typedef)1.07k
)
252
18
        Tok = Tok->getNextNonComment();
253
1.08k
      if (Tok && Tok->isOneOf(tok::kw_class, tok::kw_struct, tok::kw_union,
254
1.07k
                              tok::kw_extern, Keywords.kw_interface))
255
153
        return !Style.BraceWrapping.SplitEmptyRecord && 
EmptyBlock60
256
153
                   ? 
tryMergeSimpleBlock(I, E, Limit)30
257
153
                   : 
0123
;
258
259
929
      if (Tok && 
Tok->is(tok::kw_template)926
&&
260
929
          
Style.BraceWrapping.SplitEmptyRecord66
&&
EmptyBlock60
) {
261
9
        return 0;
262
9
      }
263
929
    }
264
265
    // FIXME: TheLine->Level != 0 might or might not be the right check to do.
266
    // If necessary, change to something smarter.
267
40.9k
    bool MergeShortFunctions =
268
40.9k
        Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_All ||
269
40.9k
        
(6.97k
Style.AllowShortFunctionsOnASingleLine >= FormatStyle::SFS_Empty6.97k
&&
270
6.97k
         
I[1]->First->is(tok::r_brace)5.62k
) ||
271
40.9k
        
(5.89k
Style.AllowShortFunctionsOnASingleLine & FormatStyle::SFS_InlineOnly5.89k
&&
272
5.89k
         
TheLine->Level != 0281
);
273
274
40.9k
    if (Style.CompactNamespaces) {
275
58
      if (auto nsToken = TheLine->First->getNamespaceToken()) {
276
32
        int i = 0;
277
32
        unsigned closingLine = TheLine->MatchingClosingBlockLineIndex - 1;
278
51
        for (; I + 1 + i != E &&
279
51
               nsToken->TokenText == getNamespaceTokenText(I[i + 1]) &&
280
51
               
closingLine == I[i + 1]->MatchingClosingBlockLineIndex23
&&
281
51
               
I[i + 1]->Last->TotalLength < Limit21
;
282
32
             
i++, closingLine--19
) {
283
          // No extra indent for compacted namespaces
284
19
          IndentTracker.skipLine(*I[i + 1]);
285
286
19
          Limit -= I[i + 1]->Last->TotalLength;
287
19
        }
288
32
        return i;
289
32
      }
290
291
26
      if (auto nsToken = getMatchingNamespaceToken(TheLine, AnnotatedLines)) {
292
18
        int i = 0;
293
18
        unsigned openingLine = TheLine->MatchingOpeningBlockLineIndex - 1;
294
39
        for (; I + 1 + i != E &&
295
39
               nsToken->TokenText ==
296
39
                   getMatchingNamespaceTokenText(I[i + 1], AnnotatedLines) &&
297
39
               
openingLine == I[i + 1]->MatchingOpeningBlockLineIndex21
;
298
21
             i++, openingLine--) {
299
          // No space between consecutive braces
300
21
          I[i + 1]->First->SpacesRequiredBefore = !I[i]->Last->is(tok::r_brace);
301
302
          // Indent like the outer-most namespace
303
21
          IndentTracker.nextLine(*I[i + 1]);
304
21
        }
305
18
        return i;
306
18
      }
307
26
    }
308
309
    // Try to merge a function block with left brace unwrapped
310
40.9k
    if (TheLine->Last->is(TT_FunctionLBrace) &&
311
40.9k
        
TheLine->First != TheLine->Last4.28k
) {
312
3.87k
      return MergeShortFunctions ? 
tryMergeSimpleBlock(I, E, Limit)3.53k
:
0338
;
313
3.87k
    }
314
    // Try to merge a control statement block with left brace unwrapped
315
37.0k
    if (TheLine->Last->is(tok::l_brace) && 
TheLine->First != TheLine->Last6.49k
&&
316
37.0k
        
TheLine->First->isOneOf(tok::kw_if, tok::kw_while, tok::kw_for)5.44k
) {
317
859
      return Style.AllowShortBlocksOnASingleLine != FormatStyle::SBS_Never
318
859
                 ? 
tryMergeSimpleBlock(I, E, Limit)113
319
859
                 : 
0746
;
320
859
    }
321
    // Try to merge a control statement block with left brace wrapped
322
36.1k
    if (I[1]->First->is(tok::l_brace) &&
323
36.1k
        
(1.29k
TheLine->First->isOneOf(tok::kw_if, tok::kw_while, tok::kw_for,
324
1.29k
                                 tok::kw_switch, tok::kw_try, tok::kw_do,
325
1.29k
                                 TT_ForEachMacro) ||
326
1.29k
         
(993
TheLine->First->is(tok::r_brace)993
&&
TheLine->First->Next22
&&
327
993
          
TheLine->First->Next->isOneOf(tok::kw_else, tok::kw_catch)22
)) &&
328
36.1k
        Style.BraceWrapping.AfterControlStatement ==
329
326
            FormatStyle::BWACS_MultiLine) {
330
      // If possible, merge the next line's wrapped left brace with the current
331
      // line. Otherwise, leave it on the next line, as this is a multi-line
332
      // control statement.
333
32
      return (Style.ColumnLimit == 0 ||
334
32
              TheLine->Last->TotalLength <= Style.ColumnLimit)
335
32
                 ? 
123
336
32
                 : 
09
;
337
36.1k
    } else if (I[1]->First->is(tok::l_brace) &&
338
36.1k
               TheLine->First->isOneOf(tok::kw_if, tok::kw_while,
339
1.26k
                                       tok::kw_for)) {
340
226
      return (Style.BraceWrapping.AfterControlStatement ==
341
226
              FormatStyle::BWACS_Always)
342
226
                 ? tryMergeSimpleBlock(I, E, Limit)
343
226
                 : 
00
;
344
35.9k
    } else if (I[1]->First->is(tok::l_brace) &&
345
35.9k
               
TheLine->First->isOneOf(tok::kw_else, tok::kw_catch)1.03k
&&
346
35.9k
               Style.BraceWrapping.AfterControlStatement ==
347
30
                   FormatStyle::BWACS_MultiLine) {
348
      // This case if different from the upper BWACS_MultiLine processing
349
      // in that a preceding r_brace is not on the same line as else/catch
350
      // most likely because of BeforeElse/BeforeCatch set to true.
351
      // If the line length doesn't fit ColumnLimit, leave l_brace on the
352
      // next line to respect the BWACS_MultiLine.
353
3
      return (Style.ColumnLimit == 0 ||
354
3
              TheLine->Last->TotalLength <= Style.ColumnLimit)
355
3
                 ? 
12
356
3
                 : 
01
;
357
3
    }
358
    // Don't merge block with left brace wrapped after ObjC special blocks
359
35.9k
    if (TheLine->First->is(tok::l_brace) && 
I != AnnotatedLines.begin()1.05k
&&
360
35.9k
        
I[-1]->First->is(tok::at)925
&&
I[-1]->First->Next17
) {
361
17
      tok::ObjCKeywordKind kwId = I[-1]->First->Next->Tok.getObjCKeywordID();
362
17
      if (kwId == clang::tok::objc_autoreleasepool ||
363
17
          
kwId == clang::tok::objc_synchronized13
)
364
8
        return 0;
365
17
    }
366
    // Don't merge block with left brace wrapped after case labels
367
35.9k
    if (TheLine->First->is(tok::l_brace) && 
I != AnnotatedLines.begin()1.04k
&&
368
35.9k
        
I[-1]->First->isOneOf(tok::kw_case, tok::kw_default)917
)
369
50
      return 0;
370
371
    // Don't merge an empty template class or struct if SplitEmptyRecords
372
    // is defined.
373
35.8k
    if (Style.BraceWrapping.SplitEmptyRecord &&
374
35.8k
        
TheLine->Last->is(tok::l_brace)35.3k
&&
I != AnnotatedLines.begin()5.48k
&&
375
35.8k
        
I[-1]->Last3.61k
) {
376
3.61k
      const FormatToken *Previous = I[-1]->Last;
377
3.61k
      if (Previous) {
378
3.61k
        if (Previous->is(tok::comment))
379
276
          Previous = Previous->getPreviousNonComment();
380
3.61k
        if (Previous) {
381
3.55k
          if (Previous->is(tok::greater) && 
!I[-1]->InPPDirective24
)
382
17
            return 0;
383
3.53k
          if (Previous->is(tok::identifier)) {
384
272
            const FormatToken *PreviousPrevious =
385
272
                Previous->getPreviousNonComment();
386
272
            if (PreviousPrevious &&
387
272
                
PreviousPrevious->isOneOf(tok::kw_class, tok::kw_struct)269
)
388
40
              return 0;
389
272
          }
390
3.53k
        }
391
3.61k
      }
392
3.61k
    }
393
394
    // Try to merge a block with left brace wrapped that wasn't yet covered
395
35.8k
    if (TheLine->Last->is(tok::l_brace)) {
396
5.52k
      return !Style.BraceWrapping.AfterFunction ||
397
5.52k
                     
(863
I[1]->First->is(tok::r_brace)863
&&
398
863
                      
!Style.BraceWrapping.SplitEmptyRecord117
)
399
5.52k
                 ? 
tryMergeSimpleBlock(I, E, Limit)4.66k
400
5.52k
                 : 
0860
;
401
5.52k
    }
402
    // Try to merge a function block with left brace wrapped
403
30.2k
    if (I[1]->First->is(TT_FunctionLBrace) &&
404
30.2k
        
Style.BraceWrapping.AfterFunction511
) {
405
511
      if (I[1]->Last->is(TT_LineComment))
406
6
        return 0;
407
408
      // Check for Limit <= 2 to account for the " {".
409
505
      if (Limit <= 2 || 
(440
Style.ColumnLimit == 0440
&&
containsMustBreak(TheLine)97
))
410
84
        return 0;
411
421
      Limit -= 2;
412
413
421
      unsigned MergedLines = 0;
414
421
      if (MergeShortFunctions ||
415
421
          
(233
Style.AllowShortFunctionsOnASingleLine >= FormatStyle::SFS_Empty233
&&
416
233
           
I[1]->First == I[1]->Last90
&&
I + 2 != E90
&&
417
233
           
I[2]->First->is(tok::r_brace)90
)) {
418
206
        MergedLines = tryMergeSimpleBlock(I + 1, E, Limit);
419
        // If we managed to merge the block, count the function header, which is
420
        // on a separate line.
421
206
        if (MergedLines > 0)
422
126
          ++MergedLines;
423
206
      }
424
421
      return MergedLines;
425
505
    }
426
29.7k
    auto IsElseLine = [&TheLine]() -> bool {
427
29.0k
      const FormatToken *First = TheLine->First;
428
29.0k
      if (First->is(tok::kw_else))
429
289
        return true;
430
431
28.8k
      return First->is(tok::r_brace) && 
First->Next5.58k
&&
432
28.8k
             
First->Next->is(tok::kw_else)1.78k
;
433
29.0k
    };
434
29.7k
    if (TheLine->First->is(tok::kw_if) ||
435
29.7k
        
(29.0k
IsElseLine()29.0k
&& (Style.AllowShortIfStatementsOnASingleLine ==
436
823
                          FormatStyle::SIS_AllIfsAndElse))) {
437
823
      return Style.AllowShortIfStatementsOnASingleLine
438
823
                 ? 
tryMergeSimpleControlStatement(I, E, Limit)536
439
823
                 : 
0287
;
440
823
    }
441
28.9k
    if (TheLine->First->isOneOf(tok::kw_for, tok::kw_while, tok::kw_do)) {
442
190
      return Style.AllowShortLoopsOnASingleLine
443
190
                 ? 
tryMergeSimpleControlStatement(I, E, Limit)52
444
190
                 : 
0138
;
445
190
    }
446
28.7k
    if (TheLine->First->isOneOf(tok::kw_case, tok::kw_default)) {
447
337
      return Style.AllowShortCaseLabelsOnASingleLine
448
337
                 ? 
tryMergeShortCaseLabels(I, E, Limit)87
449
337
                 : 
0250
;
450
337
    }
451
28.4k
    if (TheLine->InPPDirective &&
452
28.4k
        
(1.03k
TheLine->First->HasUnescapedNewline1.03k
||
TheLine->First->IsFirst563
)) {
453
818
      return tryMergeSimplePPDirective(I, E, Limit);
454
818
    }
455
27.6k
    return 0;
456
28.4k
  }
457
458
  unsigned
459
  tryMergeSimplePPDirective(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
460
                            SmallVectorImpl<AnnotatedLine *>::const_iterator E,
461
818
                            unsigned Limit) {
462
818
    if (Limit == 0)
463
3
      return 0;
464
815
    if (I + 2 != E && I[2]->InPPDirective && 
!I[2]->First->HasUnescapedNewline388
)
465
157
      return 0;
466
658
    if (1 + I[1]->Last->TotalLength > Limit)
467
70
      return 0;
468
588
    return 1;
469
658
  }
470
471
  unsigned tryMergeSimpleControlStatement(
472
      SmallVectorImpl<AnnotatedLine *>::const_iterator I,
473
588
      SmallVectorImpl<AnnotatedLine *>::const_iterator E, unsigned Limit) {
474
588
    if (Limit == 0)
475
10
      return 0;
476
578
    if (Style.BraceWrapping.AfterControlStatement ==
477
578
            FormatStyle::BWACS_Always &&
478
578
        
I[1]->First->is(tok::l_brace)12
&&
479
578
        
Style.AllowShortBlocksOnASingleLine == FormatStyle::SBS_Never0
)
480
0
      return 0;
481
578
    if (I[1]->InPPDirective != (*I)->InPPDirective ||
482
578
        
(575
I[1]->InPPDirective575
&&
I[1]->First->HasUnescapedNewline21
))
483
3
      return 0;
484
575
    Limit = limitConsideringMacros(I + 1, E, Limit);
485
575
    AnnotatedLine &Line = **I;
486
575
    if (!Line.First->is(tok::kw_do) && 
!Line.First->is(tok::kw_else)566
&&
487
575
        
!Line.Last->is(tok::kw_else)476
&&
Line.Last->isNot(tok::r_paren)449
)
488
34
      return 0;
489
    // Only merge do while if do is the only statement on the line.
490
541
    if (Line.First->is(tok::kw_do) && 
!Line.Last->is(tok::kw_do)9
)
491
3
      return 0;
492
538
    if (1 + I[1]->Last->TotalLength > Limit)
493
15
      return 0;
494
523
    if (I[1]->First->isOneOf(tok::semi, tok::kw_if, tok::kw_for, tok::kw_while,
495
523
                             TT_LineComment))
496
66
      return 0;
497
    // Only inline simple if's (no nested if or else), unless specified
498
457
    if (Style.AllowShortIfStatementsOnASingleLine ==
499
457
        FormatStyle::SIS_WithoutElse) {
500
151
      if (I + 2 != E && 
Line.startsWith(tok::kw_if)139
&&
501
151
          
I[2]->First->is(tok::kw_else)135
)
502
62
        return 0;
503
151
    }
504
395
    return 1;
505
457
  }
506
507
  unsigned
508
  tryMergeShortCaseLabels(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
509
                          SmallVectorImpl<AnnotatedLine *>::const_iterator E,
510
87
                          unsigned Limit) {
511
87
    if (Limit == 0 || I + 1 == E ||
512
87
        I[1]->First->isOneOf(tok::kw_case, tok::kw_default))
513
12
      return 0;
514
75
    if (I[0]->Last->is(tok::l_brace) || I[1]->First->is(tok::l_brace))
515
2
      return 0;
516
73
    unsigned NumStmts = 0;
517
73
    unsigned Length = 0;
518
73
    bool EndsWithComment = false;
519
73
    bool InPPDirective = I[0]->InPPDirective;
520
73
    const unsigned Level = I[0]->Level;
521
155
    for (; NumStmts < 3; 
++NumStmts82
) {
522
155
      if (I + 1 + NumStmts == E)
523
0
        break;
524
155
      const AnnotatedLine *Line = I[1 + NumStmts];
525
155
      if (Line->InPPDirective != InPPDirective)
526
4
        break;
527
151
      if (Line->First->isOneOf(tok::kw_case, tok::kw_default, tok::r_brace))
528
43
        break;
529
108
      if (Line->First->isOneOf(tok::kw_if, tok::kw_for, tok::kw_switch,
530
108
                               tok::kw_while) ||
531
108
          
EndsWithComment105
)
532
11
        return 0;
533
97
      if (Line->First->is(tok::comment)) {
534
15
        if (Level != Line->Level)
535
7
          return 0;
536
8
        SmallVectorImpl<AnnotatedLine *>::const_iterator J = I + 2 + NumStmts;
537
8
        for (; J != E; 
++J0
) {
538
8
          Line = *J;
539
8
          if (Line->InPPDirective != InPPDirective)
540
1
            break;
541
7
          if (Line->First->isOneOf(tok::kw_case, tok::kw_default, tok::r_brace))
542
7
            break;
543
0
          if (Line->First->isNot(tok::comment) || Level != Line->Level)
544
0
            return 0;
545
0
        }
546
8
        break;
547
8
      }
548
82
      if (Line->Last->is(tok::comment))
549
21
        EndsWithComment = true;
550
82
      Length += I[1 + NumStmts]->Last->TotalLength + 1; // 1 for the space.
551
82
    }
552
55
    if (NumStmts == 0 || NumStmts == 3 || Length > Limit)
553
7
      return 0;
554
48
    return NumStmts;
555
55
  }
556
557
  unsigned
558
  tryMergeSimpleBlock(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
559
                      SmallVectorImpl<AnnotatedLine *>::const_iterator E,
560
8.89k
                      unsigned Limit) {
561
8.89k
    AnnotatedLine &Line = **I;
562
563
    // Don't merge ObjC @ keywords and methods.
564
    // FIXME: If an option to allow short exception handling clauses on a single
565
    // line is added, change this to not return for @try and friends.
566
8.89k
    if (Style.Language != FormatStyle::LK_Java &&
567
8.89k
        
Line.First->isOneOf(tok::at, tok::minus, tok::plus)8.73k
)
568
153
      return 0;
569
570
    // Check that the current line allows merging. This depends on whether we
571
    // are in a control flow statements as well as several style flags.
572
8.73k
    if (Line.First->isOneOf(tok::kw_else, tok::kw_case) ||
573
8.73k
        
(8.49k
Line.First->Next8.49k
&&
Line.First->Next->is(tok::kw_else)7.88k
))
574
453
      return 0;
575
    // default: in switch statement
576
8.28k
    if (Line.First->is(tok::kw_default)) {
577
28
      const FormatToken *Tok = Line.First->getNextNonComment();
578
28
      if (Tok && Tok->is(tok::colon))
579
26
        return 0;
580
28
    }
581
8.25k
    if (Line.First->isOneOf(tok::kw_if, tok::kw_while, tok::kw_do, tok::kw_try,
582
8.25k
                            tok::kw___try, tok::kw_catch, tok::kw___finally,
583
8.25k
                            tok::kw_for, tok::r_brace, Keywords.kw___except)) {
584
538
      if (Style.AllowShortBlocksOnASingleLine == FormatStyle::SBS_Never)
585
310
        return 0;
586
      // Don't merge when we can't except the case when
587
      // the control statement block is empty
588
228
      if (!Style.AllowShortIfStatementsOnASingleLine &&
589
228
          
Line.startsWith(tok::kw_if)65
&&
590
228
          
!Style.BraceWrapping.AfterControlStatement38
&&
591
228
          
!I[1]->First->is(tok::r_brace)20
)
592
14
        return 0;
593
214
      if (!Style.AllowShortIfStatementsOnASingleLine &&
594
214
          
Line.startsWith(tok::kw_if)51
&&
595
214
          Style.BraceWrapping.AfterControlStatement ==
596
24
              FormatStyle::BWACS_Always &&
597
214
          
I + 2 != E18
&&
!I[2]->First->is(tok::r_brace)18
)
598
12
        return 0;
599
202
      if (!Style.AllowShortLoopsOnASingleLine &&
600
202
          
Line.First->isOneOf(tok::kw_while, tok::kw_do, tok::kw_for)28
&&
601
202
          
!Style.BraceWrapping.AfterControlStatement27
&&
602
202
          
!I[1]->First->is(tok::r_brace)15
)
603
7
        return 0;
604
195
      if (!Style.AllowShortLoopsOnASingleLine &&
605
195
          
Line.First->isOneOf(tok::kw_while, tok::kw_do, tok::kw_for)21
&&
606
195
          Style.BraceWrapping.AfterControlStatement ==
607
20
              FormatStyle::BWACS_Always &&
608
195
          
I + 2 != E12
&&
!I[2]->First->is(tok::r_brace)12
)
609
6
        return 0;
610
      // FIXME: Consider an option to allow short exception handling clauses on
611
      // a single line.
612
      // FIXME: This isn't covered by tests.
613
      // FIXME: For catch, __except, __finally the first token on the line
614
      // is '}', so this isn't correct here.
615
189
      if (Line.First->isOneOf(tok::kw_try, tok::kw___try, tok::kw_catch,
616
189
                              Keywords.kw___except, tok::kw___finally))
617
0
        return 0;
618
189
    }
619
620
7.90k
    if (Line.Last->is(tok::l_brace)) {
621
7.81k
      FormatToken *Tok = I[1]->First;
622
7.81k
      if (Tok->is(tok::r_brace) && 
!Tok->MustBreakBefore2.72k
&&
623
7.81k
          
(2.72k
Tok->getNextNonComment() == nullptr2.72k
||
624
2.72k
           
Tok->getNextNonComment()->is(tok::semi)675
)) {
625
        // We merge empty blocks even if the line exceeds the column limit.
626
2.66k
        Tok->SpacesRequiredBefore = Style.SpaceInEmptyBlock ? 
14
:
02.65k
;
627
2.66k
        Tok->CanBreakBefore = true;
628
2.66k
        return 1;
629
5.15k
      } else if (Limit != 0 && 
!Line.startsWithNamespace()5.04k
&&
630
5.15k
                 
!startsExternCBlock(Line)4.00k
) {
631
        // We don't merge short records.
632
3.98k
        FormatToken *RecordTok = Line.First;
633
        // Skip record modifiers.
634
4.07k
        while (RecordTok->Next &&
635
4.07k
               RecordTok->isOneOf(tok::kw_typedef, tok::kw_export,
636
3.63k
                                  Keywords.kw_declare, Keywords.kw_abstract,
637
3.63k
                                  tok::kw_default, Keywords.kw_override,
638
3.63k
                                  tok::kw_public, tok::kw_private,
639
3.63k
                                  tok::kw_protected, Keywords.kw_internal))
640
97
          RecordTok = RecordTok->Next;
641
3.98k
        if (RecordTok &&
642
3.98k
            RecordTok->isOneOf(tok::kw_class, tok::kw_union, tok::kw_struct,
643
3.98k
                               Keywords.kw_interface))
644
1.31k
          return 0;
645
646
        // Check that we still have three lines and they fit into the limit.
647
2.66k
        if (I + 2 == E || 
I[2]->Type == LT_Invalid2.66k
)
648
4
          return 0;
649
2.66k
        Limit = limitConsideringMacros(I + 2, E, Limit);
650
651
2.66k
        if (!nextTwoLinesFitInto(I, Limit))
652
550
          return 0;
653
654
        // Second, check that the next line does not contain any braces - if it
655
        // does, readability declines when putting it into a single line.
656
2.11k
        if (I[1]->Last->is(TT_LineComment))
657
38
          return 0;
658
12.1k
        
do 2.07k
{
659
12.1k
          if (Tok->is(tok::l_brace) && 
Tok->isNot(BK_BracedInit)183
)
660
154
            return 0;
661
12.0k
          Tok = Tok->Next;
662
12.0k
        } while (Tok);
663
664
        // Last, check that the third line starts with a closing brace.
665
1.91k
        Tok = I[2]->First;
666
1.91k
        if (Tok->isNot(tok::r_brace))
667
606
          return 0;
668
669
        // Don't merge "if (a) { .. } else {".
670
1.31k
        if (Tok->Next && 
Tok->Next->is(tok::kw_else)166
)
671
13
          return 0;
672
673
        // Don't merge a trailing multi-line control statement block like:
674
        // } else if (foo &&
675
        //            bar)
676
        // { <-- current Line
677
        //   baz();
678
        // }
679
1.29k
        if (Line.First == Line.Last &&
680
1.29k
            Style.BraceWrapping.AfterControlStatement ==
681
168
                FormatStyle::BWACS_MultiLine)
682
8
          return 0;
683
684
1.29k
        return 2;
685
1.29k
      }
686
7.81k
    } else 
if (97
I[1]->First->is(tok::l_brace)97
) {
687
97
      if (I[1]->Last->is(TT_LineComment))
688
6
        return 0;
689
690
      // Check for Limit <= 2 to account for the " {".
691
91
      if (Limit <= 2 || (Style.ColumnLimit == 0 && 
containsMustBreak(*I)0
))
692
0
        return 0;
693
91
      Limit -= 2;
694
91
      unsigned MergedLines = 0;
695
91
      if (Style.AllowShortBlocksOnASingleLine != FormatStyle::SBS_Never ||
696
91
          
(0
I[1]->First == I[1]->Last0
&&
I + 2 != E0
&&
697
91
           
I[2]->First->is(tok::r_brace)0
)) {
698
91
        MergedLines = tryMergeSimpleBlock(I + 1, E, Limit);
699
        // If we managed to merge the block, count the statement header, which
700
        // is on a separate line.
701
91
        if (MergedLines > 0)
702
66
          ++MergedLines;
703
91
      }
704
91
      return MergedLines;
705
91
    }
706
1.16k
    return 0;
707
7.90k
  }
708
709
  /// Returns the modified column limit for \p I if it is inside a macro and
710
  /// needs a trailing '\'.
711
  unsigned
712
  limitConsideringMacros(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
713
                         SmallVectorImpl<AnnotatedLine *>::const_iterator E,
714
3.23k
                         unsigned Limit) {
715
3.23k
    if (I[0]->InPPDirective && 
I + 1 != E82
&&
716
3.23k
        
!I[1]->First->HasUnescapedNewline82
&&
!I[1]->First->is(tok::eof)63
) {
717
34
      return Limit < 2 ? 
00
: Limit - 2;
718
34
    }
719
3.20k
    return Limit;
720
3.23k
  }
721
722
  bool nextTwoLinesFitInto(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
723
2.66k
                           unsigned Limit) {
724
2.66k
    if (I[1]->First->MustBreakBefore || I[2]->First->MustBreakBefore)
725
52
      return false;
726
2.60k
    return 1 + I[1]->Last->TotalLength + 1 + I[2]->Last->TotalLength <= Limit;
727
2.66k
  }
728
729
97
  bool containsMustBreak(const AnnotatedLine *Line) {
730
522
    for (const FormatToken *Tok = Line->First; Tok; 
Tok = Tok->Next425
) {
731
444
      if (Tok->MustBreakBefore)
732
19
        return true;
733
444
    }
734
78
    return false;
735
97
  }
736
737
6.53k
  void join(AnnotatedLine &A, const AnnotatedLine &B) {
738
6.53k
    assert(!A.Last->Next);
739
0
    assert(!B.First->Previous);
740
6.53k
    if (B.Affected)
741
5.60k
      A.Affected = true;
742
6.53k
    A.Last->Next = B.First;
743
6.53k
    B.First->Previous = A.Last;
744
6.53k
    B.First->CanBreakBefore = true;
745
6.53k
    unsigned LengthA = A.Last->TotalLength + B.First->SpacesRequiredBefore;
746
23.4k
    for (FormatToken *Tok = B.First; Tok; 
Tok = Tok->Next16.9k
) {
747
16.9k
      Tok->TotalLength += LengthA;
748
16.9k
      A.Last = Tok;
749
16.9k
    }
750
6.53k
  }
751
752
  const FormatStyle &Style;
753
  const AdditionalKeywords &Keywords;
754
  const SmallVectorImpl<AnnotatedLine *>::const_iterator End;
755
756
  SmallVectorImpl<AnnotatedLine *>::const_iterator Next;
757
  const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines;
758
};
759
760
66.1k
static void markFinalized(FormatToken *Tok) {
761
383k
  for (; Tok; 
Tok = Tok->Next316k
) {
762
316k
    Tok->Finalized = true;
763
316k
    for (AnnotatedLine *Child : Tok->Children)
764
1.58k
      markFinalized(Child->First);
765
316k
  }
766
66.1k
}
767
768
#ifndef NDEBUG
769
0
static void printLineState(const LineState &State) {
770
0
  llvm::dbgs() << "State: ";
771
0
  for (const ParenState &P : State.Stack) {
772
0
    llvm::dbgs() << (P.Tok ? P.Tok->TokenText : "F") << "|" << P.Indent << "|"
773
0
                 << P.LastSpace << "|" << P.NestedBlockIndent << " ";
774
0
  }
775
0
  llvm::dbgs() << State.NextToken->TokenText << "\n";
776
0
}
777
#endif
778
779
/// Base class for classes that format one \c AnnotatedLine.
780
class LineFormatter {
781
public:
782
  LineFormatter(ContinuationIndenter *Indenter, WhitespaceManager *Whitespaces,
783
                const FormatStyle &Style,
784
                UnwrappedLineFormatter *BlockFormatter)
785
      : Indenter(Indenter), Whitespaces(Whitespaces), Style(Style),
786
61.0k
        BlockFormatter(BlockFormatter) {}
787
61.0k
  virtual ~LineFormatter() {}
788
789
  /// Formats an \c AnnotatedLine and returns the penalty.
790
  ///
791
  /// If \p DryRun is \c false, directly applies the changes.
792
  virtual unsigned formatLine(const AnnotatedLine &Line, unsigned FirstIndent,
793
                              unsigned FirstStartColumn, bool DryRun) = 0;
794
795
protected:
796
  /// If the \p State's next token is an r_brace closing a nested block,
797
  /// format the nested block before it.
798
  ///
799
  /// Returns \c true if all children could be placed successfully and adapts
800
  /// \p Penalty as well as \p State. If \p DryRun is false, also directly
801
  /// creates changes using \c Whitespaces.
802
  ///
803
  /// The crucial idea here is that children always get formatted upon
804
  /// encountering the closing brace right after the nested block. Now, if we
805
  /// are currently trying to keep the "}" on the same line (i.e. \p NewLine is
806
  /// \c false), the entire block has to be kept on the same line (which is only
807
  /// possible if it fits on the line, only contains a single statement, etc.
808
  ///
809
  /// If \p NewLine is true, we format the nested block on separate lines, i.e.
810
  /// break after the "{", format all lines with correct indentation and the put
811
  /// the closing "}" on yet another new line.
812
  ///
813
  /// This enables us to keep the simple structure of the
814
  /// \c UnwrappedLineFormatter, where we only have two options for each token:
815
  /// break or don't break.
816
  bool formatChildren(LineState &State, bool NewLine, bool DryRun,
817
1.01M
                      unsigned &Penalty) {
818
1.01M
    const FormatToken *LBrace = State.NextToken->getPreviousNonComment();
819
1.01M
    FormatToken &Previous = *State.NextToken->Previous;
820
1.01M
    if (!LBrace || 
LBrace->isNot(tok::l_brace)1.01M
||
LBrace->isNot(BK_Block)25.0k
||
821
1.01M
        
Previous.Children.size() == 09.71k
)
822
      // The previous token does not open a block. Nothing to do. We don't
823
      // assert so that we can simply call this function for all tokens.
824
1.00M
      return true;
825
826
3.51k
    if (NewLine) {
827
2.32k
      const ParenState &P = State.Stack.back();
828
829
2.32k
      int AdditionalIndent =
830
2.32k
          P.Indent - Previous.Children[0]->Level * Style.IndentWidth;
831
832
2.32k
      if (Style.LambdaBodyIndentation == FormatStyle::LBI_OuterScope &&
833
2.32k
          
P.NestedBlockIndent == P.LastSpace76
) {
834
19
        if (State.NextToken->MatchingParen &&
835
19
            State.NextToken->MatchingParen->is(TT_LambdaLBrace)) {
836
19
          State.Stack.pop_back();
837
19
        }
838
19
        if (LBrace->is(TT_LambdaLBrace))
839
19
          AdditionalIndent = 0;
840
19
      }
841
842
2.32k
      Penalty +=
843
2.32k
          BlockFormatter->format(Previous.Children, DryRun, AdditionalIndent,
844
2.32k
                                 /*FixBadIndentation=*/true);
845
2.32k
      return true;
846
2.32k
    }
847
848
1.19k
    if (Previous.Children[0]->First->MustBreakBefore)
849
1
      return false;
850
851
    // Cannot merge into one line if this line ends on a comment.
852
1.18k
    if (Previous.is(tok::comment))
853
0
      return false;
854
855
    // Cannot merge multiple statements into a single line.
856
1.18k
    if (Previous.Children.size() > 1)
857
377
      return false;
858
859
812
    const AnnotatedLine *Child = Previous.Children[0];
860
    // We can't put the closing "}" on a line with a trailing comment.
861
812
    if (Child->Last->isTrailingComment())
862
135
      return false;
863
864
    // If the child line exceeds the column limit, we wouldn't want to merge it.
865
    // We add +2 for the trailing " }".
866
677
    if (Style.ColumnLimit > 0 &&
867
677
        
Child->Last->TotalLength + State.Column + 2 > Style.ColumnLimit676
)
868
118
      return false;
869
870
559
    if (!DryRun) {
871
413
      Whitespaces->replaceWhitespace(
872
413
          *Child->First, /*Newlines=*/0, /*Spaces=*/1,
873
413
          /*StartOfTokenColumn=*/State.Column, /*IsAligned=*/false,
874
413
          State.Line->InPPDirective);
875
413
    }
876
559
    Penalty +=
877
559
        formatLine(*Child, State.Column + 1, /*FirstStartColumn=*/0, DryRun);
878
879
559
    State.Column += 1 + Child->Last->TotalLength;
880
559
    return true;
881
677
  }
882
883
  ContinuationIndenter *Indenter;
884
885
private:
886
  WhitespaceManager *Whitespaces;
887
  const FormatStyle &Style;
888
  UnwrappedLineFormatter *BlockFormatter;
889
};
890
891
/// Formatter that keeps the existing line breaks.
892
class NoColumnLimitLineFormatter : public LineFormatter {
893
public:
894
  NoColumnLimitLineFormatter(ContinuationIndenter *Indenter,
895
                             WhitespaceManager *Whitespaces,
896
                             const FormatStyle &Style,
897
                             UnwrappedLineFormatter *BlockFormatter)
898
1.74k
      : LineFormatter(Indenter, Whitespaces, Style, BlockFormatter) {}
899
900
  /// Formats the line, simply keeping all of the input's line breaking
901
  /// decisions.
902
  unsigned formatLine(const AnnotatedLine &Line, unsigned FirstIndent,
903
1.74k
                      unsigned FirstStartColumn, bool DryRun) override {
904
1.74k
    assert(!DryRun);
905
0
    LineState State = Indenter->getInitialState(FirstIndent, FirstStartColumn,
906
1.74k
                                                &Line, /*DryRun=*/false);
907
5.95k
    while (State.NextToken) {
908
4.21k
      bool Newline =
909
4.21k
          Indenter->mustBreak(State) ||
910
4.21k
          
(3.87k
Indenter->canBreak(State)3.87k
&&
State.NextToken->NewlinesBefore > 01.09k
);
911
4.21k
      unsigned Penalty = 0;
912
4.21k
      formatChildren(State, Newline, /*DryRun=*/false, Penalty);
913
4.21k
      Indenter->addTokenToState(State, Newline, /*DryRun=*/false);
914
4.21k
    }
915
1.74k
    return 0;
916
1.74k
  }
917
};
918
919
/// Formatter that puts all tokens into a single line without breaks.
920
class NoLineBreakFormatter : public LineFormatter {
921
public:
922
  NoLineBreakFormatter(ContinuationIndenter *Indenter,
923
                       WhitespaceManager *Whitespaces, const FormatStyle &Style,
924
                       UnwrappedLineFormatter *BlockFormatter)
925
53.3k
      : LineFormatter(Indenter, Whitespaces, Style, BlockFormatter) {}
926
927
  /// Puts all tokens into a single line.
928
  unsigned formatLine(const AnnotatedLine &Line, unsigned FirstIndent,
929
53.6k
                      unsigned FirstStartColumn, bool DryRun) override {
930
53.6k
    unsigned Penalty = 0;
931
53.6k
    LineState State =
932
53.6k
        Indenter->getInitialState(FirstIndent, FirstStartColumn, &Line, DryRun);
933
202k
    while (State.NextToken) {
934
148k
      formatChildren(State, /*NewLine=*/false, DryRun, Penalty);
935
148k
      Indenter->addTokenToState(
936
148k
          State, /*Newline=*/State.NextToken->MustBreakBefore, DryRun);
937
148k
    }
938
53.6k
    return Penalty;
939
53.6k
  }
940
};
941
942
/// Finds the best way to break lines.
943
class OptimizingLineFormatter : public LineFormatter {
944
public:
945
  OptimizingLineFormatter(ContinuationIndenter *Indenter,
946
                          WhitespaceManager *Whitespaces,
947
                          const FormatStyle &Style,
948
                          UnwrappedLineFormatter *BlockFormatter)
949
6.01k
      : LineFormatter(Indenter, Whitespaces, Style, BlockFormatter) {}
950
951
  /// Formats the line by finding the best line breaks with line lengths
952
  /// below the column limit.
953
  unsigned formatLine(const AnnotatedLine &Line, unsigned FirstIndent,
954
6.21k
                      unsigned FirstStartColumn, bool DryRun) override {
955
6.21k
    LineState State =
956
6.21k
        Indenter->getInitialState(FirstIndent, FirstStartColumn, &Line, DryRun);
957
958
    // If the ObjC method declaration does not fit on a line, we should format
959
    // it with one arg per line.
960
6.21k
    if (State.Line->Type == LT_ObjCMethodDecl)
961
42
      State.Stack.back().BreakBeforeParameter = true;
962
963
    // Find best solution in solution space.
964
6.21k
    return analyzeSolutionSpace(State, DryRun);
965
6.21k
  }
966
967
private:
968
  struct CompareLineStatePointers {
969
14.3M
    bool operator()(LineState *obj1, LineState *obj2) const {
970
14.3M
      return *obj1 < *obj2;
971
14.3M
    }
972
  };
973
974
  /// A pair of <penalty, count> that is used to prioritize the BFS on.
975
  ///
976
  /// In case of equal penalties, we want to prefer states that were inserted
977
  /// first. During state generation we make sure that we insert states first
978
  /// that break the line as late as possible.
979
  typedef std::pair<unsigned, unsigned> OrderedPenalty;
980
981
  /// An edge in the solution space from \c Previous->State to \c State,
982
  /// inserting a newline dependent on the \c NewLine.
983
  struct StateNode {
984
    StateNode(const LineState &State, bool NewLine, StateNode *Previous)
985
788k
        : State(State), NewLine(NewLine), Previous(Previous) {}
986
    LineState State;
987
    bool NewLine;
988
    StateNode *Previous;
989
  };
990
991
  /// An item in the prioritized BFS search queue. The \c StateNode's
992
  /// \c State has the given \c OrderedPenalty.
993
  typedef std::pair<OrderedPenalty, StateNode *> QueueItem;
994
995
  /// The BFS queue type.
996
  typedef std::priority_queue<QueueItem, std::vector<QueueItem>,
997
                              std::greater<QueueItem>>
998
      QueueType;
999
1000
  /// Analyze the entire solution space starting from \p InitialState.
1001
  ///
1002
  /// This implements a variant of Dijkstra's algorithm on the graph that spans
1003
  /// the solution space (\c LineStates are the nodes). The algorithm tries to
1004
  /// find the shortest path (the one with lowest penalty) from \p InitialState
1005
  /// to a state where all tokens are placed. Returns the penalty.
1006
  ///
1007
  /// If \p DryRun is \c false, directly applies the changes.
1008
6.21k
  unsigned analyzeSolutionSpace(LineState &InitialState, bool DryRun) {
1009
6.21k
    std::set<LineState *, CompareLineStatePointers> Seen;
1010
1011
    // Increasing count of \c StateNode items we have created. This is used to
1012
    // create a deterministic order independent of the container.
1013
6.21k
    unsigned Count = 0;
1014
6.21k
    QueueType Queue;
1015
1016
    // Insert start element into queue.
1017
6.21k
    StateNode *Node =
1018
6.21k
        new (Allocator.Allocate()) StateNode(InitialState, false, nullptr);
1019
6.21k
    Queue.push(QueueItem(OrderedPenalty(0, Count), Node));
1020
6.21k
    ++Count;
1021
1022
6.21k
    unsigned Penalty = 0;
1023
1024
    // While not empty, take first element and follow edges.
1025
716k
    while (!Queue.empty()) {
1026
716k
      Penalty = Queue.top().first.first;
1027
716k
      StateNode *Node = Queue.top().second;
1028
716k
      if (!Node->State.NextToken) {
1029
6.21k
        LLVM_DEBUG(llvm::dbgs()
1030
6.21k
                   << "\n---\nPenalty for line: " << Penalty << "\n");
1031
6.21k
        break;
1032
6.21k
      }
1033
709k
      Queue.pop();
1034
1035
      // Cut off the analysis of certain solutions if the analysis gets too
1036
      // complex. See description of IgnoreStackForComparison.
1037
709k
      if (Count > 50000)
1038
134k
        Node->State.IgnoreStackForComparison = true;
1039
1040
709k
      if (!Seen.insert(&Node->State).second)
1041
        // State already examined with lower penalty.
1042
135k
        continue;
1043
1044
574k
      FormatDecision LastFormat = Node->State.NextToken->getDecision();
1045
574k
      if (LastFormat == FD_Unformatted || 
LastFormat == FD_Continue339
)
1046
573k
        addNextStateToQueue(Penalty, Node, /*NewLine=*/false, &Count, &Queue);
1047
574k
      if (LastFormat == FD_Unformatted || 
LastFormat == FD_Break339
)
1048
573k
        addNextStateToQueue(Penalty, Node, /*NewLine=*/true, &Count, &Queue);
1049
574k
    }
1050
1051
6.21k
    if (Queue.empty()) {
1052
      // We were unable to find a solution, do nothing.
1053
      // FIXME: Add diagnostic?
1054
0
      LLVM_DEBUG(llvm::dbgs() << "Could not find a solution.\n");
1055
0
      return 0;
1056
0
    }
1057
1058
    // Reconstruct the solution.
1059
6.21k
    if (!DryRun)
1060
5.97k
      reconstructPath(InitialState, Queue.top().second);
1061
1062
6.21k
    LLVM_DEBUG(llvm::dbgs()
1063
6.21k
               << "Total number of analyzed states: " << Count << "\n");
1064
6.21k
    LLVM_DEBUG(llvm::dbgs() << "---\n");
1065
1066
6.21k
    return Penalty;
1067
6.21k
  }
1068
1069
  /// Add the following state to the analysis queue \c Queue.
1070
  ///
1071
  /// Assume the current state is \p PreviousNode and has been reached with a
1072
  /// penalty of \p Penalty. Insert a line break if \p NewLine is \c true.
1073
  void addNextStateToQueue(unsigned Penalty, StateNode *PreviousNode,
1074
1.14M
                           bool NewLine, unsigned *Count, QueueType *Queue) {
1075
1.14M
    if (NewLine && 
!Indenter->canBreak(PreviousNode->State)573k
)
1076
330k
      return;
1077
817k
    if (!NewLine && 
Indenter->mustBreak(PreviousNode->State)573k
)
1078
35.6k
      return;
1079
1080
781k
    StateNode *Node = new (Allocator.Allocate())
1081
781k
        StateNode(PreviousNode->State, NewLine, PreviousNode);
1082
781k
    if (!formatChildren(Node->State, NewLine, /*DryRun=*/true, Penalty))
1083
631
      return;
1084
1085
781k
    Penalty += Indenter->addTokenToState(Node->State, NewLine, true);
1086
1087
781k
    Queue->push(QueueItem(OrderedPenalty(Penalty, *Count), Node));
1088
781k
    ++(*Count);
1089
781k
  }
1090
1091
  /// Applies the best formatting by reconstructing the path in the
1092
  /// solution space that leads to \c Best.
1093
5.97k
  void reconstructPath(LineState &State, StateNode *Best) {
1094
5.97k
    std::deque<StateNode *> Path;
1095
    // We do not need a break before the initial token.
1096
83.4k
    while (Best->Previous) {
1097
77.4k
      Path.push_front(Best);
1098
77.4k
      Best = Best->Previous;
1099
77.4k
    }
1100
83.4k
    for (auto I = Path.begin(), E = Path.end(); I != E; 
++I77.4k
) {
1101
77.4k
      unsigned Penalty = 0;
1102
77.4k
      formatChildren(State, (*I)->NewLine, /*DryRun=*/false, Penalty);
1103
77.4k
      Penalty += Indenter->addTokenToState(State, (*I)->NewLine, false);
1104
1105
77.4k
      LLVM_DEBUG({
1106
77.4k
        printLineState((*I)->Previous->State);
1107
77.4k
        if ((*I)->NewLine) {
1108
77.4k
          llvm::dbgs() << "Penalty for placing "
1109
77.4k
                       << (*I)->Previous->State.NextToken->Tok.getName()
1110
77.4k
                       << " on a new line: " << Penalty << "\n";
1111
77.4k
        }
1112
77.4k
      });
1113
77.4k
    }
1114
5.97k
  }
1115
1116
  llvm::SpecificBumpPtrAllocator<StateNode> Allocator;
1117
};
1118
1119
} // anonymous namespace
1120
1121
unsigned UnwrappedLineFormatter::format(
1122
    const SmallVectorImpl<AnnotatedLine *> &Lines, bool DryRun,
1123
    int AdditionalIndent, bool FixBadIndentation, unsigned FirstStartColumn,
1124
20.8k
    unsigned NextStartColumn, unsigned LastStartColumn) {
1125
20.8k
  LineJoiner Joiner(Style, Keywords, Lines);
1126
1127
  // Try to look up already computed penalty in DryRun-mode.
1128
20.8k
  std::pair<const SmallVectorImpl<AnnotatedLine *> *, unsigned> CacheKey(
1129
20.8k
      &Lines, AdditionalIndent);
1130
20.8k
  auto CacheIt = PenaltyCache.find(CacheKey);
1131
20.8k
  if (DryRun && 
CacheIt != PenaltyCache.end()1.68k
)
1132
573
    return CacheIt->second;
1133
1134
20.2k
  assert(!Lines.empty());
1135
0
  unsigned Penalty = 0;
1136
20.2k
  LevelIndentTracker IndentTracker(Style, Keywords, Lines[0]->Level,
1137
20.2k
                                   AdditionalIndent);
1138
20.2k
  const AnnotatedLine *PrevPrevLine = nullptr;
1139
20.2k
  const AnnotatedLine *PreviousLine = nullptr;
1140
20.2k
  const AnnotatedLine *NextLine = nullptr;
1141
1142
  // The minimum level of consecutive lines that have been formatted.
1143
20.2k
  unsigned RangeMinLevel = UINT_MAX;
1144
1145
20.2k
  bool FirstLine = true;
1146
20.2k
  for (const AnnotatedLine *Line =
1147
20.2k
           Joiner.getNextMergedLine(DryRun, IndentTracker);
1148
86.8k
       Line; 
Line = NextLine, FirstLine = false66.5k
) {
1149
66.5k
    const AnnotatedLine &TheLine = *Line;
1150
66.5k
    unsigned Indent = IndentTracker.getIndent();
1151
1152
    // We continue formatting unchanged lines to adjust their indent, e.g. if a
1153
    // scope was added. However, we need to carefully stop doing this when we
1154
    // exit the scope of affected lines to prevent indenting a the entire
1155
    // remaining file if it currently missing a closing brace.
1156
66.5k
    bool PreviousRBrace =
1157
66.5k
        PreviousLine && 
PreviousLine->startsWith(tok::r_brace)46.2k
;
1158
66.5k
    bool ContinueFormatting =
1159
66.5k
        TheLine.Level > RangeMinLevel ||
1160
66.5k
        
(56.7k
TheLine.Level == RangeMinLevel56.7k
&&
!PreviousRBrace31.2k
&&
1161
56.7k
         
!TheLine.startsWith(tok::r_brace)26.3k
);
1162
1163
66.5k
    bool FixIndentation = (FixBadIndentation || 
ContinueFormatting63.4k
) &&
1164
66.5k
                          
Indent != TheLine.First->OriginalColumn33.6k
;
1165
66.5k
    bool ShouldFormat = TheLine.Affected || 
FixIndentation5.80k
;
1166
    // We cannot format this line; if the reason is that the line had a
1167
    // parsing error, remember that.
1168
66.5k
    if (ShouldFormat && 
TheLine.Type == LT_Invalid61.1k
&&
Status25
) {
1169
19
      Status->FormatComplete = false;
1170
19
      Status->Line =
1171
19
          SourceMgr.getSpellingLineNumber(TheLine.First->Tok.getLocation());
1172
19
    }
1173
1174
66.5k
    if (ShouldFormat && 
TheLine.Type != LT_Invalid61.1k
) {
1175
61.0k
      if (!DryRun) {
1176
59.1k
        bool LastLine = Line->First->is(tok::eof);
1177
59.1k
        formatFirstToken(TheLine, PreviousLine, PrevPrevLine, Lines, Indent,
1178
59.1k
                         LastLine ? 
LastStartColumn18.1k
:
NextStartColumn + Indent40.9k
);
1179
59.1k
      }
1180
1181
61.0k
      NextLine = Joiner.getNextMergedLine(DryRun, IndentTracker);
1182
61.0k
      unsigned ColumnLimit = getColumnLimit(TheLine.InPPDirective, NextLine);
1183
61.0k
      bool FitsIntoOneLine =
1184
61.0k
          TheLine.Last->TotalLength + Indent <= ColumnLimit ||
1185
61.0k
          
(7.52k
TheLine.Type == LT_ImportStatement7.52k
&&
1186
7.52k
           
(61
Style.Language != FormatStyle::LK_JavaScript61
||
1187
61
            
!Style.JavaScriptWrapImports26
)) ||
1188
61.0k
          
(7.47k
Style.isCSharp()7.47k
&&
1189
7.47k
           
TheLine.InPPDirective90
); // don't split #regions in C#
1190
61.0k
      if (Style.ColumnLimit == 0)
1191
1.74k
        NoColumnLimitLineFormatter(Indenter, Whitespaces, Style, this)
1192
1.74k
            .formatLine(TheLine, NextStartColumn + Indent,
1193
1.74k
                        FirstLine ? 
FirstStartColumn317
:
01.42k
, DryRun);
1194
59.3k
      else if (FitsIntoOneLine)
1195
53.3k
        Penalty += NoLineBreakFormatter(Indenter, Whitespaces, Style, this)
1196
53.3k
                       .formatLine(TheLine, NextStartColumn + Indent,
1197
53.3k
                                   FirstLine ? 
FirstStartColumn14.5k
:
038.7k
, DryRun);
1198
6.01k
      else
1199
6.01k
        Penalty += OptimizingLineFormatter(Indenter, Whitespaces, Style, this)
1200
6.01k
                       .formatLine(TheLine, NextStartColumn + Indent,
1201
6.01k
                                   FirstLine ? 
FirstStartColumn4.87k
:
01.13k
, DryRun);
1202
61.0k
      RangeMinLevel = std::min(RangeMinLevel, TheLine.Level);
1203
61.0k
    } else {
1204
      // If no token in the current line is affected, we still need to format
1205
      // affected children.
1206
5.42k
      if (TheLine.ChildrenAffected)
1207
93
        
for (const FormatToken *Tok = TheLine.First; 11
Tok;
Tok = Tok->Next82
)
1208
82
          if (!Tok->Children.empty())
1209
12
            format(Tok->Children, DryRun);
1210
1211
      // Adapt following lines on the current indent level to the same level
1212
      // unless the current \c AnnotatedLine is not at the beginning of a line.
1213
5.42k
      bool StartsNewLine =
1214
5.42k
          TheLine.First->NewlinesBefore > 0 || 
TheLine.First->IsFirst544
;
1215
5.42k
      if (StartsNewLine)
1216
5.19k
        IndentTracker.adjustToUnmodifiedLine(TheLine);
1217
5.42k
      if (!DryRun) {
1218
5.42k
        bool ReformatLeadingWhitespace =
1219
5.42k
            StartsNewLine && 
(5.18k
(5.18k
PreviousLine5.18k
&&
PreviousLine->Affected4.65k
) ||
1220
5.18k
                              
TheLine.LeadingEmptyLinesAffected4.75k
);
1221
        // Format the first token.
1222
5.42k
        if (ReformatLeadingWhitespace)
1223
447
          formatFirstToken(TheLine, PreviousLine, PrevPrevLine, Lines,
1224
447
                           TheLine.First->OriginalColumn,
1225
447
                           TheLine.First->OriginalColumn);
1226
4.97k
        else
1227
4.97k
          Whitespaces->addUntouchableToken(*TheLine.First,
1228
4.97k
                                           TheLine.InPPDirective);
1229
1230
        // Notify the WhitespaceManager about the unchanged whitespace.
1231
24.5k
        for (FormatToken *Tok = TheLine.First->Next; Tok; 
Tok = Tok->Next19.1k
)
1232
19.1k
          Whitespaces->addUntouchableToken(*Tok, TheLine.InPPDirective);
1233
5.42k
      }
1234
5.42k
      NextLine = Joiner.getNextMergedLine(DryRun, IndentTracker);
1235
5.42k
      RangeMinLevel = UINT_MAX;
1236
5.42k
    }
1237
66.5k
    if (!DryRun)
1238
64.5k
      markFinalized(TheLine.First);
1239
66.5k
    PrevPrevLine = PreviousLine;
1240
66.5k
    PreviousLine = &TheLine;
1241
66.5k
  }
1242
20.2k
  PenaltyCache[CacheKey] = Penalty;
1243
20.2k
  return Penalty;
1244
20.8k
}
1245
1246
void UnwrappedLineFormatter::formatFirstToken(
1247
    const AnnotatedLine &Line, const AnnotatedLine *PreviousLine,
1248
    const AnnotatedLine *PrevPrevLine,
1249
    const SmallVectorImpl<AnnotatedLine *> &Lines, unsigned Indent,
1250
59.6k
    unsigned NewlineIndent) {
1251
59.6k
  FormatToken &RootToken = *Line.First;
1252
59.6k
  if (RootToken.is(tok::eof)) {
1253
18.2k
    unsigned Newlines = std::min(RootToken.NewlinesBefore, 1u);
1254
18.2k
    unsigned TokenIndent = Newlines ? 
NewlineIndent1.52k
:
016.6k
;
1255
18.2k
    Whitespaces->replaceWhitespace(RootToken, Newlines, TokenIndent,
1256
18.2k
                                   TokenIndent);
1257
18.2k
    return;
1258
18.2k
  }
1259
41.4k
  unsigned Newlines =
1260
41.4k
      std::min(RootToken.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1);
1261
  // Remove empty lines before "}" where applicable.
1262
41.4k
  if (RootToken.is(tok::r_brace) &&
1263
41.4k
      
(5.85k
!RootToken.Next5.85k
||
1264
5.85k
       
(2.08k
RootToken.Next->is(tok::semi)2.08k
&&
!RootToken.Next->Next976
)) &&
1265
      // Do not remove empty lines before namespace closing "}".
1266
41.4k
      
!getNamespaceToken(&Line, Lines)4.74k
)
1267
4.59k
    Newlines = std::min(Newlines, 1u);
1268
  // Remove empty lines at the start of nested blocks (lambdas/arrow functions)
1269
41.4k
  if (PreviousLine == nullptr && 
Line.Level > 018.6k
)
1270
627
    Newlines = std::min(Newlines, 1u);
1271
41.4k
  if (Newlines == 0 && 
!RootToken.IsFirst27.7k
)
1272
10.0k
    Newlines = 1;
1273
41.4k
  if (RootToken.IsFirst && 
!RootToken.HasUnescapedNewline17.9k
)
1274
17.7k
    Newlines = 0;
1275
1276
  // Remove empty lines after "{".
1277
41.4k
  if (!Style.KeepEmptyLinesAtTheStartOfBlocks && 
PreviousLine6.01k
&&
1278
41.4k
      
PreviousLine->Last->is(tok::l_brace)2.32k
&&
1279
41.4k
      
!PreviousLine->startsWithNamespace()686
&&
1280
41.4k
      
!(679
PrevPrevLine679
&&
PrevPrevLine->startsWithNamespace()227
&&
1281
679
        
PreviousLine->startsWith(tok::l_brace)9
) &&
1282
41.4k
      
!startsExternCBlock(*PreviousLine)670
)
1283
663
    Newlines = 1;
1284
1285
  // Insert or remove empty line before access specifiers.
1286
41.4k
  if (PreviousLine && 
RootToken.isAccessSpecifier()22.7k
) {
1287
513
    switch (Style.EmptyLineBeforeAccessModifier) {
1288
64
    case FormatStyle::ELBAMS_Never:
1289
64
      if (Newlines > 1)
1290
13
        Newlines = 1;
1291
64
      break;
1292
38
    case FormatStyle::ELBAMS_Leave:
1293
38
      Newlines = std::max(RootToken.NewlinesBefore, 1u);
1294
38
      break;
1295
359
    case FormatStyle::ELBAMS_LogicalBlock:
1296
359
      if (PreviousLine->Last->isOneOf(tok::semi, tok::r_brace) && 
Newlines <= 198
)
1297
47
        Newlines = 2;
1298
359
      if (PreviousLine->First->isAccessSpecifier())
1299
44
        Newlines = 1; // Previous is an access modifier remove all new lines.
1300
359
      break;
1301
52
    case FormatStyle::ELBAMS_Always: {
1302
52
      const FormatToken *previousToken;
1303
52
      if (PreviousLine->Last->is(tok::comment))
1304
6
        previousToken = PreviousLine->Last->getPreviousNonComment();
1305
46
      else
1306
46
        previousToken = PreviousLine->Last;
1307
52
      if ((!previousToken || 
!previousToken->is(tok::l_brace)49
) &&
Newlines <= 135
)
1308
24
        Newlines = 2;
1309
52
    } break;
1310
513
    }
1311
513
  }
1312
1313
  // Insert or remove empty line after access specifiers.
1314
41.4k
  if (PreviousLine && 
PreviousLine->First->isAccessSpecifier()22.7k
&&
1315
41.4k
      
(515
!PreviousLine->InPPDirective515
||
!RootToken.HasUnescapedNewline5
)) {
1316
    // EmptyLineBeforeAccessModifier is handling the case when two access
1317
    // modifiers follow each other.
1318
515
    if (!RootToken.isAccessSpecifier()) {
1319
446
      switch (Style.EmptyLineAfterAccessModifier) {
1320
366
      case FormatStyle::ELAAMS_Never:
1321
366
        Newlines = 1;
1322
366
        break;
1323
34
      case FormatStyle::ELAAMS_Leave:
1324
34
        Newlines = std::max(Newlines, 1u);
1325
34
        break;
1326
46
      case FormatStyle::ELAAMS_Always:
1327
46
        if (RootToken.is(tok::r_brace)) // Do not add at end of class.
1328
10
          Newlines = 1u;
1329
36
        else
1330
36
          Newlines = std::max(Newlines, 2u);
1331
46
        break;
1332
446
      }
1333
446
    }
1334
515
  }
1335
1336
41.4k
  if (Newlines)
1337
23.6k
    Indent = NewlineIndent;
1338
1339
  // Preprocessor directives get indented before the hash only if specified
1340
41.4k
  if (Style.IndentPPDirectives != FormatStyle::PPDIS_BeforeHash &&
1341
41.4k
      
(41.2k
Line.Type == LT_PreprocessorDirective41.2k
||
1342
41.2k
       
Line.Type == LT_ImportStatement39.3k
))
1343
3.01k
    Indent = 0;
1344
1345
41.4k
  Whitespaces->replaceWhitespace(RootToken, Newlines, Indent, Indent,
1346
41.4k
                                 /*IsAligned=*/false,
1347
41.4k
                                 Line.InPPDirective &&
1348
41.4k
                                     
!RootToken.HasUnescapedNewline3.41k
);
1349
41.4k
}
1350
1351
unsigned
1352
UnwrappedLineFormatter::getColumnLimit(bool InPPDirective,
1353
61.0k
                                       const AnnotatedLine *NextLine) const {
1354
  // In preprocessor directives reserve two chars for trailing " \" if the
1355
  // next line continues the preprocessor directive.
1356
61.0k
  bool ContinuesPPDirective =
1357
61.0k
      InPPDirective &&
1358
      // If there is no next line, this is likely a child line and the parent
1359
      // continues the preprocessor directive.
1360
61.0k
      
(3.42k
!NextLine3.42k
||
1361
3.42k
       
(3.40k
NextLine->InPPDirective3.40k
&&
1362
        // If there is an unescaped newline between this line and the next, the
1363
        // next line starts a new preprocessor directive.
1364
3.40k
        
!NextLine->First->HasUnescapedNewline1.65k
));
1365
61.0k
  return Style.ColumnLimit - (ContinuesPPDirective ? 
2540
:
060.5k
);
1366
61.0k
}
1367
1368
} // namespace format
1369
} // namespace clang