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