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