]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - lib/Format/UnwrappedLineFormatter.cpp
Vendor import of clang trunk r238337:
[FreeBSD/FreeBSD.git] / lib / Format / UnwrappedLineFormatter.cpp
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 /// \brief Tracks the indent level of \c AnnotatedLines across levels.
29 ///
30 /// \c nextLine must be called for each \c AnnotatedLine, after which \c
31 /// getIndent() will return the indent for the last line \c nextLine was called
32 /// with.
33 /// If the line is not formatted (and thus the indent does not change), calling
34 /// \c adjustToUnmodifiedLine after the call to \c nextLine will cause
35 /// subsequent lines on the same level to be indented at the same level as the
36 /// given line.
37 class LevelIndentTracker {
38 public:
39   LevelIndentTracker(const FormatStyle &Style,
40                      const AdditionalKeywords &Keywords, unsigned StartLevel,
41                      int AdditionalIndent)
42       : Style(Style), Keywords(Keywords), AdditionalIndent(AdditionalIndent) {
43     for (unsigned i = 0; i != StartLevel; ++i)
44       IndentForLevel.push_back(Style.IndentWidth * i + AdditionalIndent);
45   }
46
47   /// \brief Returns the indent for the current line.
48   unsigned getIndent() const { return Indent; }
49
50   /// \brief Update the indent state given that \p Line is going to be formatted
51   /// next.
52   void nextLine(const AnnotatedLine &Line) {
53     Offset = getIndentOffset(*Line.First);
54     if (Line.InPPDirective) {
55       Indent = Line.Level * Style.IndentWidth + AdditionalIndent;
56     } else {
57       while (IndentForLevel.size() <= Line.Level)
58         IndentForLevel.push_back(-1);
59       IndentForLevel.resize(Line.Level + 1);
60       Indent = getIndent(IndentForLevel, Line.Level);
61     }
62     if (static_cast<int>(Indent) + Offset >= 0)
63       Indent += Offset;
64   }
65
66   /// \brief Update the level indent to adapt to the given \p Line.
67   ///
68   /// When a line is not formatted, we move the subsequent lines on the same
69   /// level to the same indent.
70   /// Note that \c nextLine must have been called before this method.
71   void adjustToUnmodifiedLine(const AnnotatedLine &Line) {
72     unsigned LevelIndent = Line.First->OriginalColumn;
73     if (static_cast<int>(LevelIndent) - Offset >= 0)
74       LevelIndent -= Offset;
75     if ((Line.First->isNot(tok::comment) || IndentForLevel[Line.Level] == -1) &&
76         !Line.InPPDirective)
77       IndentForLevel[Line.Level] = LevelIndent;
78   }
79
80 private:
81   /// \brief Get the offset of the line relatively to the level.
82   ///
83   /// For example, 'public:' labels in classes are offset by 1 or 2
84   /// characters to the left from their level.
85   int getIndentOffset(const FormatToken &RootToken) {
86     if (Style.Language == FormatStyle::LK_Java ||
87         Style.Language == FormatStyle::LK_JavaScript)
88       return 0;
89     if (RootToken.isAccessSpecifier(false) ||
90         RootToken.isObjCAccessSpecifier() ||
91         (RootToken.is(Keywords.kw_signals) && RootToken.Next &&
92          RootToken.Next->is(tok::colon)))
93       return Style.AccessModifierOffset;
94     return 0;
95   }
96
97   /// \brief Get the indent of \p Level from \p IndentForLevel.
98   ///
99   /// \p IndentForLevel must contain the indent for the level \c l
100   /// at \p IndentForLevel[l], or a value < 0 if the indent for
101   /// that level is unknown.
102   unsigned getIndent(ArrayRef<int> IndentForLevel, unsigned Level) {
103     if (IndentForLevel[Level] != -1)
104       return IndentForLevel[Level];
105     if (Level == 0)
106       return 0;
107     return getIndent(IndentForLevel, Level - 1) + Style.IndentWidth;
108   }
109
110   const FormatStyle &Style;
111   const AdditionalKeywords &Keywords;
112   const unsigned AdditionalIndent;
113
114   /// \brief The indent in characters for each level.
115   std::vector<int> IndentForLevel;
116
117   /// \brief Offset of the current line relative to the indent level.
118   ///
119   /// For example, the 'public' keywords is often indented with a negative
120   /// offset.
121   int Offset = 0;
122
123   /// \brief The current line's indent.
124   unsigned Indent = 0;
125 };
126
127 class LineJoiner {
128 public:
129   LineJoiner(const FormatStyle &Style, const AdditionalKeywords &Keywords,
130              const SmallVectorImpl<AnnotatedLine *> &Lines)
131       : Style(Style), Keywords(Keywords), End(Lines.end()),
132         Next(Lines.begin()) {}
133
134   /// \brief Returns the next line, merging multiple lines into one if possible.
135   const AnnotatedLine *getNextMergedLine(bool DryRun,
136                                          LevelIndentTracker &IndentTracker) {
137     if (Next == End)
138       return nullptr;
139     const AnnotatedLine *Current = *Next;
140     IndentTracker.nextLine(*Current);
141     unsigned MergedLines =
142         tryFitMultipleLinesInOne(IndentTracker.getIndent(), Next, End);
143     if (MergedLines > 0 && Style.ColumnLimit == 0)
144       // Disallow line merging if there is a break at the start of one of the
145       // input lines.
146       for (unsigned i = 0; i < MergedLines; ++i)
147         if (Next[i + 1]->First->NewlinesBefore > 0)
148           MergedLines = 0;
149     if (!DryRun)
150       for (unsigned i = 0; i < MergedLines; ++i)
151         join(*Next[i], *Next[i + 1]);
152     Next = Next + MergedLines + 1;
153     return Current;
154   }
155
156 private:
157   /// \brief Calculates how many lines can be merged into 1 starting at \p I.
158   unsigned
159   tryFitMultipleLinesInOne(unsigned Indent,
160                            SmallVectorImpl<AnnotatedLine *>::const_iterator I,
161                            SmallVectorImpl<AnnotatedLine *>::const_iterator E) {
162     // Can't join the last line with anything.
163     if (I + 1 == E)
164       return 0;
165     // We can never merge stuff if there are trailing line comments.
166     const AnnotatedLine *TheLine = *I;
167     if (TheLine->Last->is(TT_LineComment))
168       return 0;
169     if (I[1]->Type == LT_Invalid || I[1]->First->MustBreakBefore)
170       return 0;
171     if (TheLine->InPPDirective &&
172         (!I[1]->InPPDirective || I[1]->First->HasUnescapedNewline))
173       return 0;
174
175     if (Style.ColumnLimit > 0 && Indent > Style.ColumnLimit)
176       return 0;
177
178     unsigned Limit =
179         Style.ColumnLimit == 0 ? UINT_MAX : Style.ColumnLimit - Indent;
180     // If we already exceed the column limit, we set 'Limit' to 0. The different
181     // tryMerge..() functions can then decide whether to still do merging.
182     Limit = TheLine->Last->TotalLength > Limit
183                 ? 0
184                 : Limit - TheLine->Last->TotalLength;
185
186     // FIXME: TheLine->Level != 0 might or might not be the right check to do.
187     // If necessary, change to something smarter.
188     bool MergeShortFunctions =
189         Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_All ||
190         (Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_Empty &&
191          I[1]->First->is(tok::r_brace)) ||
192         (Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_Inline &&
193          TheLine->Level != 0);
194
195     if (TheLine->Last->is(TT_FunctionLBrace) &&
196         TheLine->First != TheLine->Last) {
197       return MergeShortFunctions ? tryMergeSimpleBlock(I, E, Limit) : 0;
198     }
199     if (TheLine->Last->is(tok::l_brace)) {
200       return Style.BreakBeforeBraces == FormatStyle::BS_Attach
201                  ? tryMergeSimpleBlock(I, E, Limit)
202                  : 0;
203     }
204     if (I[1]->First->is(TT_FunctionLBrace) &&
205         Style.BreakBeforeBraces != FormatStyle::BS_Attach) {
206       if (I[1]->Last->is(TT_LineComment))
207         return 0;
208
209       // Check for Limit <= 2 to account for the " {".
210       if (Limit <= 2 || (Style.ColumnLimit == 0 && containsMustBreak(TheLine)))
211         return 0;
212       Limit -= 2;
213
214       unsigned MergedLines = 0;
215       if (MergeShortFunctions) {
216         MergedLines = tryMergeSimpleBlock(I + 1, E, Limit);
217         // If we managed to merge the block, count the function header, which is
218         // on a separate line.
219         if (MergedLines > 0)
220           ++MergedLines;
221       }
222       return MergedLines;
223     }
224     if (TheLine->First->is(tok::kw_if)) {
225       return Style.AllowShortIfStatementsOnASingleLine
226                  ? tryMergeSimpleControlStatement(I, E, Limit)
227                  : 0;
228     }
229     if (TheLine->First->isOneOf(tok::kw_for, tok::kw_while)) {
230       return Style.AllowShortLoopsOnASingleLine
231                  ? tryMergeSimpleControlStatement(I, E, Limit)
232                  : 0;
233     }
234     if (TheLine->First->isOneOf(tok::kw_case, tok::kw_default)) {
235       return Style.AllowShortCaseLabelsOnASingleLine
236                  ? tryMergeShortCaseLabels(I, E, Limit)
237                  : 0;
238     }
239     if (TheLine->InPPDirective &&
240         (TheLine->First->HasUnescapedNewline || TheLine->First->IsFirst)) {
241       return tryMergeSimplePPDirective(I, E, Limit);
242     }
243     return 0;
244   }
245
246   unsigned
247   tryMergeSimplePPDirective(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
248                             SmallVectorImpl<AnnotatedLine *>::const_iterator E,
249                             unsigned Limit) {
250     if (Limit == 0)
251       return 0;
252     if (I + 2 != E && I[2]->InPPDirective && !I[2]->First->HasUnescapedNewline)
253       return 0;
254     if (1 + I[1]->Last->TotalLength > Limit)
255       return 0;
256     return 1;
257   }
258
259   unsigned tryMergeSimpleControlStatement(
260       SmallVectorImpl<AnnotatedLine *>::const_iterator I,
261       SmallVectorImpl<AnnotatedLine *>::const_iterator E, unsigned Limit) {
262     if (Limit == 0)
263       return 0;
264     if ((Style.BreakBeforeBraces == FormatStyle::BS_Allman ||
265          Style.BreakBeforeBraces == FormatStyle::BS_GNU) &&
266         (I[1]->First->is(tok::l_brace) && !Style.AllowShortBlocksOnASingleLine))
267       return 0;
268     if (I[1]->InPPDirective != (*I)->InPPDirective ||
269         (I[1]->InPPDirective && I[1]->First->HasUnescapedNewline))
270       return 0;
271     Limit = limitConsideringMacros(I + 1, E, Limit);
272     AnnotatedLine &Line = **I;
273     if (Line.Last->isNot(tok::r_paren))
274       return 0;
275     if (1 + I[1]->Last->TotalLength > Limit)
276       return 0;
277     if (I[1]->First->isOneOf(tok::semi, tok::kw_if, tok::kw_for, tok::kw_while,
278                              TT_LineComment))
279       return 0;
280     // Only inline simple if's (no nested if or else).
281     if (I + 2 != E && Line.First->is(tok::kw_if) &&
282         I[2]->First->is(tok::kw_else))
283       return 0;
284     return 1;
285   }
286
287   unsigned
288   tryMergeShortCaseLabels(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
289                           SmallVectorImpl<AnnotatedLine *>::const_iterator E,
290                           unsigned Limit) {
291     if (Limit == 0 || I + 1 == E ||
292         I[1]->First->isOneOf(tok::kw_case, tok::kw_default))
293       return 0;
294     unsigned NumStmts = 0;
295     unsigned Length = 0;
296     bool InPPDirective = I[0]->InPPDirective;
297     for (; NumStmts < 3; ++NumStmts) {
298       if (I + 1 + NumStmts == E)
299         break;
300       const AnnotatedLine *Line = I[1 + NumStmts];
301       if (Line->InPPDirective != InPPDirective)
302         break;
303       if (Line->First->isOneOf(tok::kw_case, tok::kw_default, tok::r_brace))
304         break;
305       if (Line->First->isOneOf(tok::kw_if, tok::kw_for, tok::kw_switch,
306                                tok::kw_while, tok::comment))
307         return 0;
308       Length += I[1 + NumStmts]->Last->TotalLength + 1; // 1 for the space.
309     }
310     if (NumStmts == 0 || NumStmts == 3 || Length > Limit)
311       return 0;
312     return NumStmts;
313   }
314
315   unsigned
316   tryMergeSimpleBlock(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
317                       SmallVectorImpl<AnnotatedLine *>::const_iterator E,
318                       unsigned Limit) {
319     AnnotatedLine &Line = **I;
320
321     // Don't merge ObjC @ keywords and methods.
322     // FIXME: If an option to allow short exception handling clauses on a single
323     // line is added, change this to not return for @try and friends.
324     if (Style.Language != FormatStyle::LK_Java &&
325         Line.First->isOneOf(tok::at, tok::minus, tok::plus))
326       return 0;
327
328     // Check that the current line allows merging. This depends on whether we
329     // are in a control flow statements as well as several style flags.
330     if (Line.First->isOneOf(tok::kw_else, tok::kw_case) ||
331         (Line.First->Next && Line.First->Next->is(tok::kw_else)))
332       return 0;
333     if (Line.First->isOneOf(tok::kw_if, tok::kw_while, tok::kw_do, tok::kw_try,
334                             tok::kw___try, tok::kw_catch, tok::kw___finally,
335                             tok::kw_for, tok::r_brace) ||
336         Line.First->is(Keywords.kw___except)) {
337       if (!Style.AllowShortBlocksOnASingleLine)
338         return 0;
339       if (!Style.AllowShortIfStatementsOnASingleLine &&
340           Line.First->is(tok::kw_if))
341         return 0;
342       if (!Style.AllowShortLoopsOnASingleLine &&
343           Line.First->isOneOf(tok::kw_while, tok::kw_do, tok::kw_for))
344         return 0;
345       // FIXME: Consider an option to allow short exception handling clauses on
346       // a single line.
347       // FIXME: This isn't covered by tests.
348       // FIXME: For catch, __except, __finally the first token on the line
349       // is '}', so this isn't correct here.
350       if (Line.First->isOneOf(tok::kw_try, tok::kw___try, tok::kw_catch,
351                               Keywords.kw___except, tok::kw___finally))
352         return 0;
353     }
354
355     FormatToken *Tok = I[1]->First;
356     if (Tok->is(tok::r_brace) && !Tok->MustBreakBefore &&
357         (Tok->getNextNonComment() == nullptr ||
358          Tok->getNextNonComment()->is(tok::semi))) {
359       // We merge empty blocks even if the line exceeds the column limit.
360       Tok->SpacesRequiredBefore = 0;
361       Tok->CanBreakBefore = true;
362       return 1;
363     } else if (Limit != 0 && Line.First->isNot(tok::kw_namespace) &&
364                !startsExternCBlock(Line)) {
365       // We don't merge short records.
366       if (Line.First->isOneOf(tok::kw_class, tok::kw_union, tok::kw_struct,
367                               Keywords.kw_interface))
368         return 0;
369
370       // Check that we still have three lines and they fit into the limit.
371       if (I + 2 == E || I[2]->Type == LT_Invalid)
372         return 0;
373       Limit = limitConsideringMacros(I + 2, E, Limit);
374
375       if (!nextTwoLinesFitInto(I, Limit))
376         return 0;
377
378       // Second, check that the next line does not contain any braces - if it
379       // does, readability declines when putting it into a single line.
380       if (I[1]->Last->is(TT_LineComment))
381         return 0;
382       do {
383         if (Tok->is(tok::l_brace) && Tok->BlockKind != BK_BracedInit)
384           return 0;
385         Tok = Tok->Next;
386       } while (Tok);
387
388       // Last, check that the third line starts with a closing brace.
389       Tok = I[2]->First;
390       if (Tok->isNot(tok::r_brace))
391         return 0;
392
393       // Don't merge "if (a) { .. } else {".
394       if (Tok->Next && Tok->Next->is(tok::kw_else))
395         return 0;
396
397       return 2;
398     }
399     return 0;
400   }
401
402   /// Returns the modified column limit for \p I if it is inside a macro and
403   /// needs a trailing '\'.
404   unsigned
405   limitConsideringMacros(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
406                          SmallVectorImpl<AnnotatedLine *>::const_iterator E,
407                          unsigned Limit) {
408     if (I[0]->InPPDirective && I + 1 != E &&
409         !I[1]->First->HasUnescapedNewline && !I[1]->First->is(tok::eof)) {
410       return Limit < 2 ? 0 : Limit - 2;
411     }
412     return Limit;
413   }
414
415   bool nextTwoLinesFitInto(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
416                            unsigned Limit) {
417     if (I[1]->First->MustBreakBefore || I[2]->First->MustBreakBefore)
418       return false;
419     return 1 + I[1]->Last->TotalLength + 1 + I[2]->Last->TotalLength <= Limit;
420   }
421
422   bool containsMustBreak(const AnnotatedLine *Line) {
423     for (const FormatToken *Tok = Line->First; Tok; Tok = Tok->Next) {
424       if (Tok->MustBreakBefore)
425         return true;
426     }
427     return false;
428   }
429
430   void join(AnnotatedLine &A, const AnnotatedLine &B) {
431     assert(!A.Last->Next);
432     assert(!B.First->Previous);
433     if (B.Affected)
434       A.Affected = true;
435     A.Last->Next = B.First;
436     B.First->Previous = A.Last;
437     B.First->CanBreakBefore = true;
438     unsigned LengthA = A.Last->TotalLength + B.First->SpacesRequiredBefore;
439     for (FormatToken *Tok = B.First; Tok; Tok = Tok->Next) {
440       Tok->TotalLength += LengthA;
441       A.Last = Tok;
442     }
443   }
444
445   const FormatStyle &Style;
446   const AdditionalKeywords &Keywords;
447   const SmallVectorImpl<AnnotatedLine*>::const_iterator End;
448
449   SmallVectorImpl<AnnotatedLine*>::const_iterator Next;
450 };
451
452 static void markFinalized(FormatToken *Tok) {
453   for (; Tok; Tok = Tok->Next) {
454     Tok->Finalized = true;
455     for (AnnotatedLine *Child : Tok->Children)
456       markFinalized(Child->First);
457   }
458 }
459
460 #ifndef NDEBUG
461 static void printLineState(const LineState &State) {
462   llvm::dbgs() << "State: ";
463   for (const ParenState &P : State.Stack) {
464     llvm::dbgs() << P.Indent << "|" << P.LastSpace << "|" << P.NestedBlockIndent
465                  << " ";
466   }
467   llvm::dbgs() << State.NextToken->TokenText << "\n";
468 }
469 #endif
470
471 /// \brief Base class for classes that format one \c AnnotatedLine.
472 class LineFormatter {
473 public:
474   LineFormatter(ContinuationIndenter *Indenter, WhitespaceManager *Whitespaces,
475                 const FormatStyle &Style,
476                 UnwrappedLineFormatter *BlockFormatter)
477       : Indenter(Indenter), Whitespaces(Whitespaces), Style(Style),
478         BlockFormatter(BlockFormatter) {}
479   virtual ~LineFormatter() {}
480
481   /// \brief Formats an \c AnnotatedLine and returns the penalty.
482   ///
483   /// If \p DryRun is \c false, directly applies the changes.
484   virtual unsigned formatLine(const AnnotatedLine &Line, unsigned FirstIndent,
485                               bool DryRun) = 0;
486
487 protected:
488   /// \brief If the \p State's next token is an r_brace closing a nested block,
489   /// format the nested block before it.
490   ///
491   /// Returns \c true if all children could be placed successfully and adapts
492   /// \p Penalty as well as \p State. If \p DryRun is false, also directly
493   /// creates changes using \c Whitespaces.
494   ///
495   /// The crucial idea here is that children always get formatted upon
496   /// encountering the closing brace right after the nested block. Now, if we
497   /// are currently trying to keep the "}" on the same line (i.e. \p NewLine is
498   /// \c false), the entire block has to be kept on the same line (which is only
499   /// possible if it fits on the line, only contains a single statement, etc.
500   ///
501   /// If \p NewLine is true, we format the nested block on separate lines, i.e.
502   /// break after the "{", format all lines with correct indentation and the put
503   /// the closing "}" on yet another new line.
504   ///
505   /// This enables us to keep the simple structure of the
506   /// \c UnwrappedLineFormatter, where we only have two options for each token:
507   /// break or don't break.
508   bool formatChildren(LineState &State, bool NewLine, bool DryRun,
509                       unsigned &Penalty) {
510     const FormatToken *LBrace = State.NextToken->getPreviousNonComment();
511     FormatToken &Previous = *State.NextToken->Previous;
512     if (!LBrace || LBrace->isNot(tok::l_brace) ||
513         LBrace->BlockKind != BK_Block || Previous.Children.size() == 0)
514       // The previous token does not open a block. Nothing to do. We don't
515       // assert so that we can simply call this function for all tokens.
516       return true;
517
518     if (NewLine) {
519       int AdditionalIndent = State.Stack.back().Indent -
520                              Previous.Children[0]->Level * Style.IndentWidth;
521
522       Penalty +=
523           BlockFormatter->format(Previous.Children, DryRun, AdditionalIndent,
524                                  /*FixBadIndentation=*/true);
525       return true;
526     }
527
528     if (Previous.Children[0]->First->MustBreakBefore)
529       return false;
530
531     // Cannot merge multiple statements into a single line.
532     if (Previous.Children.size() > 1)
533       return false;
534
535     // Cannot merge into one line if this line ends on a comment.
536     if (Previous.is(tok::comment))
537       return false;
538
539     // We can't put the closing "}" on a line with a trailing comment.
540     if (Previous.Children[0]->Last->isTrailingComment())
541       return false;
542
543     // If the child line exceeds the column limit, we wouldn't want to merge it.
544     // We add +2 for the trailing " }".
545     if (Style.ColumnLimit > 0 &&
546         Previous.Children[0]->Last->TotalLength + State.Column + 2 >
547             Style.ColumnLimit)
548       return false;
549
550     if (!DryRun) {
551       Whitespaces->replaceWhitespace(
552           *Previous.Children[0]->First,
553           /*Newlines=*/0, /*IndentLevel=*/0, /*Spaces=*/1,
554           /*StartOfTokenColumn=*/State.Column, State.Line->InPPDirective);
555     }
556     Penalty += formatLine(*Previous.Children[0], State.Column + 1, DryRun);
557
558     State.Column += 1 + Previous.Children[0]->Last->TotalLength;
559     return true;
560   }
561
562   ContinuationIndenter *Indenter;
563
564 private:
565   WhitespaceManager *Whitespaces;
566   const FormatStyle &Style;
567   UnwrappedLineFormatter *BlockFormatter;
568 };
569
570 /// \brief Formatter that keeps the existing line breaks.
571 class NoColumnLimitLineFormatter : public LineFormatter {
572 public:
573   NoColumnLimitLineFormatter(ContinuationIndenter *Indenter,
574                              WhitespaceManager *Whitespaces,
575                              const FormatStyle &Style,
576                              UnwrappedLineFormatter *BlockFormatter)
577       : LineFormatter(Indenter, Whitespaces, Style, BlockFormatter) {}
578
579   /// \brief Formats the line, simply keeping all of the input's line breaking
580   /// decisions.
581   unsigned formatLine(const AnnotatedLine &Line, unsigned FirstIndent,
582                       bool DryRun) override {
583     assert(!DryRun);
584     LineState State =
585         Indenter->getInitialState(FirstIndent, &Line, /*DryRun=*/false);
586     while (State.NextToken) {
587       bool Newline =
588           Indenter->mustBreak(State) ||
589           (Indenter->canBreak(State) && State.NextToken->NewlinesBefore > 0);
590       unsigned Penalty = 0;
591       formatChildren(State, Newline, /*DryRun=*/false, Penalty);
592       Indenter->addTokenToState(State, Newline, /*DryRun=*/false);
593     }
594     return 0;
595   }
596 };
597
598 /// \brief Formatter that puts all tokens into a single line without breaks.
599 class NoLineBreakFormatter : public LineFormatter {
600 public:
601   NoLineBreakFormatter(ContinuationIndenter *Indenter,
602                        WhitespaceManager *Whitespaces, const FormatStyle &Style,
603                        UnwrappedLineFormatter *BlockFormatter)
604       : LineFormatter(Indenter, Whitespaces, Style, BlockFormatter) {}
605
606   /// \brief Puts all tokens into a single line.
607   unsigned formatLine(const AnnotatedLine &Line, unsigned FirstIndent,
608                       bool DryRun) {
609     unsigned Penalty = 0;
610     LineState State = Indenter->getInitialState(FirstIndent, &Line, DryRun);
611     while (State.NextToken) {
612       formatChildren(State, /*Newline=*/false, DryRun, Penalty);
613       Indenter->addTokenToState(State, /*Newline=*/false, DryRun);
614     }
615     return Penalty;
616   }
617 };
618
619 /// \brief Finds the best way to break lines.
620 class OptimizingLineFormatter : public LineFormatter {
621 public:
622   OptimizingLineFormatter(ContinuationIndenter *Indenter,
623                           WhitespaceManager *Whitespaces,
624                           const FormatStyle &Style,
625                           UnwrappedLineFormatter *BlockFormatter)
626       : LineFormatter(Indenter, Whitespaces, Style, BlockFormatter) {}
627
628   /// \brief Formats the line by finding the best line breaks with line lengths
629   /// below the column limit.
630   unsigned formatLine(const AnnotatedLine &Line, unsigned FirstIndent,
631                       bool DryRun) {
632     LineState State = Indenter->getInitialState(FirstIndent, &Line, DryRun);
633
634     // If the ObjC method declaration does not fit on a line, we should format
635     // it with one arg per line.
636     if (State.Line->Type == LT_ObjCMethodDecl)
637       State.Stack.back().BreakBeforeParameter = true;
638
639     // Find best solution in solution space.
640     return analyzeSolutionSpace(State, DryRun);
641   }
642
643 private:
644   struct CompareLineStatePointers {
645     bool operator()(LineState *obj1, LineState *obj2) const {
646       return *obj1 < *obj2;
647     }
648   };
649
650   /// \brief A pair of <penalty, count> that is used to prioritize the BFS on.
651   ///
652   /// In case of equal penalties, we want to prefer states that were inserted
653   /// first. During state generation we make sure that we insert states first
654   /// that break the line as late as possible.
655   typedef std::pair<unsigned, unsigned> OrderedPenalty;
656
657   /// \brief An edge in the solution space from \c Previous->State to \c State,
658   /// inserting a newline dependent on the \c NewLine.
659   struct StateNode {
660     StateNode(const LineState &State, bool NewLine, StateNode *Previous)
661         : State(State), NewLine(NewLine), Previous(Previous) {}
662     LineState State;
663     bool NewLine;
664     StateNode *Previous;
665   };
666
667   /// \brief An item in the prioritized BFS search queue. The \c StateNode's
668   /// \c State has the given \c OrderedPenalty.
669   typedef std::pair<OrderedPenalty, StateNode *> QueueItem;
670
671   /// \brief The BFS queue type.
672   typedef std::priority_queue<QueueItem, std::vector<QueueItem>,
673                               std::greater<QueueItem>> QueueType;
674
675   /// \brief Analyze the entire solution space starting from \p InitialState.
676   ///
677   /// This implements a variant of Dijkstra's algorithm on the graph that spans
678   /// the solution space (\c LineStates are the nodes). The algorithm tries to
679   /// find the shortest path (the one with lowest penalty) from \p InitialState
680   /// to a state where all tokens are placed. Returns the penalty.
681   ///
682   /// If \p DryRun is \c false, directly applies the changes.
683   unsigned analyzeSolutionSpace(LineState &InitialState, bool DryRun) {
684     std::set<LineState *, CompareLineStatePointers> Seen;
685
686     // Increasing count of \c StateNode items we have created. This is used to
687     // create a deterministic order independent of the container.
688     unsigned Count = 0;
689     QueueType Queue;
690
691     // Insert start element into queue.
692     StateNode *Node =
693         new (Allocator.Allocate()) StateNode(InitialState, false, nullptr);
694     Queue.push(QueueItem(OrderedPenalty(0, Count), Node));
695     ++Count;
696
697     unsigned Penalty = 0;
698
699     // While not empty, take first element and follow edges.
700     while (!Queue.empty()) {
701       Penalty = Queue.top().first.first;
702       StateNode *Node = Queue.top().second;
703       if (!Node->State.NextToken) {
704         DEBUG(llvm::dbgs() << "\n---\nPenalty for line: " << Penalty << "\n");
705         break;
706       }
707       Queue.pop();
708
709       // Cut off the analysis of certain solutions if the analysis gets too
710       // complex. See description of IgnoreStackForComparison.
711       if (Count > 10000)
712         Node->State.IgnoreStackForComparison = true;
713
714       if (!Seen.insert(&Node->State).second)
715         // State already examined with lower penalty.
716         continue;
717
718       FormatDecision LastFormat = Node->State.NextToken->Decision;
719       if (LastFormat == FD_Unformatted || LastFormat == FD_Continue)
720         addNextStateToQueue(Penalty, Node, /*NewLine=*/false, &Count, &Queue);
721       if (LastFormat == FD_Unformatted || LastFormat == FD_Break)
722         addNextStateToQueue(Penalty, Node, /*NewLine=*/true, &Count, &Queue);
723     }
724
725     if (Queue.empty()) {
726       // We were unable to find a solution, do nothing.
727       // FIXME: Add diagnostic?
728       DEBUG(llvm::dbgs() << "Could not find a solution.\n");
729       return 0;
730     }
731
732     // Reconstruct the solution.
733     if (!DryRun)
734       reconstructPath(InitialState, Queue.top().second);
735
736     DEBUG(llvm::dbgs() << "Total number of analyzed states: " << Count << "\n");
737     DEBUG(llvm::dbgs() << "---\n");
738
739     return Penalty;
740   }
741
742   /// \brief Add the following state to the analysis queue \c Queue.
743   ///
744   /// Assume the current state is \p PreviousNode and has been reached with a
745   /// penalty of \p Penalty. Insert a line break if \p NewLine is \c true.
746   void addNextStateToQueue(unsigned Penalty, StateNode *PreviousNode,
747                            bool NewLine, unsigned *Count, QueueType *Queue) {
748     if (NewLine && !Indenter->canBreak(PreviousNode->State))
749       return;
750     if (!NewLine && Indenter->mustBreak(PreviousNode->State))
751       return;
752
753     StateNode *Node = new (Allocator.Allocate())
754         StateNode(PreviousNode->State, NewLine, PreviousNode);
755     if (!formatChildren(Node->State, NewLine, /*DryRun=*/true, Penalty))
756       return;
757
758     Penalty += Indenter->addTokenToState(Node->State, NewLine, true);
759
760     Queue->push(QueueItem(OrderedPenalty(Penalty, *Count), Node));
761     ++(*Count);
762   }
763
764   /// \brief Applies the best formatting by reconstructing the path in the
765   /// solution space that leads to \c Best.
766   void reconstructPath(LineState &State, StateNode *Best) {
767     std::deque<StateNode *> Path;
768     // We do not need a break before the initial token.
769     while (Best->Previous) {
770       Path.push_front(Best);
771       Best = Best->Previous;
772     }
773     for (std::deque<StateNode *>::iterator I = Path.begin(), E = Path.end();
774          I != E; ++I) {
775       unsigned Penalty = 0;
776       formatChildren(State, (*I)->NewLine, /*DryRun=*/false, Penalty);
777       Penalty += Indenter->addTokenToState(State, (*I)->NewLine, false);
778
779       DEBUG({
780         printLineState((*I)->Previous->State);
781         if ((*I)->NewLine) {
782           llvm::dbgs() << "Penalty for placing "
783                        << (*I)->Previous->State.NextToken->Tok.getName() << ": "
784                        << Penalty << "\n";
785         }
786       });
787     }
788   }
789
790   llvm::SpecificBumpPtrAllocator<StateNode> Allocator;
791 };
792
793 } // namespace
794
795 unsigned
796 UnwrappedLineFormatter::format(const SmallVectorImpl<AnnotatedLine *> &Lines,
797                                bool DryRun, int AdditionalIndent,
798                                bool FixBadIndentation) {
799   LineJoiner Joiner(Style, Keywords, Lines);
800
801   // Try to look up already computed penalty in DryRun-mode.
802   std::pair<const SmallVectorImpl<AnnotatedLine *> *, unsigned> CacheKey(
803       &Lines, AdditionalIndent);
804   auto CacheIt = PenaltyCache.find(CacheKey);
805   if (DryRun && CacheIt != PenaltyCache.end())
806     return CacheIt->second;
807
808   assert(!Lines.empty());
809   unsigned Penalty = 0;
810   LevelIndentTracker IndentTracker(Style, Keywords, Lines[0]->Level,
811                                    AdditionalIndent);
812   const AnnotatedLine *PreviousLine = nullptr;
813   const AnnotatedLine *NextLine = nullptr;
814   for (const AnnotatedLine *Line =
815            Joiner.getNextMergedLine(DryRun, IndentTracker);
816        Line; Line = NextLine) {
817     const AnnotatedLine &TheLine = *Line;
818     unsigned Indent = IndentTracker.getIndent();
819     bool FixIndentation =
820         FixBadIndentation && (Indent != TheLine.First->OriginalColumn);
821     bool ShouldFormat = TheLine.Affected || FixIndentation;
822     // We cannot format this line; if the reason is that the line had a
823     // parsing error, remember that.
824     if (ShouldFormat && TheLine.Type == LT_Invalid && IncompleteFormat)
825       *IncompleteFormat = true;
826
827     if (ShouldFormat && TheLine.Type != LT_Invalid) {
828       if (!DryRun)
829         formatFirstToken(*TheLine.First, PreviousLine, TheLine.Level, Indent,
830                          TheLine.InPPDirective);
831
832       NextLine = Joiner.getNextMergedLine(DryRun, IndentTracker);
833       unsigned ColumnLimit = getColumnLimit(TheLine.InPPDirective, NextLine);
834       bool FitsIntoOneLine =
835           TheLine.Last->TotalLength + Indent <= ColumnLimit ||
836           TheLine.Type == LT_ImportStatement;
837
838       if (Style.ColumnLimit == 0)
839         NoColumnLimitLineFormatter(Indenter, Whitespaces, Style, this)
840             .formatLine(TheLine, Indent, DryRun);
841       else if (FitsIntoOneLine)
842         Penalty += NoLineBreakFormatter(Indenter, Whitespaces, Style, this)
843                        .formatLine(TheLine, Indent, DryRun);
844       else
845         Penalty += OptimizingLineFormatter(Indenter, Whitespaces, Style, this)
846                        .formatLine(TheLine, Indent, DryRun);
847     } else {
848       // If no token in the current line is affected, we still need to format
849       // affected children.
850       if (TheLine.ChildrenAffected)
851         format(TheLine.Children, DryRun);
852
853       // Adapt following lines on the current indent level to the same level
854       // unless the current \c AnnotatedLine is not at the beginning of a line.
855       bool StartsNewLine =
856           TheLine.First->NewlinesBefore > 0 || TheLine.First->IsFirst;
857       if (StartsNewLine)
858         IndentTracker.adjustToUnmodifiedLine(TheLine);
859       if (!DryRun) {
860         bool ReformatLeadingWhitespace =
861             StartsNewLine && ((PreviousLine && PreviousLine->Affected) ||
862                               TheLine.LeadingEmptyLinesAffected);
863         // Format the first token.
864         if (ReformatLeadingWhitespace)
865           formatFirstToken(*TheLine.First, PreviousLine, TheLine.Level,
866                            TheLine.First->OriginalColumn,
867                            TheLine.InPPDirective);
868         else
869           Whitespaces->addUntouchableToken(*TheLine.First,
870                                            TheLine.InPPDirective);
871
872         // Notify the WhitespaceManager about the unchanged whitespace.
873         for (FormatToken *Tok = TheLine.First->Next; Tok; Tok = Tok->Next)
874           Whitespaces->addUntouchableToken(*Tok, TheLine.InPPDirective);
875       }
876       NextLine = Joiner.getNextMergedLine(DryRun, IndentTracker);
877     }
878     if (!DryRun)
879       markFinalized(TheLine.First);
880     PreviousLine = &TheLine;
881   }
882   PenaltyCache[CacheKey] = Penalty;
883   return Penalty;
884 }
885
886 void UnwrappedLineFormatter::formatFirstToken(FormatToken &RootToken,
887                                               const AnnotatedLine *PreviousLine,
888                                               unsigned IndentLevel,
889                                               unsigned Indent,
890                                               bool InPPDirective) {
891   if (RootToken.is(tok::eof)) {
892     unsigned Newlines = std::min(RootToken.NewlinesBefore, 1u);
893     Whitespaces->replaceWhitespace(RootToken, Newlines, /*IndentLevel=*/0,
894                                    /*Spaces=*/0, /*TargetColumn=*/0);
895     return;
896   }
897   unsigned Newlines =
898       std::min(RootToken.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1);
899   // Remove empty lines before "}" where applicable.
900   if (RootToken.is(tok::r_brace) &&
901       (!RootToken.Next ||
902        (RootToken.Next->is(tok::semi) && !RootToken.Next->Next)))
903     Newlines = std::min(Newlines, 1u);
904   if (Newlines == 0 && !RootToken.IsFirst)
905     Newlines = 1;
906   if (RootToken.IsFirst && !RootToken.HasUnescapedNewline)
907     Newlines = 0;
908
909   // Remove empty lines after "{".
910   if (!Style.KeepEmptyLinesAtTheStartOfBlocks && PreviousLine &&
911       PreviousLine->Last->is(tok::l_brace) &&
912       PreviousLine->First->isNot(tok::kw_namespace) &&
913       !startsExternCBlock(*PreviousLine))
914     Newlines = 1;
915
916   // Insert extra new line before access specifiers.
917   if (PreviousLine && PreviousLine->Last->isOneOf(tok::semi, tok::r_brace) &&
918       RootToken.isAccessSpecifier() && RootToken.NewlinesBefore == 1)
919     ++Newlines;
920
921   // Remove empty lines after access specifiers.
922   if (PreviousLine && PreviousLine->First->isAccessSpecifier() &&
923       (!PreviousLine->InPPDirective || !RootToken.HasUnescapedNewline))
924     Newlines = std::min(1u, Newlines);
925
926   Whitespaces->replaceWhitespace(RootToken, Newlines, IndentLevel, Indent,
927                                  Indent, InPPDirective &&
928                                              !RootToken.HasUnescapedNewline);
929 }
930
931 unsigned
932 UnwrappedLineFormatter::getColumnLimit(bool InPPDirective,
933                                        const AnnotatedLine *NextLine) const {
934   // In preprocessor directives reserve two chars for trailing " \" if the
935   // next line continues the preprocessor directive.
936   bool ContinuesPPDirective =
937       InPPDirective &&
938       // If there is no next line, this is likely a child line and the parent
939       // continues the preprocessor directive.
940       (!NextLine ||
941        (NextLine->InPPDirective &&
942         // If there is an unescaped newline between this line and the next, the
943         // next line starts a new preprocessor directive.
944         !NextLine->First->HasUnescapedNewline));
945   return Style.ColumnLimit - (ContinuesPPDirective ? 2 : 0);
946 }
947
948 } // namespace format
949 } // namespace clang