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