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