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