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