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