1 //===--- UnwrappedLineFormatter.cpp - Format C++ code ---------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include "UnwrappedLineFormatter.h"
11 #include "WhitespaceManager.h"
12 #include "llvm/Support/Debug.h"
13 
14 #define DEBUG_TYPE "format-formatter"
15 
16 namespace clang {
17 namespace format {
18 
19 namespace {
20 
21 bool startsExternCBlock(const AnnotatedLine &Line) {
22   const FormatToken *Next = Line.First->getNextNonComment();
23   const FormatToken *NextNext = Next ? Next->getNextNonComment() : nullptr;
24   return Line.First->is(tok::kw_extern) && Next && Next->isStringLiteral() &&
25          NextNext && NextNext->is(tok::l_brace);
26 }
27 
28 class LineJoiner {
29 public:
30   LineJoiner(const FormatStyle &Style) : Style(Style) {}
31 
32   /// \brief Calculates how many lines can be merged into 1 starting at \p I.
33   unsigned
34   tryFitMultipleLinesInOne(unsigned Indent,
35                            SmallVectorImpl<AnnotatedLine *>::const_iterator I,
36                            SmallVectorImpl<AnnotatedLine *>::const_iterator E) {
37     // We can never merge stuff if there are trailing line comments.
38     const AnnotatedLine *TheLine = *I;
39     if (TheLine->Last->is(TT_LineComment))
40       return 0;
41 
42     if (Style.ColumnLimit > 0 && Indent > Style.ColumnLimit)
43       return 0;
44 
45     unsigned Limit =
46         Style.ColumnLimit == 0 ? UINT_MAX : Style.ColumnLimit - Indent;
47     // If we already exceed the column limit, we set 'Limit' to 0. The different
48     // tryMerge..() functions can then decide whether to still do merging.
49     Limit = TheLine->Last->TotalLength > Limit
50                 ? 0
51                 : Limit - TheLine->Last->TotalLength;
52 
53     if (I + 1 == E || I[1]->Type == LT_Invalid || I[1]->First->MustBreakBefore)
54       return 0;
55 
56     // FIXME: TheLine->Level != 0 might or might not be the right check to do.
57     // If necessary, change to something smarter.
58     bool MergeShortFunctions =
59         Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_All ||
60         (Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_Empty &&
61          I[1]->First->is(tok::r_brace)) ||
62         (Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_Inline &&
63          TheLine->Level != 0);
64 
65     if (TheLine->Last->is(TT_FunctionLBrace) &&
66         TheLine->First != TheLine->Last) {
67       return MergeShortFunctions ? tryMergeSimpleBlock(I, E, Limit) : 0;
68     }
69     if (TheLine->Last->is(tok::l_brace)) {
70       return Style.BreakBeforeBraces == FormatStyle::BS_Attach
71                  ? tryMergeSimpleBlock(I, E, Limit)
72                  : 0;
73     }
74     if (I[1]->First->is(TT_FunctionLBrace) &&
75         Style.BreakBeforeBraces != FormatStyle::BS_Attach) {
76       if (I[1]->Last->is(TT_LineComment))
77         return 0;
78 
79       // Check for Limit <= 2 to account for the " {".
80       if (Limit <= 2 || (Style.ColumnLimit == 0 && containsMustBreak(TheLine)))
81         return 0;
82       Limit -= 2;
83 
84       unsigned MergedLines = 0;
85       if (MergeShortFunctions) {
86         MergedLines = tryMergeSimpleBlock(I + 1, E, Limit);
87         // If we managed to merge the block, count the function header, which is
88         // on a separate line.
89         if (MergedLines > 0)
90           ++MergedLines;
91       }
92       return MergedLines;
93     }
94     if (TheLine->First->is(tok::kw_if)) {
95       return Style.AllowShortIfStatementsOnASingleLine
96                  ? tryMergeSimpleControlStatement(I, E, Limit)
97                  : 0;
98     }
99     if (TheLine->First->isOneOf(tok::kw_for, tok::kw_while)) {
100       return Style.AllowShortLoopsOnASingleLine
101                  ? tryMergeSimpleControlStatement(I, E, Limit)
102                  : 0;
103     }
104     if (TheLine->First->isOneOf(tok::kw_case, tok::kw_default)) {
105       return Style.AllowShortCaseLabelsOnASingleLine
106                  ? tryMergeShortCaseLabels(I, E, Limit)
107                  : 0;
108     }
109     if (TheLine->InPPDirective &&
110         (TheLine->First->HasUnescapedNewline || TheLine->First->IsFirst)) {
111       return tryMergeSimplePPDirective(I, E, Limit);
112     }
113     return 0;
114   }
115 
116 private:
117   unsigned
118   tryMergeSimplePPDirective(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
119                             SmallVectorImpl<AnnotatedLine *>::const_iterator E,
120                             unsigned Limit) {
121     if (Limit == 0)
122       return 0;
123     if (!I[1]->InPPDirective || I[1]->First->HasUnescapedNewline)
124       return 0;
125     if (I + 2 != E && I[2]->InPPDirective && !I[2]->First->HasUnescapedNewline)
126       return 0;
127     if (1 + I[1]->Last->TotalLength > Limit)
128       return 0;
129     return 1;
130   }
131 
132   unsigned tryMergeSimpleControlStatement(
133       SmallVectorImpl<AnnotatedLine *>::const_iterator I,
134       SmallVectorImpl<AnnotatedLine *>::const_iterator E, unsigned Limit) {
135     if (Limit == 0)
136       return 0;
137     if ((Style.BreakBeforeBraces == FormatStyle::BS_Allman ||
138          Style.BreakBeforeBraces == FormatStyle::BS_GNU) &&
139         (I[1]->First->is(tok::l_brace) && !Style.AllowShortBlocksOnASingleLine))
140       return 0;
141     if (I[1]->InPPDirective != (*I)->InPPDirective ||
142         (I[1]->InPPDirective && I[1]->First->HasUnescapedNewline))
143       return 0;
144     Limit = limitConsideringMacros(I + 1, E, Limit);
145     AnnotatedLine &Line = **I;
146     if (Line.Last->isNot(tok::r_paren))
147       return 0;
148     if (1 + I[1]->Last->TotalLength > Limit)
149       return 0;
150     if (I[1]->First->isOneOf(tok::semi, tok::kw_if, tok::kw_for,
151                              tok::kw_while, TT_LineComment))
152       return 0;
153     // Only inline simple if's (no nested if or else).
154     if (I + 2 != E && Line.First->is(tok::kw_if) &&
155         I[2]->First->is(tok::kw_else))
156       return 0;
157     return 1;
158   }
159 
160   unsigned tryMergeShortCaseLabels(
161       SmallVectorImpl<AnnotatedLine *>::const_iterator I,
162       SmallVectorImpl<AnnotatedLine *>::const_iterator E, unsigned Limit) {
163     if (Limit == 0 || I + 1 == E ||
164         I[1]->First->isOneOf(tok::kw_case, tok::kw_default))
165       return 0;
166     unsigned NumStmts = 0;
167     unsigned Length = 0;
168     bool InPPDirective = I[0]->InPPDirective;
169     for (; NumStmts < 3; ++NumStmts) {
170       if (I + 1 + NumStmts == E)
171         break;
172       const AnnotatedLine *Line = I[1 + NumStmts];
173       if (Line->InPPDirective != InPPDirective)
174         break;
175       if (Line->First->isOneOf(tok::kw_case, tok::kw_default, tok::r_brace))
176         break;
177       if (Line->First->isOneOf(tok::kw_if, tok::kw_for, tok::kw_switch,
178                                tok::kw_while, tok::comment))
179         return 0;
180       Length += I[1 + NumStmts]->Last->TotalLength + 1; // 1 for the space.
181     }
182     if (NumStmts == 0 || NumStmts == 3 || Length > Limit)
183       return 0;
184     return NumStmts;
185   }
186 
187   unsigned
188   tryMergeSimpleBlock(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
189                       SmallVectorImpl<AnnotatedLine *>::const_iterator E,
190                       unsigned Limit) {
191     AnnotatedLine &Line = **I;
192 
193     // Don't merge ObjC @ keywords and methods.
194     if (Style.Language != FormatStyle::LK_Java &&
195         Line.First->isOneOf(tok::at, tok::minus, tok::plus))
196       return 0;
197 
198     // Check that the current line allows merging. This depends on whether we
199     // are in a control flow statements as well as several style flags.
200     if (Line.First->isOneOf(tok::kw_else, tok::kw_case))
201       return 0;
202     if (Line.First->isOneOf(tok::kw_if, tok::kw_while, tok::kw_do, tok::kw_try,
203                             tok::kw_catch, tok::kw_for, tok::r_brace)) {
204       if (!Style.AllowShortBlocksOnASingleLine)
205         return 0;
206       if (!Style.AllowShortIfStatementsOnASingleLine &&
207           Line.First->is(tok::kw_if))
208         return 0;
209       if (!Style.AllowShortLoopsOnASingleLine &&
210           Line.First->isOneOf(tok::kw_while, tok::kw_do, tok::kw_for))
211         return 0;
212       // FIXME: Consider an option to allow short exception handling clauses on
213       // a single line.
214       if (Line.First->isOneOf(tok::kw_try, tok::kw_catch))
215         return 0;
216     }
217 
218     FormatToken *Tok = I[1]->First;
219     if (Tok->is(tok::r_brace) && !Tok->MustBreakBefore &&
220         (Tok->getNextNonComment() == nullptr ||
221          Tok->getNextNonComment()->is(tok::semi))) {
222       // We merge empty blocks even if the line exceeds the column limit.
223       Tok->SpacesRequiredBefore = 0;
224       Tok->CanBreakBefore = true;
225       return 1;
226     } else if (Limit != 0 && Line.First->isNot(tok::kw_namespace) &&
227                !startsExternCBlock(Line)) {
228       // We don't merge short records.
229       if (Line.First->isOneOf(tok::kw_class, tok::kw_union, tok::kw_struct))
230         return 0;
231 
232       // Check that we still have three lines and they fit into the limit.
233       if (I + 2 == E || I[2]->Type == LT_Invalid)
234         return 0;
235       Limit = limitConsideringMacros(I + 2, E, Limit);
236 
237       if (!nextTwoLinesFitInto(I, Limit))
238         return 0;
239 
240       // Second, check that the next line does not contain any braces - if it
241       // does, readability declines when putting it into a single line.
242       if (I[1]->Last->is(TT_LineComment))
243         return 0;
244       do {
245         if (Tok->is(tok::l_brace) && Tok->BlockKind != BK_BracedInit)
246           return 0;
247         Tok = Tok->Next;
248       } while (Tok);
249 
250       // Last, check that the third line starts with a closing brace.
251       Tok = I[2]->First;
252       if (Tok->isNot(tok::r_brace))
253         return 0;
254 
255       return 2;
256     }
257     return 0;
258   }
259 
260   /// Returns the modified column limit for \p I if it is inside a macro and
261   /// needs a trailing '\'.
262   unsigned
263   limitConsideringMacros(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
264                          SmallVectorImpl<AnnotatedLine *>::const_iterator E,
265                          unsigned Limit) {
266     if (I[0]->InPPDirective && I + 1 != E &&
267         !I[1]->First->HasUnescapedNewline && !I[1]->First->is(tok::eof)) {
268       return Limit < 2 ? 0 : Limit - 2;
269     }
270     return Limit;
271   }
272 
273   bool nextTwoLinesFitInto(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
274                            unsigned Limit) {
275     if (I[1]->First->MustBreakBefore || I[2]->First->MustBreakBefore)
276       return false;
277     return 1 + I[1]->Last->TotalLength + 1 + I[2]->Last->TotalLength <= Limit;
278   }
279 
280   bool containsMustBreak(const AnnotatedLine *Line) {
281     for (const FormatToken *Tok = Line->First; Tok; Tok = Tok->Next) {
282       if (Tok->MustBreakBefore)
283         return true;
284     }
285     return false;
286   }
287 
288   const FormatStyle &Style;
289 };
290 
291 class NoColumnLimitFormatter {
292 public:
293   NoColumnLimitFormatter(ContinuationIndenter *Indenter) : Indenter(Indenter) {}
294 
295   /// \brief Formats the line starting at \p State, simply keeping all of the
296   /// input's line breaking decisions.
297   void format(unsigned FirstIndent, const AnnotatedLine *Line) {
298     LineState State =
299         Indenter->getInitialState(FirstIndent, Line, /*DryRun=*/false);
300     while (State.NextToken) {
301       bool Newline =
302           Indenter->mustBreak(State) ||
303           (Indenter->canBreak(State) && State.NextToken->NewlinesBefore > 0);
304       Indenter->addTokenToState(State, Newline, /*DryRun=*/false);
305     }
306   }
307 
308 private:
309   ContinuationIndenter *Indenter;
310 };
311 
312 
313 static void markFinalized(FormatToken *Tok) {
314   for (; Tok; Tok = Tok->Next) {
315     Tok->Finalized = true;
316     for (AnnotatedLine *Child : Tok->Children)
317       markFinalized(Child->First);
318   }
319 }
320 
321 } // namespace
322 
323 unsigned
324 UnwrappedLineFormatter::format(const SmallVectorImpl<AnnotatedLine *> &Lines,
325                                bool DryRun, int AdditionalIndent,
326                                bool FixBadIndentation) {
327   LineJoiner Joiner(Style);
328 
329   // Try to look up already computed penalty in DryRun-mode.
330   std::pair<const SmallVectorImpl<AnnotatedLine *> *, unsigned> CacheKey(
331       &Lines, AdditionalIndent);
332   auto CacheIt = PenaltyCache.find(CacheKey);
333   if (DryRun && CacheIt != PenaltyCache.end())
334     return CacheIt->second;
335 
336   assert(!Lines.empty());
337   unsigned Penalty = 0;
338   std::vector<int> IndentForLevel;
339   for (unsigned i = 0, e = Lines[0]->Level; i != e; ++i)
340     IndentForLevel.push_back(Style.IndentWidth * i + AdditionalIndent);
341   const AnnotatedLine *PreviousLine = nullptr;
342   for (SmallVectorImpl<AnnotatedLine *>::const_iterator I = Lines.begin(),
343                                                         E = Lines.end();
344        I != E; ++I) {
345     const AnnotatedLine &TheLine = **I;
346     const FormatToken *FirstTok = TheLine.First;
347     int Offset = getIndentOffset(*FirstTok);
348 
349     // Determine indent and try to merge multiple unwrapped lines.
350     unsigned Indent;
351     if (TheLine.InPPDirective) {
352       Indent = TheLine.Level * Style.IndentWidth;
353     } else {
354       while (IndentForLevel.size() <= TheLine.Level)
355         IndentForLevel.push_back(-1);
356       IndentForLevel.resize(TheLine.Level + 1);
357       Indent = getIndent(IndentForLevel, TheLine.Level);
358     }
359     unsigned LevelIndent = Indent;
360     if (static_cast<int>(Indent) + Offset >= 0)
361       Indent += Offset;
362 
363     // Merge multiple lines if possible.
364     unsigned MergedLines = Joiner.tryFitMultipleLinesInOne(Indent, I, E);
365     if (MergedLines > 0 && Style.ColumnLimit == 0) {
366       // Disallow line merging if there is a break at the start of one of the
367       // input lines.
368       for (unsigned i = 0; i < MergedLines; ++i) {
369         if (I[i + 1]->First->NewlinesBefore > 0)
370           MergedLines = 0;
371       }
372     }
373     if (!DryRun) {
374       for (unsigned i = 0; i < MergedLines; ++i) {
375         join(*I[i], *I[i + 1]);
376       }
377     }
378     I += MergedLines;
379 
380     bool FixIndentation =
381         FixBadIndentation && (LevelIndent != FirstTok->OriginalColumn);
382     if (TheLine.First->is(tok::eof)) {
383       if (PreviousLine && PreviousLine->Affected && !DryRun) {
384         // Remove the file's trailing whitespace.
385         unsigned Newlines = std::min(FirstTok->NewlinesBefore, 1u);
386         Whitespaces->replaceWhitespace(*TheLine.First, Newlines,
387                                        /*IndentLevel=*/0, /*Spaces=*/0,
388                                        /*TargetColumn=*/0);
389       }
390     } else if (TheLine.Type != LT_Invalid &&
391                (TheLine.Affected || FixIndentation)) {
392       if (FirstTok->WhitespaceRange.isValid()) {
393         if (!DryRun)
394           formatFirstToken(*TheLine.First, PreviousLine, TheLine.Level, Indent,
395                            TheLine.InPPDirective);
396       } else {
397         Indent = LevelIndent = FirstTok->OriginalColumn;
398       }
399 
400       // If everything fits on a single line, just put it there.
401       unsigned ColumnLimit = Style.ColumnLimit;
402       if (I + 1 != E) {
403         AnnotatedLine *NextLine = I[1];
404         if (NextLine->InPPDirective && !NextLine->First->HasUnescapedNewline)
405           ColumnLimit = getColumnLimit(TheLine.InPPDirective);
406       }
407 
408       if (TheLine.Last->TotalLength + Indent <= ColumnLimit ||
409           TheLine.Type == LT_ImportStatement) {
410         LineState State = Indenter->getInitialState(Indent, &TheLine, DryRun);
411         while (State.NextToken) {
412           formatChildren(State, /*Newline=*/false, DryRun, Penalty);
413           Indenter->addTokenToState(State, /*Newline=*/false, DryRun);
414         }
415       } else if (Style.ColumnLimit == 0) {
416         // FIXME: Implement nested blocks for ColumnLimit = 0.
417         NoColumnLimitFormatter Formatter(Indenter);
418         if (!DryRun)
419           Formatter.format(Indent, &TheLine);
420       } else {
421         Penalty += format(TheLine, Indent, DryRun);
422       }
423 
424       if (!TheLine.InPPDirective)
425         IndentForLevel[TheLine.Level] = LevelIndent;
426     } else if (TheLine.ChildrenAffected) {
427       format(TheLine.Children, DryRun);
428     } else {
429       // Format the first token if necessary, and notify the WhitespaceManager
430       // about the unchanged whitespace.
431       for (FormatToken *Tok = TheLine.First; Tok; Tok = Tok->Next) {
432         if (Tok == TheLine.First && (Tok->NewlinesBefore > 0 || Tok->IsFirst)) {
433           unsigned LevelIndent = Tok->OriginalColumn;
434           if (!DryRun) {
435             // Remove trailing whitespace of the previous line.
436             if ((PreviousLine && PreviousLine->Affected) ||
437                 TheLine.LeadingEmptyLinesAffected) {
438               formatFirstToken(*Tok, PreviousLine, TheLine.Level, LevelIndent,
439                                TheLine.InPPDirective);
440             } else {
441               Whitespaces->addUntouchableToken(*Tok, TheLine.InPPDirective);
442             }
443           }
444 
445           if (static_cast<int>(LevelIndent) - Offset >= 0)
446             LevelIndent -= Offset;
447           if (Tok->isNot(tok::comment) && !TheLine.InPPDirective)
448             IndentForLevel[TheLine.Level] = LevelIndent;
449         } else if (!DryRun) {
450           Whitespaces->addUntouchableToken(*Tok, TheLine.InPPDirective);
451         }
452       }
453     }
454     if (!DryRun)
455       markFinalized(TheLine.First);
456     PreviousLine = *I;
457   }
458   PenaltyCache[CacheKey] = Penalty;
459   return Penalty;
460 }
461 
462 unsigned UnwrappedLineFormatter::format(const AnnotatedLine &Line,
463                                         unsigned FirstIndent, bool DryRun) {
464   LineState State = Indenter->getInitialState(FirstIndent, &Line, DryRun);
465 
466   // If the ObjC method declaration does not fit on a line, we should format
467   // it with one arg per line.
468   if (State.Line->Type == LT_ObjCMethodDecl)
469     State.Stack.back().BreakBeforeParameter = true;
470 
471   // Find best solution in solution space.
472   return analyzeSolutionSpace(State, DryRun);
473 }
474 
475 void UnwrappedLineFormatter::formatFirstToken(FormatToken &RootToken,
476                                               const AnnotatedLine *PreviousLine,
477                                               unsigned IndentLevel,
478                                               unsigned Indent,
479                                               bool InPPDirective) {
480   unsigned Newlines =
481       std::min(RootToken.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1);
482   // Remove empty lines before "}" where applicable.
483   if (RootToken.is(tok::r_brace) &&
484       (!RootToken.Next ||
485        (RootToken.Next->is(tok::semi) && !RootToken.Next->Next)))
486     Newlines = std::min(Newlines, 1u);
487   if (Newlines == 0 && !RootToken.IsFirst)
488     Newlines = 1;
489   if (RootToken.IsFirst && !RootToken.HasUnescapedNewline)
490     Newlines = 0;
491 
492   // Remove empty lines after "{".
493   if (!Style.KeepEmptyLinesAtTheStartOfBlocks && PreviousLine &&
494       PreviousLine->Last->is(tok::l_brace) &&
495       PreviousLine->First->isNot(tok::kw_namespace) &&
496       !startsExternCBlock(*PreviousLine))
497     Newlines = 1;
498 
499   // Insert extra new line before access specifiers.
500   if (PreviousLine && PreviousLine->Last->isOneOf(tok::semi, tok::r_brace) &&
501       RootToken.isAccessSpecifier() && RootToken.NewlinesBefore == 1)
502     ++Newlines;
503 
504   // Remove empty lines after access specifiers.
505   if (PreviousLine && PreviousLine->First->isAccessSpecifier())
506     Newlines = std::min(1u, Newlines);
507 
508   Whitespaces->replaceWhitespace(RootToken, Newlines, IndentLevel, Indent,
509                                  Indent, InPPDirective &&
510                                              !RootToken.HasUnescapedNewline);
511 }
512 
513 /// \brief Get the indent of \p Level from \p IndentForLevel.
514 ///
515 /// \p IndentForLevel must contain the indent for the level \c l
516 /// at \p IndentForLevel[l], or a value < 0 if the indent for
517 /// that level is unknown.
518 unsigned UnwrappedLineFormatter::getIndent(ArrayRef<int> IndentForLevel,
519                                            unsigned Level) {
520   if (IndentForLevel[Level] != -1)
521     return IndentForLevel[Level];
522   if (Level == 0)
523     return 0;
524   return getIndent(IndentForLevel, Level - 1) + Style.IndentWidth;
525 }
526 
527 void UnwrappedLineFormatter::join(AnnotatedLine &A, const AnnotatedLine &B) {
528   assert(!A.Last->Next);
529   assert(!B.First->Previous);
530   if (B.Affected)
531     A.Affected = true;
532   A.Last->Next = B.First;
533   B.First->Previous = A.Last;
534   B.First->CanBreakBefore = true;
535   unsigned LengthA = A.Last->TotalLength + B.First->SpacesRequiredBefore;
536   for (FormatToken *Tok = B.First; Tok; Tok = Tok->Next) {
537     Tok->TotalLength += LengthA;
538     A.Last = Tok;
539   }
540 }
541 
542 unsigned UnwrappedLineFormatter::analyzeSolutionSpace(LineState &InitialState,
543                                                       bool DryRun) {
544   std::set<LineState *, CompareLineStatePointers> Seen;
545 
546   // Increasing count of \c StateNode items we have created. This is used to
547   // create a deterministic order independent of the container.
548   unsigned Count = 0;
549   QueueType Queue;
550 
551   // Insert start element into queue.
552   StateNode *Node =
553       new (Allocator.Allocate()) StateNode(InitialState, false, nullptr);
554   Queue.push(QueueItem(OrderedPenalty(0, Count), Node));
555   ++Count;
556 
557   unsigned Penalty = 0;
558 
559   // While not empty, take first element and follow edges.
560   while (!Queue.empty()) {
561     Penalty = Queue.top().first.first;
562     StateNode *Node = Queue.top().second;
563     if (!Node->State.NextToken) {
564       DEBUG(llvm::dbgs() << "\n---\nPenalty for line: " << Penalty << "\n");
565       break;
566     }
567     Queue.pop();
568 
569     // Cut off the analysis of certain solutions if the analysis gets too
570     // complex. See description of IgnoreStackForComparison.
571     if (Count > 10000)
572       Node->State.IgnoreStackForComparison = true;
573 
574     if (!Seen.insert(&Node->State).second)
575       // State already examined with lower penalty.
576       continue;
577 
578     FormatDecision LastFormat = Node->State.NextToken->Decision;
579     if (LastFormat == FD_Unformatted || LastFormat == FD_Continue)
580       addNextStateToQueue(Penalty, Node, /*NewLine=*/false, &Count, &Queue);
581     if (LastFormat == FD_Unformatted || LastFormat == FD_Break)
582       addNextStateToQueue(Penalty, Node, /*NewLine=*/true, &Count, &Queue);
583   }
584 
585   if (Queue.empty()) {
586     // We were unable to find a solution, do nothing.
587     // FIXME: Add diagnostic?
588     DEBUG(llvm::dbgs() << "Could not find a solution.\n");
589     return 0;
590   }
591 
592   // Reconstruct the solution.
593   if (!DryRun)
594     reconstructPath(InitialState, Queue.top().second);
595 
596   DEBUG(llvm::dbgs() << "Total number of analyzed states: " << Count << "\n");
597   DEBUG(llvm::dbgs() << "---\n");
598 
599   return Penalty;
600 }
601 
602 #ifndef NDEBUG
603 static void printLineState(const LineState &State) {
604   llvm::dbgs() << "State: ";
605   for (const ParenState &P : State.Stack) {
606     llvm::dbgs() << P.Indent << "|" << P.LastSpace << "|" << P.NestedBlockIndent
607                  << " ";
608   }
609   llvm::dbgs() << State.NextToken->TokenText << "\n";
610 }
611 #endif
612 
613 void UnwrappedLineFormatter::reconstructPath(LineState &State,
614                                              StateNode *Current) {
615   std::deque<StateNode *> Path;
616   // We do not need a break before the initial token.
617   while (Current->Previous) {
618     Path.push_front(Current);
619     Current = Current->Previous;
620   }
621   for (std::deque<StateNode *>::iterator I = Path.begin(), E = Path.end();
622        I != E; ++I) {
623     unsigned Penalty = 0;
624     formatChildren(State, (*I)->NewLine, /*DryRun=*/false, Penalty);
625     Penalty += Indenter->addTokenToState(State, (*I)->NewLine, false);
626 
627     DEBUG({
628       printLineState((*I)->Previous->State);
629       if ((*I)->NewLine) {
630         llvm::dbgs() << "Penalty for placing "
631                      << (*I)->Previous->State.NextToken->Tok.getName() << ": "
632                      << Penalty << "\n";
633       }
634     });
635   }
636 }
637 
638 void UnwrappedLineFormatter::addNextStateToQueue(unsigned Penalty,
639                                                  StateNode *PreviousNode,
640                                                  bool NewLine, unsigned *Count,
641                                                  QueueType *Queue) {
642   if (NewLine && !Indenter->canBreak(PreviousNode->State))
643     return;
644   if (!NewLine && Indenter->mustBreak(PreviousNode->State))
645     return;
646 
647   StateNode *Node = new (Allocator.Allocate())
648       StateNode(PreviousNode->State, NewLine, PreviousNode);
649   if (!formatChildren(Node->State, NewLine, /*DryRun=*/true, Penalty))
650     return;
651 
652   Penalty += Indenter->addTokenToState(Node->State, NewLine, true);
653 
654   Queue->push(QueueItem(OrderedPenalty(Penalty, *Count), Node));
655   ++(*Count);
656 }
657 
658 bool UnwrappedLineFormatter::formatChildren(LineState &State, bool NewLine,
659                                             bool DryRun, unsigned &Penalty) {
660   const FormatToken *LBrace = State.NextToken->getPreviousNonComment();
661   FormatToken &Previous = *State.NextToken->Previous;
662   if (!LBrace || LBrace->isNot(tok::l_brace) || LBrace->BlockKind != BK_Block ||
663       Previous.Children.size() == 0)
664     // The previous token does not open a block. Nothing to do. We don't
665     // assert so that we can simply call this function for all tokens.
666     return true;
667 
668   if (NewLine) {
669     int AdditionalIndent = State.Stack.back().Indent -
670                            Previous.Children[0]->Level * Style.IndentWidth;
671 
672     Penalty += format(Previous.Children, DryRun, AdditionalIndent,
673                       /*FixBadIndentation=*/true);
674     return true;
675   }
676 
677   if (Previous.Children[0]->First->MustBreakBefore)
678     return false;
679 
680   // Cannot merge multiple statements into a single line.
681   if (Previous.Children.size() > 1)
682     return false;
683 
684   // Cannot merge into one line if this line ends on a comment.
685   if (Previous.is(tok::comment))
686     return false;
687 
688   // We can't put the closing "}" on a line with a trailing comment.
689   if (Previous.Children[0]->Last->isTrailingComment())
690     return false;
691 
692   // If the child line exceeds the column limit, we wouldn't want to merge it.
693   // We add +2 for the trailing " }".
694   if (Style.ColumnLimit > 0 &&
695       Previous.Children[0]->Last->TotalLength + State.Column + 2 >
696           Style.ColumnLimit)
697     return false;
698 
699   if (!DryRun) {
700     Whitespaces->replaceWhitespace(
701         *Previous.Children[0]->First,
702         /*Newlines=*/0, /*IndentLevel=*/0, /*Spaces=*/1,
703         /*StartOfTokenColumn=*/State.Column, State.Line->InPPDirective);
704   }
705   Penalty += format(*Previous.Children[0], State.Column + 1, DryRun);
706 
707   State.Column += 1 + Previous.Children[0]->Last->TotalLength;
708   return true;
709 }
710 
711 } // namespace format
712 } // namespace clang
713