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