1 //===--- UnwrappedLineFormatter.cpp - Format C++ code ---------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include "UnwrappedLineFormatter.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 bool startsExternCBlock(const AnnotatedLine &Line) {
23   const FormatToken *Next = Line.First->getNextNonComment();
24   const FormatToken *NextNext = Next ? Next->getNextNonComment() : nullptr;
25   return Line.startsWith(tok::kw_extern) && Next && Next->isStringLiteral() &&
26          NextNext && NextNext->is(tok::l_brace);
27 }
28 
29 /// \brief 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       : Style(Style), Keywords(Keywords), AdditionalIndent(AdditionalIndent) {
44     for (unsigned i = 0; i != StartLevel; ++i)
45       IndentForLevel.push_back(Style.IndentWidth * i + AdditionalIndent);
46   }
47 
48   /// \brief Returns the indent for the current line.
49   unsigned getIndent() const { return Indent; }
50 
51   /// \brief Update the indent state given that \p Line is going to be formatted
52   /// next.
53   void nextLine(const AnnotatedLine &Line) {
54     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     while (IndentForLevel.size() <= Line.Level)
58       IndentForLevel.push_back(-1);
59     if (Line.InPPDirective) {
60       Indent = Line.Level * Style.IndentWidth + AdditionalIndent;
61     } else {
62       IndentForLevel.resize(Line.Level + 1);
63       Indent = getIndent(IndentForLevel, Line.Level);
64     }
65     if (static_cast<int>(Indent) + Offset >= 0)
66       Indent += Offset;
67   }
68 
69   /// \brief Update the indent state given that \p Line indent should be
70   /// skipped.
71   void skipLine(const AnnotatedLine &Line) {
72     while (IndentForLevel.size() <= Line.Level)
73       IndentForLevel.push_back(Indent);
74   }
75 
76   /// \brief Update the level indent to adapt to the given \p Line.
77   ///
78   /// When a line is not formatted, we move the subsequent lines on the same
79   /// level to the same indent.
80   /// Note that \c nextLine must have been called before this method.
81   void adjustToUnmodifiedLine(const AnnotatedLine &Line) {
82     unsigned LevelIndent = Line.First->OriginalColumn;
83     if (static_cast<int>(LevelIndent) - Offset >= 0)
84       LevelIndent -= Offset;
85     if ((!Line.First->is(tok::comment) || IndentForLevel[Line.Level] == -1) &&
86         !Line.InPPDirective)
87       IndentForLevel[Line.Level] = LevelIndent;
88   }
89 
90 private:
91   /// \brief Get the offset of the line relatively to the level.
92   ///
93   /// For example, 'public:' labels in classes are offset by 1 or 2
94   /// characters to the left from their level.
95   int getIndentOffset(const FormatToken &RootToken) {
96     if (Style.Language == FormatStyle::LK_Java ||
97         Style.Language == FormatStyle::LK_JavaScript)
98       return 0;
99     if (RootToken.isAccessSpecifier(false) ||
100         RootToken.isObjCAccessSpecifier() ||
101         (RootToken.isOneOf(Keywords.kw_signals, Keywords.kw_qsignals) &&
102          RootToken.Next && RootToken.Next->is(tok::colon)))
103       return Style.AccessModifierOffset;
104     return 0;
105   }
106 
107   /// \brief Get the indent of \p Level from \p IndentForLevel.
108   ///
109   /// \p IndentForLevel must contain the indent for the level \c l
110   /// at \p IndentForLevel[l], or a value < 0 if the indent for
111   /// that level is unknown.
112   unsigned getIndent(ArrayRef<int> IndentForLevel, unsigned Level) {
113     if (IndentForLevel[Level] != -1)
114       return IndentForLevel[Level];
115     if (Level == 0)
116       return 0;
117     return getIndent(IndentForLevel, Level - 1) + Style.IndentWidth;
118   }
119 
120   const FormatStyle &Style;
121   const AdditionalKeywords &Keywords;
122   const unsigned AdditionalIndent;
123 
124   /// \brief The indent in characters for each level.
125   std::vector<int> IndentForLevel;
126 
127   /// \brief Offset of the current line relative to the indent level.
128   ///
129   /// For example, the 'public' keywords is often indented with a negative
130   /// offset.
131   int Offset = 0;
132 
133   /// \brief The current line's indent.
134   unsigned Indent = 0;
135 };
136 
137 bool isNamespaceDeclaration(const AnnotatedLine *Line) {
138   const FormatToken *NamespaceTok = Line->First;
139   return NamespaceTok && NamespaceTok->getNamespaceToken();
140 }
141 
142 bool isEndOfNamespace(const AnnotatedLine *Line,
143                       const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines) {
144   if (!Line->startsWith(tok::r_brace))
145     return false;
146   size_t StartLineIndex = Line->MatchingOpeningBlockLineIndex;
147   if (StartLineIndex == UnwrappedLine::kInvalidIndex)
148     return false;
149   assert(StartLineIndex < AnnotatedLines.size());
150   return isNamespaceDeclaration(AnnotatedLines[StartLineIndex]);
151 }
152 
153 class LineJoiner {
154 public:
155   LineJoiner(const FormatStyle &Style, const AdditionalKeywords &Keywords,
156              const SmallVectorImpl<AnnotatedLine *> &Lines)
157       : Style(Style), Keywords(Keywords), End(Lines.end()), Next(Lines.begin()),
158         AnnotatedLines(Lines) {}
159 
160   /// \brief Returns the next line, merging multiple lines into one if possible.
161   const AnnotatedLine *getNextMergedLine(bool DryRun,
162                                          LevelIndentTracker &IndentTracker) {
163     if (Next == End)
164       return nullptr;
165     const AnnotatedLine *Current = *Next;
166     IndentTracker.nextLine(*Current);
167     unsigned MergedLines =
168         tryFitMultipleLinesInOne(IndentTracker, Next, End);
169     if (MergedLines > 0 && Style.ColumnLimit == 0)
170       // Disallow line merging if there is a break at the start of one of the
171       // input lines.
172       for (unsigned i = 0; i < MergedLines; ++i)
173         if (Next[i + 1]->First->NewlinesBefore > 0)
174           MergedLines = 0;
175     if (!DryRun)
176       for (unsigned i = 0; i < MergedLines; ++i)
177         join(*Next[0], *Next[i + 1]);
178     Next = Next + MergedLines + 1;
179     return Current;
180   }
181 
182 private:
183   /// \brief Calculates how many lines can be merged into 1 starting at \p I.
184   unsigned
185   tryFitMultipleLinesInOne(LevelIndentTracker &IndentTracker,
186                            SmallVectorImpl<AnnotatedLine *>::const_iterator I,
187                            SmallVectorImpl<AnnotatedLine *>::const_iterator E) {
188     const unsigned Indent = IndentTracker.getIndent();
189 
190     // Can't join the last line with anything.
191     if (I + 1 == E)
192       return 0;
193     // We can never merge stuff if there are trailing line comments.
194     const AnnotatedLine *TheLine = *I;
195     if (TheLine->Last->is(TT_LineComment))
196       return 0;
197     if (I[1]->Type == LT_Invalid || I[1]->First->MustBreakBefore)
198       return 0;
199     if (TheLine->InPPDirective &&
200         (!I[1]->InPPDirective || I[1]->First->HasUnescapedNewline))
201       return 0;
202 
203     if (Style.ColumnLimit > 0 && Indent > Style.ColumnLimit)
204       return 0;
205 
206     unsigned Limit =
207         Style.ColumnLimit == 0 ? UINT_MAX : Style.ColumnLimit - Indent;
208     // If we already exceed the column limit, we set 'Limit' to 0. The different
209     // tryMerge..() functions can then decide whether to still do merging.
210     Limit = TheLine->Last->TotalLength > Limit
211                 ? 0
212                 : Limit - TheLine->Last->TotalLength;
213 
214     if (TheLine->Last->is(TT_FunctionLBrace) &&
215         TheLine->First == TheLine->Last &&
216         !Style.BraceWrapping.SplitEmptyFunction &&
217         I[1]->First->is(tok::r_brace))
218       return tryMergeSimpleBlock(I, E, Limit);
219 
220     // Handle empty record blocks where the brace has already been wrapped
221     if (TheLine->Last->is(tok::l_brace) && TheLine->First == TheLine->Last &&
222         I != AnnotatedLines.begin()) {
223       bool EmptyBlock = I[1]->First->is(tok::r_brace);
224 
225       const FormatToken *Tok = I[-1]->First;
226       if (Tok && Tok->is(tok::comment))
227         Tok = Tok->getNextNonComment();
228 
229       if (Tok && Tok->getNamespaceToken())
230         return !Style.BraceWrapping.SplitEmptyNamespace && EmptyBlock
231             ? tryMergeSimpleBlock(I, E, Limit) : 0;
232 
233       if (Tok && Tok->is(tok::kw_typedef))
234         Tok = Tok->getNextNonComment();
235       if (Tok && Tok->isOneOf(tok::kw_class, tok::kw_struct, tok::kw_union,
236                               Keywords.kw_interface))
237         return !Style.BraceWrapping.SplitEmptyRecord && EmptyBlock
238             ? tryMergeSimpleBlock(I, E, Limit) : 0;
239     }
240 
241     // FIXME: TheLine->Level != 0 might or might not be the right check to do.
242     // If necessary, change to something smarter.
243     bool MergeShortFunctions =
244         Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_All ||
245         (Style.AllowShortFunctionsOnASingleLine >= FormatStyle::SFS_Empty &&
246          I[1]->First->is(tok::r_brace)) ||
247         (Style.AllowShortFunctionsOnASingleLine & FormatStyle::SFS_InlineOnly &&
248          TheLine->Level != 0);
249 
250     if (Style.CompactNamespaces) {
251       if (isNamespaceDeclaration(TheLine)) {
252         int i = 0;
253         unsigned closingLine = TheLine->MatchingOpeningBlockLineIndex - 1;
254         for (; I + 1 + i != E && isNamespaceDeclaration(I[i + 1]) &&
255                closingLine == I[i + 1]->MatchingOpeningBlockLineIndex &&
256                I[i + 1]->Last->TotalLength < Limit;
257              i++, closingLine--) {
258           // No extra indent for compacted namespaces
259           IndentTracker.skipLine(*I[i + 1]);
260 
261           Limit -= I[i + 1]->Last->TotalLength;
262         }
263         return i;
264       }
265 
266       if (isEndOfNamespace(TheLine, AnnotatedLines)) {
267         int i = 0;
268         unsigned openingLine = TheLine->MatchingOpeningBlockLineIndex - 1;
269         for (; I + 1 + i != E && isEndOfNamespace(I[i + 1], AnnotatedLines) &&
270                openingLine == I[i + 1]->MatchingOpeningBlockLineIndex;
271              i++, openingLine--) {
272           // No space between consecutive braces
273           I[i + 1]->First->SpacesRequiredBefore = !I[i]->Last->is(tok::r_brace);
274 
275           // Indent like the outer-most namespace
276           IndentTracker.nextLine(*I[i + 1]);
277         }
278         return i;
279       }
280     }
281 
282     // Try to merge a function block with left brace unwrapped
283     if (TheLine->Last->is(TT_FunctionLBrace) &&
284         TheLine->First != TheLine->Last) {
285       return MergeShortFunctions ? tryMergeSimpleBlock(I, E, Limit) : 0;
286     }
287     // Try to merge a control statement block with left brace unwrapped
288     if (TheLine->Last->is(tok::l_brace) && TheLine->First != TheLine->Last &&
289         TheLine->First->isOneOf(tok::kw_if, tok::kw_while, tok::kw_for)) {
290       return Style.AllowShortBlocksOnASingleLine
291                  ? tryMergeSimpleBlock(I, E, Limit)
292                  : 0;
293     }
294     // Try to merge a control statement block with left brace wrapped
295     if (I[1]->First->is(tok::l_brace) &&
296         TheLine->First->isOneOf(tok::kw_if, tok::kw_while, tok::kw_for)) {
297       return Style.BraceWrapping.AfterControlStatement
298                  ? tryMergeSimpleBlock(I, E, Limit)
299                  : 0;
300     }
301     // Try to merge either empty or one-line block if is precedeed by control
302     // statement token
303     if (TheLine->First->is(tok::l_brace) && TheLine->First == TheLine->Last &&
304         I != AnnotatedLines.begin() &&
305         I[-1]->First->isOneOf(tok::kw_if, tok::kw_while, tok::kw_for)) {
306       return Style.AllowShortBlocksOnASingleLine
307                  ? tryMergeSimpleBlock(I - 1, E, Limit)
308                  : 0;
309     }
310     // Try to merge a block with left brace wrapped that wasn't yet covered
311     if (TheLine->Last->is(tok::l_brace)) {
312       return !Style.BraceWrapping.AfterFunction ||
313              (I[1]->First->is(tok::r_brace) &&
314               !Style.BraceWrapping.SplitEmptyRecord)
315                  ? tryMergeSimpleBlock(I, E, Limit)
316                  : 0;
317     }
318     // Try to merge a function block with left brace wrapped
319     if (I[1]->First->is(TT_FunctionLBrace) &&
320         Style.BraceWrapping.AfterFunction) {
321       if (I[1]->Last->is(TT_LineComment))
322         return 0;
323 
324       // Check for Limit <= 2 to account for the " {".
325       if (Limit <= 2 || (Style.ColumnLimit == 0 && containsMustBreak(TheLine)))
326         return 0;
327       Limit -= 2;
328 
329       unsigned MergedLines = 0;
330       if (MergeShortFunctions ||
331           (Style.AllowShortFunctionsOnASingleLine >= FormatStyle::SFS_Empty &&
332            I[1]->First == I[1]->Last && I + 2 != E &&
333            I[2]->First->is(tok::r_brace))) {
334         MergedLines = tryMergeSimpleBlock(I + 1, E, Limit);
335         // If we managed to merge the block, count the function header, which is
336         // on a separate line.
337         if (MergedLines > 0)
338           ++MergedLines;
339       }
340       return MergedLines;
341     }
342     if (TheLine->First->is(tok::kw_if)) {
343       return Style.AllowShortIfStatementsOnASingleLine
344                  ? tryMergeSimpleControlStatement(I, E, Limit)
345                  : 0;
346     }
347     if (TheLine->First->isOneOf(tok::kw_for, tok::kw_while)) {
348       return Style.AllowShortLoopsOnASingleLine
349                  ? tryMergeSimpleControlStatement(I, E, Limit)
350                  : 0;
351     }
352     if (TheLine->First->isOneOf(tok::kw_case, tok::kw_default)) {
353       return Style.AllowShortCaseLabelsOnASingleLine
354                  ? tryMergeShortCaseLabels(I, E, Limit)
355                  : 0;
356     }
357     if (TheLine->InPPDirective &&
358         (TheLine->First->HasUnescapedNewline || TheLine->First->IsFirst)) {
359       return tryMergeSimplePPDirective(I, E, Limit);
360     }
361     return 0;
362   }
363 
364   unsigned
365   tryMergeSimplePPDirective(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
366                             SmallVectorImpl<AnnotatedLine *>::const_iterator E,
367                             unsigned Limit) {
368     if (Limit == 0)
369       return 0;
370     if (I + 2 != E && I[2]->InPPDirective && !I[2]->First->HasUnescapedNewline)
371       return 0;
372     if (1 + I[1]->Last->TotalLength > Limit)
373       return 0;
374     return 1;
375   }
376 
377   unsigned tryMergeSimpleControlStatement(
378       SmallVectorImpl<AnnotatedLine *>::const_iterator I,
379       SmallVectorImpl<AnnotatedLine *>::const_iterator E, unsigned Limit) {
380     if (Limit == 0)
381       return 0;
382     if (Style.BraceWrapping.AfterControlStatement &&
383         (I[1]->First->is(tok::l_brace) && !Style.AllowShortBlocksOnASingleLine))
384       return 0;
385     if (I[1]->InPPDirective != (*I)->InPPDirective ||
386         (I[1]->InPPDirective && I[1]->First->HasUnescapedNewline))
387       return 0;
388     Limit = limitConsideringMacros(I + 1, E, Limit);
389     AnnotatedLine &Line = **I;
390     if (Line.Last->isNot(tok::r_paren))
391       return 0;
392     if (1 + I[1]->Last->TotalLength > Limit)
393       return 0;
394     if (I[1]->First->isOneOf(tok::semi, tok::kw_if, tok::kw_for, tok::kw_while,
395                              TT_LineComment))
396       return 0;
397     // Only inline simple if's (no nested if or else).
398     if (I + 2 != E && Line.startsWith(tok::kw_if) &&
399         I[2]->First->is(tok::kw_else))
400       return 0;
401     return 1;
402   }
403 
404   unsigned
405   tryMergeShortCaseLabels(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
406                           SmallVectorImpl<AnnotatedLine *>::const_iterator E,
407                           unsigned Limit) {
408     if (Limit == 0 || I + 1 == E ||
409         I[1]->First->isOneOf(tok::kw_case, tok::kw_default))
410       return 0;
411     unsigned NumStmts = 0;
412     unsigned Length = 0;
413     bool EndsWithComment = false;
414     bool InPPDirective = I[0]->InPPDirective;
415     const unsigned Level = I[0]->Level;
416     for (; NumStmts < 3; ++NumStmts) {
417       if (I + 1 + NumStmts == E)
418         break;
419       const AnnotatedLine *Line = I[1 + NumStmts];
420       if (Line->InPPDirective != InPPDirective)
421         break;
422       if (Line->First->isOneOf(tok::kw_case, tok::kw_default, tok::r_brace))
423         break;
424       if (Line->First->isOneOf(tok::kw_if, tok::kw_for, tok::kw_switch,
425                                tok::kw_while) ||
426           EndsWithComment)
427         return 0;
428       if (Line->First->is(tok::comment)) {
429         if (Level != Line->Level)
430           return 0;
431         SmallVectorImpl<AnnotatedLine *>::const_iterator J = I + 2 + NumStmts;
432         for (; J != E; ++J) {
433           Line = *J;
434           if (Line->InPPDirective != InPPDirective)
435             break;
436           if (Line->First->isOneOf(tok::kw_case, tok::kw_default, tok::r_brace))
437             break;
438           if (Line->First->isNot(tok::comment) || Level != Line->Level)
439             return 0;
440         }
441         break;
442       }
443       if (Line->Last->is(tok::comment))
444         EndsWithComment = true;
445       Length += I[1 + NumStmts]->Last->TotalLength + 1; // 1 for the space.
446     }
447     if (NumStmts == 0 || NumStmts == 3 || Length > Limit)
448       return 0;
449     return NumStmts;
450   }
451 
452   unsigned
453   tryMergeSimpleBlock(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
454                       SmallVectorImpl<AnnotatedLine *>::const_iterator E,
455                       unsigned Limit) {
456     AnnotatedLine &Line = **I;
457 
458     // Don't merge ObjC @ keywords and methods.
459     // FIXME: If an option to allow short exception handling clauses on a single
460     // line is added, change this to not return for @try and friends.
461     if (Style.Language != FormatStyle::LK_Java &&
462         Line.First->isOneOf(tok::at, tok::minus, tok::plus))
463       return 0;
464 
465     // Check that the current line allows merging. This depends on whether we
466     // are in a control flow statements as well as several style flags.
467     if (Line.First->isOneOf(tok::kw_else, tok::kw_case) ||
468         (Line.First->Next && Line.First->Next->is(tok::kw_else)) ||
469         (I != AnnotatedLines.begin() && I[-1]->Last->is(tok::kw_else)))
470       return 0;
471     if (Line.First->isOneOf(tok::kw_if, tok::kw_while, tok::kw_do, tok::kw_try,
472                             tok::kw___try, tok::kw_catch, tok::kw___finally,
473                             tok::kw_for, tok::r_brace, Keywords.kw___except)) {
474       if (!Style.AllowShortBlocksOnASingleLine)
475         return 0;
476       // Don't merge when we can't except the case when
477       // the control statement block is empty
478       if (!Style.AllowShortIfStatementsOnASingleLine &&
479           Line.startsWith(tok::kw_if) &&
480           !Style.BraceWrapping.AfterControlStatement &&
481           !I[1]->First->is(tok::r_brace))
482         return 0;
483       if (!Style.AllowShortIfStatementsOnASingleLine &&
484           Line.startsWith(tok::kw_if) &&
485           Style.BraceWrapping.AfterControlStatement && I + 2 != E &&
486           !I[2]->First->is(tok::r_brace))
487         return 0;
488       if (!Style.AllowShortLoopsOnASingleLine &&
489           Line.First->isOneOf(tok::kw_while, tok::kw_do, tok::kw_for) &&
490           !Style.BraceWrapping.AfterControlStatement &&
491           !I[1]->First->is(tok::r_brace))
492         return 0;
493       if (!Style.AllowShortLoopsOnASingleLine &&
494           Line.First->isOneOf(tok::kw_while, tok::kw_do, tok::kw_for) &&
495           Style.BraceWrapping.AfterControlStatement && I + 2 != E &&
496           !I[2]->First->is(tok::r_brace))
497         return 0;
498       // FIXME: Consider an option to allow short exception handling clauses on
499       // a single line.
500       // FIXME: This isn't covered by tests.
501       // FIXME: For catch, __except, __finally the first token on the line
502       // is '}', so this isn't correct here.
503       if (Line.First->isOneOf(tok::kw_try, tok::kw___try, tok::kw_catch,
504                               Keywords.kw___except, tok::kw___finally))
505         return 0;
506     }
507 
508     if (Line.Last->is(tok::l_brace)) {
509       FormatToken *Tok = I[1]->First;
510       if (Tok->is(tok::r_brace) && !Tok->MustBreakBefore &&
511           (Tok->getNextNonComment() == nullptr ||
512            Tok->getNextNonComment()->is(tok::semi))) {
513         // We merge empty blocks even if the line exceeds the column limit.
514         Tok->SpacesRequiredBefore = 0;
515         Tok->CanBreakBefore = true;
516         return 1;
517       } else if (Limit != 0 && !Line.startsWith(tok::kw_namespace) &&
518                  !startsExternCBlock(Line)) {
519         // We don't merge short records.
520         FormatToken *RecordTok =
521             Line.First->is(tok::kw_typedef) ? Line.First->Next : Line.First;
522         if (RecordTok &&
523             RecordTok->isOneOf(tok::kw_class, tok::kw_union, tok::kw_struct,
524                                Keywords.kw_interface))
525           return 0;
526 
527         // Check that we still have three lines and they fit into the limit.
528         if (I + 2 == E || I[2]->Type == LT_Invalid)
529           return 0;
530         Limit = limitConsideringMacros(I + 2, E, Limit);
531 
532         if (!nextTwoLinesFitInto(I, Limit))
533           return 0;
534 
535         // Second, check that the next line does not contain any braces - if it
536         // does, readability declines when putting it into a single line.
537         if (I[1]->Last->is(TT_LineComment))
538           return 0;
539         do {
540           if (Tok->is(tok::l_brace) && Tok->BlockKind != BK_BracedInit)
541             return 0;
542           Tok = Tok->Next;
543         } while (Tok);
544 
545         // Last, check that the third line starts with a closing brace.
546         Tok = I[2]->First;
547         if (Tok->isNot(tok::r_brace))
548           return 0;
549 
550         // Don't merge "if (a) { .. } else {".
551         if (Tok->Next && Tok->Next->is(tok::kw_else))
552           return 0;
553 
554         return 2;
555       }
556     } else if (I[1]->First->is(tok::l_brace)) {
557       if (I[1]->Last->is(TT_LineComment))
558         return 0;
559 
560       // Check for Limit <= 2 to account for the " {".
561       if (Limit <= 2 || (Style.ColumnLimit == 0 && containsMustBreak(*I)))
562         return 0;
563       Limit -= 2;
564       unsigned MergedLines = 0;
565       if (Style.AllowShortBlocksOnASingleLine ||
566           (I[1]->First == I[1]->Last && I + 2 != E &&
567            I[2]->First->is(tok::r_brace))) {
568         MergedLines = tryMergeSimpleBlock(I + 1, E, Limit);
569         // If we managed to merge the block, count the statement header, which
570         // is on a separate line.
571         if (MergedLines > 0)
572           ++MergedLines;
573       }
574       return MergedLines;
575     }
576     return 0;
577   }
578 
579   /// Returns the modified column limit for \p I if it is inside a macro and
580   /// needs a trailing '\'.
581   unsigned
582   limitConsideringMacros(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
583                          SmallVectorImpl<AnnotatedLine *>::const_iterator E,
584                          unsigned Limit) {
585     if (I[0]->InPPDirective && I + 1 != E &&
586         !I[1]->First->HasUnescapedNewline && !I[1]->First->is(tok::eof)) {
587       return Limit < 2 ? 0 : Limit - 2;
588     }
589     return Limit;
590   }
591 
592   bool nextTwoLinesFitInto(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
593                            unsigned Limit) {
594     if (I[1]->First->MustBreakBefore || I[2]->First->MustBreakBefore)
595       return false;
596     return 1 + I[1]->Last->TotalLength + 1 + I[2]->Last->TotalLength <= Limit;
597   }
598 
599   bool containsMustBreak(const AnnotatedLine *Line) {
600     for (const FormatToken *Tok = Line->First; Tok; Tok = Tok->Next) {
601       if (Tok->MustBreakBefore)
602         return true;
603     }
604     return false;
605   }
606 
607   void join(AnnotatedLine &A, const AnnotatedLine &B) {
608     assert(!A.Last->Next);
609     assert(!B.First->Previous);
610     if (B.Affected)
611       A.Affected = true;
612     A.Last->Next = B.First;
613     B.First->Previous = A.Last;
614     B.First->CanBreakBefore = true;
615     unsigned LengthA = A.Last->TotalLength + B.First->SpacesRequiredBefore;
616     for (FormatToken *Tok = B.First; Tok; Tok = Tok->Next) {
617       Tok->TotalLength += LengthA;
618       A.Last = Tok;
619     }
620   }
621 
622   const FormatStyle &Style;
623   const AdditionalKeywords &Keywords;
624   const SmallVectorImpl<AnnotatedLine *>::const_iterator End;
625 
626   SmallVectorImpl<AnnotatedLine *>::const_iterator Next;
627   const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines;
628 };
629 
630 static void markFinalized(FormatToken *Tok) {
631   for (; Tok; Tok = Tok->Next) {
632     Tok->Finalized = true;
633     for (AnnotatedLine *Child : Tok->Children)
634       markFinalized(Child->First);
635   }
636 }
637 
638 #ifndef NDEBUG
639 static void printLineState(const LineState &State) {
640   llvm::dbgs() << "State: ";
641   for (const ParenState &P : State.Stack) {
642     llvm::dbgs() << P.Indent << "|" << P.LastSpace << "|" << P.NestedBlockIndent
643                  << " ";
644   }
645   llvm::dbgs() << State.NextToken->TokenText << "\n";
646 }
647 #endif
648 
649 /// \brief Base class for classes that format one \c AnnotatedLine.
650 class LineFormatter {
651 public:
652   LineFormatter(ContinuationIndenter *Indenter, WhitespaceManager *Whitespaces,
653                 const FormatStyle &Style,
654                 UnwrappedLineFormatter *BlockFormatter)
655       : Indenter(Indenter), Whitespaces(Whitespaces), Style(Style),
656         BlockFormatter(BlockFormatter) {}
657   virtual ~LineFormatter() {}
658 
659   /// \brief Formats an \c AnnotatedLine and returns the penalty.
660   ///
661   /// If \p DryRun is \c false, directly applies the changes.
662   virtual unsigned formatLine(const AnnotatedLine &Line, unsigned FirstIndent,
663                               bool DryRun) = 0;
664 
665 protected:
666   /// \brief If the \p State's next token is an r_brace closing a nested block,
667   /// format the nested block before it.
668   ///
669   /// Returns \c true if all children could be placed successfully and adapts
670   /// \p Penalty as well as \p State. If \p DryRun is false, also directly
671   /// creates changes using \c Whitespaces.
672   ///
673   /// The crucial idea here is that children always get formatted upon
674   /// encountering the closing brace right after the nested block. Now, if we
675   /// are currently trying to keep the "}" on the same line (i.e. \p NewLine is
676   /// \c false), the entire block has to be kept on the same line (which is only
677   /// possible if it fits on the line, only contains a single statement, etc.
678   ///
679   /// If \p NewLine is true, we format the nested block on separate lines, i.e.
680   /// break after the "{", format all lines with correct indentation and the put
681   /// the closing "}" on yet another new line.
682   ///
683   /// This enables us to keep the simple structure of the
684   /// \c UnwrappedLineFormatter, where we only have two options for each token:
685   /// break or don't break.
686   bool formatChildren(LineState &State, bool NewLine, bool DryRun,
687                       unsigned &Penalty) {
688     const FormatToken *LBrace = State.NextToken->getPreviousNonComment();
689     FormatToken &Previous = *State.NextToken->Previous;
690     if (!LBrace || LBrace->isNot(tok::l_brace) ||
691         LBrace->BlockKind != BK_Block || Previous.Children.size() == 0)
692       // The previous token does not open a block. Nothing to do. We don't
693       // assert so that we can simply call this function for all tokens.
694       return true;
695 
696     if (NewLine) {
697       int AdditionalIndent = State.Stack.back().Indent -
698                              Previous.Children[0]->Level * Style.IndentWidth;
699 
700       Penalty +=
701           BlockFormatter->format(Previous.Children, DryRun, AdditionalIndent,
702                                  /*FixBadIndentation=*/true);
703       return true;
704     }
705 
706     if (Previous.Children[0]->First->MustBreakBefore)
707       return false;
708 
709     // Cannot merge into one line if this line ends on a comment.
710     if (Previous.is(tok::comment))
711       return false;
712 
713     // Cannot merge multiple statements into a single line.
714     if (Previous.Children.size() > 1)
715       return false;
716 
717     const AnnotatedLine *Child = Previous.Children[0];
718     // We can't put the closing "}" on a line with a trailing comment.
719     if (Child->Last->isTrailingComment())
720       return false;
721 
722     // If the child line exceeds the column limit, we wouldn't want to merge it.
723     // We add +2 for the trailing " }".
724     if (Style.ColumnLimit > 0 &&
725         Child->Last->TotalLength + State.Column + 2 > Style.ColumnLimit)
726       return false;
727 
728     if (!DryRun) {
729       Whitespaces->replaceWhitespace(
730           *Child->First, /*Newlines=*/0, /*Spaces=*/1,
731           /*StartOfTokenColumn=*/State.Column, State.Line->InPPDirective);
732     }
733     Penalty += formatLine(*Child, State.Column + 1, DryRun);
734 
735     State.Column += 1 + Child->Last->TotalLength;
736     return true;
737   }
738 
739   ContinuationIndenter *Indenter;
740 
741 private:
742   WhitespaceManager *Whitespaces;
743   const FormatStyle &Style;
744   UnwrappedLineFormatter *BlockFormatter;
745 };
746 
747 /// \brief Formatter that keeps the existing line breaks.
748 class NoColumnLimitLineFormatter : public LineFormatter {
749 public:
750   NoColumnLimitLineFormatter(ContinuationIndenter *Indenter,
751                              WhitespaceManager *Whitespaces,
752                              const FormatStyle &Style,
753                              UnwrappedLineFormatter *BlockFormatter)
754       : LineFormatter(Indenter, Whitespaces, Style, BlockFormatter) {}
755 
756   /// \brief Formats the line, simply keeping all of the input's line breaking
757   /// decisions.
758   unsigned formatLine(const AnnotatedLine &Line, unsigned FirstIndent,
759                       bool DryRun) override {
760     assert(!DryRun);
761     LineState State =
762         Indenter->getInitialState(FirstIndent, &Line, /*DryRun=*/false);
763     while (State.NextToken) {
764       bool Newline =
765           Indenter->mustBreak(State) ||
766           (Indenter->canBreak(State) && State.NextToken->NewlinesBefore > 0);
767       unsigned Penalty = 0;
768       formatChildren(State, Newline, /*DryRun=*/false, Penalty);
769       Indenter->addTokenToState(State, Newline, /*DryRun=*/false);
770     }
771     return 0;
772   }
773 };
774 
775 /// \brief Formatter that puts all tokens into a single line without breaks.
776 class NoLineBreakFormatter : public LineFormatter {
777 public:
778   NoLineBreakFormatter(ContinuationIndenter *Indenter,
779                        WhitespaceManager *Whitespaces, const FormatStyle &Style,
780                        UnwrappedLineFormatter *BlockFormatter)
781       : LineFormatter(Indenter, Whitespaces, Style, BlockFormatter) {}
782 
783   /// \brief Puts all tokens into a single line.
784   unsigned formatLine(const AnnotatedLine &Line, unsigned FirstIndent,
785                       bool DryRun) override {
786     unsigned Penalty = 0;
787     LineState State = Indenter->getInitialState(FirstIndent, &Line, DryRun);
788     while (State.NextToken) {
789       formatChildren(State, /*Newline=*/false, DryRun, Penalty);
790       Indenter->addTokenToState(
791           State, /*Newline=*/State.NextToken->MustBreakBefore, DryRun);
792     }
793     return Penalty;
794   }
795 };
796 
797 /// \brief Finds the best way to break lines.
798 class OptimizingLineFormatter : public LineFormatter {
799 public:
800   OptimizingLineFormatter(ContinuationIndenter *Indenter,
801                           WhitespaceManager *Whitespaces,
802                           const FormatStyle &Style,
803                           UnwrappedLineFormatter *BlockFormatter)
804       : LineFormatter(Indenter, Whitespaces, Style, BlockFormatter) {}
805 
806   /// \brief Formats the line by finding the best line breaks with line lengths
807   /// below the column limit.
808   unsigned formatLine(const AnnotatedLine &Line, unsigned FirstIndent,
809                       bool DryRun) override {
810     LineState State = Indenter->getInitialState(FirstIndent, &Line, DryRun);
811 
812     // If the ObjC method declaration does not fit on a line, we should format
813     // it with one arg per line.
814     if (State.Line->Type == LT_ObjCMethodDecl)
815       State.Stack.back().BreakBeforeParameter = true;
816 
817     // Find best solution in solution space.
818     return analyzeSolutionSpace(State, DryRun);
819   }
820 
821 private:
822   struct CompareLineStatePointers {
823     bool operator()(LineState *obj1, LineState *obj2) const {
824       return *obj1 < *obj2;
825     }
826   };
827 
828   /// \brief A pair of <penalty, count> that is used to prioritize the BFS on.
829   ///
830   /// In case of equal penalties, we want to prefer states that were inserted
831   /// first. During state generation we make sure that we insert states first
832   /// that break the line as late as possible.
833   typedef std::pair<unsigned, unsigned> OrderedPenalty;
834 
835   /// \brief An edge in the solution space from \c Previous->State to \c State,
836   /// inserting a newline dependent on the \c NewLine.
837   struct StateNode {
838     StateNode(const LineState &State, bool NewLine, StateNode *Previous)
839         : State(State), NewLine(NewLine), Previous(Previous) {}
840     LineState State;
841     bool NewLine;
842     StateNode *Previous;
843   };
844 
845   /// \brief An item in the prioritized BFS search queue. The \c StateNode's
846   /// \c State has the given \c OrderedPenalty.
847   typedef std::pair<OrderedPenalty, StateNode *> QueueItem;
848 
849   /// \brief The BFS queue type.
850   typedef std::priority_queue<QueueItem, std::vector<QueueItem>,
851                               std::greater<QueueItem>> QueueType;
852 
853   /// \brief Analyze the entire solution space starting from \p InitialState.
854   ///
855   /// This implements a variant of Dijkstra's algorithm on the graph that spans
856   /// the solution space (\c LineStates are the nodes). The algorithm tries to
857   /// find the shortest path (the one with lowest penalty) from \p InitialState
858   /// to a state where all tokens are placed. Returns the penalty.
859   ///
860   /// If \p DryRun is \c false, directly applies the changes.
861   unsigned analyzeSolutionSpace(LineState &InitialState, bool DryRun) {
862     std::set<LineState *, CompareLineStatePointers> Seen;
863 
864     // Increasing count of \c StateNode items we have created. This is used to
865     // create a deterministic order independent of the container.
866     unsigned Count = 0;
867     QueueType Queue;
868 
869     // Insert start element into queue.
870     StateNode *Node =
871         new (Allocator.Allocate()) StateNode(InitialState, false, nullptr);
872     Queue.push(QueueItem(OrderedPenalty(0, Count), Node));
873     ++Count;
874 
875     unsigned Penalty = 0;
876 
877     // While not empty, take first element and follow edges.
878     while (!Queue.empty()) {
879       Penalty = Queue.top().first.first;
880       StateNode *Node = Queue.top().second;
881       if (!Node->State.NextToken) {
882         DEBUG(llvm::dbgs() << "\n---\nPenalty for line: " << Penalty << "\n");
883         break;
884       }
885       Queue.pop();
886 
887       // Cut off the analysis of certain solutions if the analysis gets too
888       // complex. See description of IgnoreStackForComparison.
889       if (Count > 50000)
890         Node->State.IgnoreStackForComparison = true;
891 
892       if (!Seen.insert(&Node->State).second)
893         // State already examined with lower penalty.
894         continue;
895 
896       FormatDecision LastFormat = Node->State.NextToken->Decision;
897       if (LastFormat == FD_Unformatted || LastFormat == FD_Continue)
898         addNextStateToQueue(Penalty, Node, /*NewLine=*/false, &Count, &Queue);
899       if (LastFormat == FD_Unformatted || LastFormat == FD_Break)
900         addNextStateToQueue(Penalty, Node, /*NewLine=*/true, &Count, &Queue);
901     }
902 
903     if (Queue.empty()) {
904       // We were unable to find a solution, do nothing.
905       // FIXME: Add diagnostic?
906       DEBUG(llvm::dbgs() << "Could not find a solution.\n");
907       return 0;
908     }
909 
910     // Reconstruct the solution.
911     if (!DryRun)
912       reconstructPath(InitialState, Queue.top().second);
913 
914     DEBUG(llvm::dbgs() << "Total number of analyzed states: " << Count << "\n");
915     DEBUG(llvm::dbgs() << "---\n");
916 
917     return Penalty;
918   }
919 
920   /// \brief Add the following state to the analysis queue \c Queue.
921   ///
922   /// Assume the current state is \p PreviousNode and has been reached with a
923   /// penalty of \p Penalty. Insert a line break if \p NewLine is \c true.
924   void addNextStateToQueue(unsigned Penalty, StateNode *PreviousNode,
925                            bool NewLine, unsigned *Count, QueueType *Queue) {
926     if (NewLine && !Indenter->canBreak(PreviousNode->State))
927       return;
928     if (!NewLine && Indenter->mustBreak(PreviousNode->State))
929       return;
930 
931     StateNode *Node = new (Allocator.Allocate())
932         StateNode(PreviousNode->State, NewLine, PreviousNode);
933     if (!formatChildren(Node->State, NewLine, /*DryRun=*/true, Penalty))
934       return;
935 
936     Penalty += Indenter->addTokenToState(Node->State, NewLine, true);
937 
938     Queue->push(QueueItem(OrderedPenalty(Penalty, *Count), Node));
939     ++(*Count);
940   }
941 
942   /// \brief Applies the best formatting by reconstructing the path in the
943   /// solution space that leads to \c Best.
944   void reconstructPath(LineState &State, StateNode *Best) {
945     std::deque<StateNode *> Path;
946     // We do not need a break before the initial token.
947     while (Best->Previous) {
948       Path.push_front(Best);
949       Best = Best->Previous;
950     }
951     for (std::deque<StateNode *>::iterator I = Path.begin(), E = Path.end();
952          I != E; ++I) {
953       unsigned Penalty = 0;
954       formatChildren(State, (*I)->NewLine, /*DryRun=*/false, Penalty);
955       Penalty += Indenter->addTokenToState(State, (*I)->NewLine, false);
956 
957       DEBUG({
958         printLineState((*I)->Previous->State);
959         if ((*I)->NewLine) {
960           llvm::dbgs() << "Penalty for placing "
961                        << (*I)->Previous->State.NextToken->Tok.getName() << ": "
962                        << Penalty << "\n";
963         }
964       });
965     }
966   }
967 
968   llvm::SpecificBumpPtrAllocator<StateNode> Allocator;
969 };
970 
971 } // anonymous namespace
972 
973 unsigned
974 UnwrappedLineFormatter::format(const SmallVectorImpl<AnnotatedLine *> &Lines,
975                                bool DryRun, int AdditionalIndent,
976                                bool FixBadIndentation) {
977   LineJoiner Joiner(Style, Keywords, Lines);
978 
979   // Try to look up already computed penalty in DryRun-mode.
980   std::pair<const SmallVectorImpl<AnnotatedLine *> *, unsigned> CacheKey(
981       &Lines, AdditionalIndent);
982   auto CacheIt = PenaltyCache.find(CacheKey);
983   if (DryRun && CacheIt != PenaltyCache.end())
984     return CacheIt->second;
985 
986   assert(!Lines.empty());
987   unsigned Penalty = 0;
988   LevelIndentTracker IndentTracker(Style, Keywords, Lines[0]->Level,
989                                    AdditionalIndent);
990   const AnnotatedLine *PreviousLine = nullptr;
991   const AnnotatedLine *NextLine = nullptr;
992 
993   // The minimum level of consecutive lines that have been formatted.
994   unsigned RangeMinLevel = UINT_MAX;
995 
996   for (const AnnotatedLine *Line =
997            Joiner.getNextMergedLine(DryRun, IndentTracker);
998        Line; Line = NextLine) {
999     const AnnotatedLine &TheLine = *Line;
1000     unsigned Indent = IndentTracker.getIndent();
1001 
1002     // We continue formatting unchanged lines to adjust their indent, e.g. if a
1003     // scope was added. However, we need to carefully stop doing this when we
1004     // exit the scope of affected lines to prevent indenting a the entire
1005     // remaining file if it currently missing a closing brace.
1006     bool ContinueFormatting =
1007         TheLine.Level > RangeMinLevel ||
1008         (TheLine.Level == RangeMinLevel && !TheLine.startsWith(tok::r_brace));
1009 
1010     bool FixIndentation = (FixBadIndentation || ContinueFormatting) &&
1011                           Indent != TheLine.First->OriginalColumn;
1012     bool ShouldFormat = TheLine.Affected || FixIndentation;
1013     // We cannot format this line; if the reason is that the line had a
1014     // parsing error, remember that.
1015     if (ShouldFormat && TheLine.Type == LT_Invalid && Status) {
1016       Status->FormatComplete = false;
1017       Status->Line =
1018           SourceMgr.getSpellingLineNumber(TheLine.First->Tok.getLocation());
1019     }
1020 
1021     if (ShouldFormat && TheLine.Type != LT_Invalid) {
1022       if (!DryRun)
1023         formatFirstToken(TheLine, PreviousLine, Indent);
1024 
1025       NextLine = Joiner.getNextMergedLine(DryRun, IndentTracker);
1026       unsigned ColumnLimit = getColumnLimit(TheLine.InPPDirective, NextLine);
1027       bool FitsIntoOneLine =
1028           TheLine.Last->TotalLength + Indent <= ColumnLimit ||
1029           (TheLine.Type == LT_ImportStatement &&
1030            (Style.Language != FormatStyle::LK_JavaScript ||
1031             !Style.JavaScriptWrapImports));
1032 
1033       if (Style.ColumnLimit == 0)
1034         NoColumnLimitLineFormatter(Indenter, Whitespaces, Style, this)
1035             .formatLine(TheLine, Indent, DryRun);
1036       else if (FitsIntoOneLine)
1037         Penalty += NoLineBreakFormatter(Indenter, Whitespaces, Style, this)
1038                        .formatLine(TheLine, Indent, DryRun);
1039       else
1040         Penalty += OptimizingLineFormatter(Indenter, Whitespaces, Style, this)
1041                        .formatLine(TheLine, Indent, DryRun);
1042       RangeMinLevel = std::min(RangeMinLevel, TheLine.Level);
1043     } else {
1044       // If no token in the current line is affected, we still need to format
1045       // affected children.
1046       if (TheLine.ChildrenAffected)
1047         for (const FormatToken *Tok = TheLine.First; Tok; Tok = Tok->Next)
1048           if (!Tok->Children.empty())
1049             format(Tok->Children, DryRun);
1050 
1051       // Adapt following lines on the current indent level to the same level
1052       // unless the current \c AnnotatedLine is not at the beginning of a line.
1053       bool StartsNewLine =
1054           TheLine.First->NewlinesBefore > 0 || TheLine.First->IsFirst;
1055       if (StartsNewLine)
1056         IndentTracker.adjustToUnmodifiedLine(TheLine);
1057       if (!DryRun) {
1058         bool ReformatLeadingWhitespace =
1059             StartsNewLine && ((PreviousLine && PreviousLine->Affected) ||
1060                               TheLine.LeadingEmptyLinesAffected);
1061         // Format the first token.
1062         if (ReformatLeadingWhitespace)
1063           formatFirstToken(TheLine, PreviousLine,
1064                            TheLine.First->OriginalColumn);
1065         else
1066           Whitespaces->addUntouchableToken(*TheLine.First,
1067                                            TheLine.InPPDirective);
1068 
1069         // Notify the WhitespaceManager about the unchanged whitespace.
1070         for (FormatToken *Tok = TheLine.First->Next; Tok; Tok = Tok->Next)
1071           Whitespaces->addUntouchableToken(*Tok, TheLine.InPPDirective);
1072       }
1073       NextLine = Joiner.getNextMergedLine(DryRun, IndentTracker);
1074       RangeMinLevel = UINT_MAX;
1075     }
1076     if (!DryRun)
1077       markFinalized(TheLine.First);
1078     PreviousLine = &TheLine;
1079   }
1080   PenaltyCache[CacheKey] = Penalty;
1081   return Penalty;
1082 }
1083 
1084 void UnwrappedLineFormatter::formatFirstToken(const AnnotatedLine &Line,
1085                                               const AnnotatedLine *PreviousLine,
1086                                               unsigned Indent) {
1087   FormatToken& RootToken = *Line.First;
1088   if (RootToken.is(tok::eof)) {
1089     unsigned Newlines = std::min(RootToken.NewlinesBefore, 1u);
1090     Whitespaces->replaceWhitespace(RootToken, Newlines, /*Spaces=*/0,
1091                                    /*StartOfTokenColumn=*/0);
1092     return;
1093   }
1094   unsigned Newlines =
1095       std::min(RootToken.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1);
1096   // Remove empty lines before "}" where applicable.
1097   if (RootToken.is(tok::r_brace) &&
1098       (!RootToken.Next ||
1099        (RootToken.Next->is(tok::semi) && !RootToken.Next->Next)))
1100     Newlines = std::min(Newlines, 1u);
1101   if (Newlines == 0 && !RootToken.IsFirst)
1102     Newlines = 1;
1103   if (RootToken.IsFirst && !RootToken.HasUnescapedNewline)
1104     Newlines = 0;
1105 
1106   // Preprocessor directives get indented after the hash, if indented.
1107   if (Line.Type == LT_PreprocessorDirective || Line.Type == LT_ImportStatement)
1108     Indent = 0;
1109 
1110   // Remove empty lines after "{".
1111   if (!Style.KeepEmptyLinesAtTheStartOfBlocks && PreviousLine &&
1112       PreviousLine->Last->is(tok::l_brace) &&
1113       PreviousLine->First->isNot(tok::kw_namespace) &&
1114       !startsExternCBlock(*PreviousLine))
1115     Newlines = 1;
1116 
1117   // Insert extra new line before access specifiers.
1118   if (PreviousLine && PreviousLine->Last->isOneOf(tok::semi, tok::r_brace) &&
1119       RootToken.isAccessSpecifier() && RootToken.NewlinesBefore == 1)
1120     ++Newlines;
1121 
1122   // Remove empty lines after access specifiers.
1123   if (PreviousLine && PreviousLine->First->isAccessSpecifier() &&
1124       (!PreviousLine->InPPDirective || !RootToken.HasUnescapedNewline))
1125     Newlines = std::min(1u, Newlines);
1126 
1127   Whitespaces->replaceWhitespace(RootToken, Newlines, Indent, Indent,
1128                                  Line.InPPDirective &&
1129                                      !RootToken.HasUnescapedNewline);
1130 }
1131 
1132 unsigned
1133 UnwrappedLineFormatter::getColumnLimit(bool InPPDirective,
1134                                        const AnnotatedLine *NextLine) const {
1135   // In preprocessor directives reserve two chars for trailing " \" if the
1136   // next line continues the preprocessor directive.
1137   bool ContinuesPPDirective =
1138       InPPDirective &&
1139       // If there is no next line, this is likely a child line and the parent
1140       // continues the preprocessor directive.
1141       (!NextLine ||
1142        (NextLine->InPPDirective &&
1143         // If there is an unescaped newline between this line and the next, the
1144         // next line starts a new preprocessor directive.
1145         !NextLine->First->HasUnescapedNewline));
1146   return Style.ColumnLimit - (ContinuesPPDirective ? 2 : 0);
1147 }
1148 
1149 } // namespace format
1150 } // namespace clang
1151