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