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