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