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