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