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