1 //===--- UnwrappedLineFormatter.cpp - Format C++ code ---------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "UnwrappedLineFormatter.h"
10 #include "NamespaceEndCommentsFixer.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 /// 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   /// Returns the indent for the current line.
49   unsigned getIndent() const { return Indent; }
50 
51   /// 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     if (Line.First->is(TT_CSharpGenericTypeConstraint))
68       Indent = Line.Level * Style.IndentWidth + Style.ContinuationIndentWidth;
69   }
70 
71   /// Update the indent state given that \p Line indent should be
72   /// skipped.
73   void skipLine(const AnnotatedLine &Line) {
74     while (IndentForLevel.size() <= Line.Level)
75       IndentForLevel.push_back(Indent);
76   }
77 
78   /// Update the level indent to adapt to the given \p Line.
79   ///
80   /// When a line is not formatted, we move the subsequent lines on the same
81   /// level to the same indent.
82   /// Note that \c nextLine must have been called before this method.
83   void adjustToUnmodifiedLine(const AnnotatedLine &Line) {
84     unsigned LevelIndent = Line.First->OriginalColumn;
85     if (static_cast<int>(LevelIndent) - Offset >= 0)
86       LevelIndent -= Offset;
87     if ((!Line.First->is(tok::comment) || IndentForLevel[Line.Level] == -1) &&
88         !Line.InPPDirective)
89       IndentForLevel[Line.Level] = LevelIndent;
90   }
91 
92 private:
93   /// Get the offset of the line relatively to the level.
94   ///
95   /// For example, 'public:' labels in classes are offset by 1 or 2
96   /// characters to the left from their level.
97   int getIndentOffset(const FormatToken &RootToken) {
98     if (Style.Language == FormatStyle::LK_Java ||
99         Style.Language == FormatStyle::LK_JavaScript || Style.isCSharp())
100       return 0;
101     if (RootToken.isAccessSpecifier(false) ||
102         RootToken.isObjCAccessSpecifier() ||
103         (RootToken.isOneOf(Keywords.kw_signals, Keywords.kw_qsignals) &&
104          RootToken.Next && RootToken.Next->is(tok::colon)))
105       return Style.AccessModifierOffset;
106     return 0;
107   }
108 
109   /// Get the indent of \p Level from \p IndentForLevel.
110   ///
111   /// \p IndentForLevel must contain the indent for the level \c l
112   /// at \p IndentForLevel[l], or a value < 0 if the indent for
113   /// that level is unknown.
114   unsigned getIndent(ArrayRef<int> IndentForLevel, unsigned Level) {
115     if (IndentForLevel[Level] != -1)
116       return IndentForLevel[Level];
117     if (Level == 0)
118       return 0;
119     return getIndent(IndentForLevel, Level - 1) + Style.IndentWidth;
120   }
121 
122   const FormatStyle &Style;
123   const AdditionalKeywords &Keywords;
124   const unsigned AdditionalIndent;
125 
126   /// The indent in characters for each level.
127   std::vector<int> IndentForLevel;
128 
129   /// Offset of the current line relative to the indent level.
130   ///
131   /// For example, the 'public' keywords is often indented with a negative
132   /// offset.
133   int Offset = 0;
134 
135   /// The current line's indent.
136   unsigned Indent = 0;
137 };
138 
139 const FormatToken *getMatchingNamespaceToken(
140     const AnnotatedLine *Line,
141     const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines) {
142   if (!Line->startsWith(tok::r_brace))
143     return nullptr;
144   size_t StartLineIndex = Line->MatchingOpeningBlockLineIndex;
145   if (StartLineIndex == UnwrappedLine::kInvalidIndex)
146     return nullptr;
147   assert(StartLineIndex < AnnotatedLines.size());
148   return AnnotatedLines[StartLineIndex]->First->getNamespaceToken();
149 }
150 
151 StringRef getNamespaceTokenText(const AnnotatedLine *Line) {
152   const FormatToken *NamespaceToken = Line->First->getNamespaceToken();
153   return NamespaceToken ? NamespaceToken->TokenText : StringRef();
154 }
155 
156 StringRef getMatchingNamespaceTokenText(
157     const AnnotatedLine *Line,
158     const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines) {
159   const FormatToken *NamespaceToken =
160       getMatchingNamespaceToken(Line, AnnotatedLines);
161   return NamespaceToken ? NamespaceToken->TokenText : StringRef();
162 }
163 
164 class LineJoiner {
165 public:
166   LineJoiner(const FormatStyle &Style, const AdditionalKeywords &Keywords,
167              const SmallVectorImpl<AnnotatedLine *> &Lines)
168       : Style(Style), Keywords(Keywords), End(Lines.end()), Next(Lines.begin()),
169         AnnotatedLines(Lines) {}
170 
171   /// Returns the next line, merging multiple lines into one if possible.
172   const AnnotatedLine *getNextMergedLine(bool DryRun,
173                                          LevelIndentTracker &IndentTracker) {
174     if (Next == End)
175       return nullptr;
176     const AnnotatedLine *Current = *Next;
177     IndentTracker.nextLine(*Current);
178     unsigned MergedLines = tryFitMultipleLinesInOne(IndentTracker, Next, End);
179     if (MergedLines > 0 && Style.ColumnLimit == 0)
180       // Disallow line merging if there is a break at the start of one of the
181       // input lines.
182       for (unsigned i = 0; i < MergedLines; ++i)
183         if (Next[i + 1]->First->NewlinesBefore > 0)
184           MergedLines = 0;
185     if (!DryRun)
186       for (unsigned i = 0; i < MergedLines; ++i)
187         join(*Next[0], *Next[i + 1]);
188     Next = Next + MergedLines + 1;
189     return Current;
190   }
191 
192 private:
193   /// Calculates how many lines can be merged into 1 starting at \p I.
194   unsigned
195   tryFitMultipleLinesInOne(LevelIndentTracker &IndentTracker,
196                            SmallVectorImpl<AnnotatedLine *>::const_iterator I,
197                            SmallVectorImpl<AnnotatedLine *>::const_iterator E) {
198     const unsigned Indent = IndentTracker.getIndent();
199 
200     // Can't join the last line with anything.
201     if (I + 1 == E)
202       return 0;
203     // We can never merge stuff if there are trailing line comments.
204     const AnnotatedLine *TheLine = *I;
205     if (TheLine->Last->is(TT_LineComment))
206       return 0;
207     if (I[1]->Type == LT_Invalid || I[1]->First->MustBreakBefore)
208       return 0;
209     if (TheLine->InPPDirective &&
210         (!I[1]->InPPDirective || I[1]->First->HasUnescapedNewline))
211       return 0;
212 
213     if (Style.ColumnLimit > 0 && Indent > Style.ColumnLimit)
214       return 0;
215 
216     unsigned Limit =
217         Style.ColumnLimit == 0 ? UINT_MAX : Style.ColumnLimit - Indent;
218     // If we already exceed the column limit, we set 'Limit' to 0. The different
219     // tryMerge..() functions can then decide whether to still do merging.
220     Limit = TheLine->Last->TotalLength > Limit
221                 ? 0
222                 : Limit - TheLine->Last->TotalLength;
223 
224     if (TheLine->Last->is(TT_FunctionLBrace) &&
225         TheLine->First == TheLine->Last &&
226         !Style.BraceWrapping.SplitEmptyFunction &&
227         I[1]->First->is(tok::r_brace))
228       return tryMergeSimpleBlock(I, E, Limit);
229 
230     // Handle empty record blocks where the brace has already been wrapped
231     if (TheLine->Last->is(tok::l_brace) && TheLine->First == TheLine->Last &&
232         I != AnnotatedLines.begin()) {
233       bool EmptyBlock = I[1]->First->is(tok::r_brace);
234 
235       const FormatToken *Tok = I[-1]->First;
236       if (Tok && Tok->is(tok::comment))
237         Tok = Tok->getNextNonComment();
238 
239       if (Tok && Tok->getNamespaceToken())
240         return !Style.BraceWrapping.SplitEmptyNamespace && EmptyBlock
241                    ? tryMergeSimpleBlock(I, E, Limit)
242                    : 0;
243 
244       if (Tok && Tok->is(tok::kw_typedef))
245         Tok = Tok->getNextNonComment();
246       if (Tok && Tok->isOneOf(tok::kw_class, tok::kw_struct, tok::kw_union,
247                               tok::kw_extern, Keywords.kw_interface))
248         return !Style.BraceWrapping.SplitEmptyRecord && EmptyBlock
249                    ? tryMergeSimpleBlock(I, E, Limit)
250                    : 0;
251     }
252 
253     // FIXME: TheLine->Level != 0 might or might not be the right check to do.
254     // If necessary, change to something smarter.
255     bool MergeShortFunctions =
256         Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_All ||
257         (Style.AllowShortFunctionsOnASingleLine >= FormatStyle::SFS_Empty &&
258          I[1]->First->is(tok::r_brace)) ||
259         (Style.AllowShortFunctionsOnASingleLine & FormatStyle::SFS_InlineOnly &&
260          TheLine->Level != 0);
261 
262     if (Style.CompactNamespaces) {
263       if (auto nsToken = TheLine->First->getNamespaceToken()) {
264         int i = 0;
265         unsigned closingLine = TheLine->MatchingClosingBlockLineIndex - 1;
266         for (; I + 1 + i != E &&
267                nsToken->TokenText == getNamespaceTokenText(I[i + 1]) &&
268                closingLine == I[i + 1]->MatchingClosingBlockLineIndex &&
269                I[i + 1]->Last->TotalLength < Limit;
270              i++, closingLine--) {
271           // No extra indent for compacted namespaces
272           IndentTracker.skipLine(*I[i + 1]);
273 
274           Limit -= I[i + 1]->Last->TotalLength;
275         }
276         return i;
277       }
278 
279       if (auto nsToken = getMatchingNamespaceToken(TheLine, AnnotatedLines)) {
280         int i = 0;
281         unsigned openingLine = TheLine->MatchingOpeningBlockLineIndex - 1;
282         for (; I + 1 + i != E &&
283                nsToken->TokenText ==
284                    getMatchingNamespaceTokenText(I[i + 1], AnnotatedLines) &&
285                openingLine == I[i + 1]->MatchingOpeningBlockLineIndex;
286              i++, openingLine--) {
287           // No space between consecutive braces
288           I[i + 1]->First->SpacesRequiredBefore = !I[i]->Last->is(tok::r_brace);
289 
290           // Indent like the outer-most namespace
291           IndentTracker.nextLine(*I[i + 1]);
292         }
293         return i;
294       }
295     }
296 
297     // Try to merge a CSharp property declaration like `{ get; private set }`.
298     if (Style.isCSharp()) {
299       unsigned CSPA = tryMergeCSharpPropertyAccessor(I, E, Limit);
300       if (CSPA > 0)
301         return CSPA;
302     }
303 
304     // Try to merge a function block with left brace unwrapped
305     if (TheLine->Last->is(TT_FunctionLBrace) &&
306         TheLine->First != TheLine->Last) {
307       return MergeShortFunctions ? tryMergeSimpleBlock(I, E, Limit) : 0;
308     }
309     // Try to merge a control statement block with left brace unwrapped
310     if (TheLine->Last->is(tok::l_brace) && TheLine->First != TheLine->Last &&
311         TheLine->First->isOneOf(tok::kw_if, tok::kw_while, tok::kw_for)) {
312       return Style.AllowShortBlocksOnASingleLine != FormatStyle::SBS_Never
313                  ? tryMergeSimpleBlock(I, E, Limit)
314                  : 0;
315     }
316     // Try to merge a control statement block with left brace wrapped
317     if (I[1]->First->is(tok::l_brace) &&
318         (TheLine->First->isOneOf(tok::kw_if, tok::kw_while, tok::kw_for,
319                                  tok::kw_switch, tok::kw_try, tok::kw_do) ||
320          (TheLine->First->is(tok::r_brace) && TheLine->First->Next &&
321           TheLine->First->Next->isOneOf(tok::kw_else, tok::kw_catch))) &&
322         Style.BraceWrapping.AfterControlStatement ==
323             FormatStyle::BWACS_MultiLine) {
324       // If possible, merge the next line's wrapped left brace with the current
325       // line. Otherwise, leave it on the next line, as this is a multi-line
326       // control statement.
327       return (Style.ColumnLimit == 0 ||
328               TheLine->Last->TotalLength <= Style.ColumnLimit)
329                  ? 1
330                  : 0;
331     } else if (I[1]->First->is(tok::l_brace) &&
332                TheLine->First->isOneOf(tok::kw_if, tok::kw_while,
333                                        tok::kw_for)) {
334       return (Style.BraceWrapping.AfterControlStatement ==
335               FormatStyle::BWACS_Always)
336                  ? tryMergeSimpleBlock(I, E, Limit)
337                  : 0;
338     } else if (I[1]->First->is(tok::l_brace) &&
339                TheLine->First->isOneOf(tok::kw_else, tok::kw_catch) &&
340                Style.BraceWrapping.AfterControlStatement ==
341                    FormatStyle::BWACS_MultiLine) {
342       // This case if different from the upper BWACS_MultiLine processing
343       // in that a preceding r_brace is not on the same line as else/catch
344       // most likely because of BeforeElse/BeforeCatch set to true.
345       // If the line length doesn't fit ColumnLimit, leave l_brace on the
346       // next line to respect the BWACS_MultiLine.
347       return (Style.ColumnLimit == 0 ||
348               TheLine->Last->TotalLength <= Style.ColumnLimit)
349                  ? 1
350                  : 0;
351     }
352     // Try to merge either empty or one-line block if is precedeed by control
353     // statement token
354     if (TheLine->First->is(tok::l_brace) && TheLine->First == TheLine->Last &&
355         I != AnnotatedLines.begin() &&
356         I[-1]->First->isOneOf(tok::kw_if, tok::kw_while, tok::kw_for)) {
357       unsigned MergedLines = 0;
358       if (Style.AllowShortBlocksOnASingleLine != FormatStyle::SBS_Never) {
359         MergedLines = tryMergeSimpleBlock(I - 1, E, Limit);
360         // If we managed to merge the block, discard the first merged line
361         // since we are merging starting from I.
362         if (MergedLines > 0)
363           --MergedLines;
364       }
365       return MergedLines;
366     }
367     // Don't merge block with left brace wrapped after ObjC special blocks
368     if (TheLine->First->is(tok::l_brace) && I != AnnotatedLines.begin() &&
369         I[-1]->First->is(tok::at) && I[-1]->First->Next) {
370       tok::ObjCKeywordKind kwId = I[-1]->First->Next->Tok.getObjCKeywordID();
371       if (kwId == clang::tok::objc_autoreleasepool ||
372           kwId == clang::tok::objc_synchronized)
373         return 0;
374     }
375     // Don't merge block with left brace wrapped after case labels
376     if (TheLine->First->is(tok::l_brace) && I != AnnotatedLines.begin() &&
377         I[-1]->First->isOneOf(tok::kw_case, tok::kw_default))
378       return 0;
379     // Try to merge a block with left brace wrapped that wasn't yet covered
380     if (TheLine->Last->is(tok::l_brace)) {
381       return !Style.BraceWrapping.AfterFunction ||
382                      (I[1]->First->is(tok::r_brace) &&
383                       !Style.BraceWrapping.SplitEmptyRecord)
384                  ? tryMergeSimpleBlock(I, E, Limit)
385                  : 0;
386     }
387     // Try to merge a function block with left brace wrapped
388     if (I[1]->First->is(TT_FunctionLBrace) &&
389         Style.BraceWrapping.AfterFunction) {
390       if (I[1]->Last->is(TT_LineComment))
391         return 0;
392 
393       // Check for Limit <= 2 to account for the " {".
394       if (Limit <= 2 || (Style.ColumnLimit == 0 && containsMustBreak(TheLine)))
395         return 0;
396       Limit -= 2;
397 
398       unsigned MergedLines = 0;
399       if (MergeShortFunctions ||
400           (Style.AllowShortFunctionsOnASingleLine >= FormatStyle::SFS_Empty &&
401            I[1]->First == I[1]->Last && I + 2 != E &&
402            I[2]->First->is(tok::r_brace))) {
403         MergedLines = tryMergeSimpleBlock(I + 1, E, Limit);
404         // If we managed to merge the block, count the function header, which is
405         // on a separate line.
406         if (MergedLines > 0)
407           ++MergedLines;
408       }
409       return MergedLines;
410     }
411     if (TheLine->First->is(tok::kw_if)) {
412       return Style.AllowShortIfStatementsOnASingleLine
413                  ? tryMergeSimpleControlStatement(I, E, Limit)
414                  : 0;
415     }
416     if (TheLine->First->isOneOf(tok::kw_for, tok::kw_while, tok::kw_do)) {
417       return Style.AllowShortLoopsOnASingleLine
418                  ? tryMergeSimpleControlStatement(I, E, Limit)
419                  : 0;
420     }
421     if (TheLine->First->isOneOf(tok::kw_case, tok::kw_default)) {
422       return Style.AllowShortCaseLabelsOnASingleLine
423                  ? tryMergeShortCaseLabels(I, E, Limit)
424                  : 0;
425     }
426     if (TheLine->InPPDirective &&
427         (TheLine->First->HasUnescapedNewline || TheLine->First->IsFirst)) {
428       return tryMergeSimplePPDirective(I, E, Limit);
429     }
430     return 0;
431   }
432 
433   // true for lines of the form [access-modifier] {get,set} [;]
434   bool isMergeablePropertyAccessor(const AnnotatedLine *Line) {
435     auto *Tok = Line->First;
436     if (!Tok)
437       return false;
438 
439     if (Tok->isOneOf(tok::kw_public, tok::kw_protected, tok::kw_private,
440                      Keywords.kw_internal))
441       Tok = Tok->Next;
442 
443     if (!Tok || (Tok->TokenText != "get" && Tok->TokenText != "set"))
444       return false;
445 
446     if (!Tok->Next || Tok->Next->is(tok::semi))
447       return true;
448 
449     return false;
450   }
451 
452   unsigned tryMergeCSharpPropertyAccessor(
453       SmallVectorImpl<AnnotatedLine *>::const_iterator I,
454       SmallVectorImpl<AnnotatedLine *>::const_iterator E, unsigned /*Limit*/) {
455 
456     auto CurrentLine = I;
457     // Does line start with `{`
458     if (!(*CurrentLine)->Last || (*CurrentLine)->Last->isNot(TT_FunctionLBrace))
459       return 0;
460     ++CurrentLine;
461 
462     unsigned MergedLines = 0;
463     bool HasGetOrSet = false;
464     while (CurrentLine != E) {
465       bool LineIsGetOrSet = isMergeablePropertyAccessor(*CurrentLine);
466       HasGetOrSet = HasGetOrSet || LineIsGetOrSet;
467       if (LineIsGetOrSet) {
468         ++CurrentLine;
469         ++MergedLines;
470         continue;
471       }
472       auto *Tok = (*CurrentLine)->First;
473       if (Tok && Tok->is(tok::r_brace)) {
474         ++CurrentLine;
475         ++MergedLines;
476         // See if the next line is a default value so that we can merge `{ get;
477         // set } = 0`
478         if (CurrentLine != E && (*CurrentLine)->First &&
479             (*CurrentLine)->First->is(tok::equal)) {
480           ++MergedLines;
481         }
482         break;
483       }
484       // Not a '}' or a get/set line so do not merege lines.
485       return 0;
486     }
487 
488     return HasGetOrSet ? MergedLines : 0;
489   }
490 
491   unsigned
492   tryMergeSimplePPDirective(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
493                             SmallVectorImpl<AnnotatedLine *>::const_iterator E,
494                             unsigned Limit) {
495     if (Limit == 0)
496       return 0;
497     if (I + 2 != E && I[2]->InPPDirective && !I[2]->First->HasUnescapedNewline)
498       return 0;
499     if (1 + I[1]->Last->TotalLength > Limit)
500       return 0;
501     return 1;
502   }
503 
504   unsigned tryMergeSimpleControlStatement(
505       SmallVectorImpl<AnnotatedLine *>::const_iterator I,
506       SmallVectorImpl<AnnotatedLine *>::const_iterator E, unsigned Limit) {
507     if (Limit == 0)
508       return 0;
509     if (Style.BraceWrapping.AfterControlStatement ==
510             FormatStyle::BWACS_Always &&
511         I[1]->First->is(tok::l_brace) &&
512         Style.AllowShortBlocksOnASingleLine == FormatStyle::SBS_Never)
513       return 0;
514     if (I[1]->InPPDirective != (*I)->InPPDirective ||
515         (I[1]->InPPDirective && I[1]->First->HasUnescapedNewline))
516       return 0;
517     Limit = limitConsideringMacros(I + 1, E, Limit);
518     AnnotatedLine &Line = **I;
519     if (!Line.First->is(tok::kw_do) && Line.Last->isNot(tok::r_paren))
520       return 0;
521     // Only merge do while if do is the only statement on the line.
522     if (Line.First->is(tok::kw_do) && !Line.Last->is(tok::kw_do))
523       return 0;
524     if (1 + I[1]->Last->TotalLength > Limit)
525       return 0;
526     if (I[1]->First->isOneOf(tok::semi, tok::kw_if, tok::kw_for, tok::kw_while,
527                              TT_LineComment))
528       return 0;
529     // Only inline simple if's (no nested if or else), unless specified
530     if (Style.AllowShortIfStatementsOnASingleLine != FormatStyle::SIS_Always) {
531       if (I + 2 != E && Line.startsWith(tok::kw_if) &&
532           I[2]->First->is(tok::kw_else))
533         return 0;
534     }
535     return 1;
536   }
537 
538   unsigned
539   tryMergeShortCaseLabels(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
540                           SmallVectorImpl<AnnotatedLine *>::const_iterator E,
541                           unsigned Limit) {
542     if (Limit == 0 || I + 1 == E ||
543         I[1]->First->isOneOf(tok::kw_case, tok::kw_default))
544       return 0;
545     if (I[0]->Last->is(tok::l_brace) || I[1]->First->is(tok::l_brace))
546       return 0;
547     unsigned NumStmts = 0;
548     unsigned Length = 0;
549     bool EndsWithComment = false;
550     bool InPPDirective = I[0]->InPPDirective;
551     const unsigned Level = I[0]->Level;
552     for (; NumStmts < 3; ++NumStmts) {
553       if (I + 1 + NumStmts == E)
554         break;
555       const AnnotatedLine *Line = I[1 + NumStmts];
556       if (Line->InPPDirective != InPPDirective)
557         break;
558       if (Line->First->isOneOf(tok::kw_case, tok::kw_default, tok::r_brace))
559         break;
560       if (Line->First->isOneOf(tok::kw_if, tok::kw_for, tok::kw_switch,
561                                tok::kw_while) ||
562           EndsWithComment)
563         return 0;
564       if (Line->First->is(tok::comment)) {
565         if (Level != Line->Level)
566           return 0;
567         SmallVectorImpl<AnnotatedLine *>::const_iterator J = I + 2 + NumStmts;
568         for (; J != E; ++J) {
569           Line = *J;
570           if (Line->InPPDirective != InPPDirective)
571             break;
572           if (Line->First->isOneOf(tok::kw_case, tok::kw_default, tok::r_brace))
573             break;
574           if (Line->First->isNot(tok::comment) || Level != Line->Level)
575             return 0;
576         }
577         break;
578       }
579       if (Line->Last->is(tok::comment))
580         EndsWithComment = true;
581       Length += I[1 + NumStmts]->Last->TotalLength + 1; // 1 for the space.
582     }
583     if (NumStmts == 0 || NumStmts == 3 || Length > Limit)
584       return 0;
585     return NumStmts;
586   }
587 
588   unsigned
589   tryMergeSimpleBlock(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
590                       SmallVectorImpl<AnnotatedLine *>::const_iterator E,
591                       unsigned Limit) {
592     AnnotatedLine &Line = **I;
593 
594     // Don't merge ObjC @ keywords and methods.
595     // FIXME: If an option to allow short exception handling clauses on a single
596     // line is added, change this to not return for @try and friends.
597     if (Style.Language != FormatStyle::LK_Java &&
598         Line.First->isOneOf(tok::at, tok::minus, tok::plus))
599       return 0;
600 
601     // Check that the current line allows merging. This depends on whether we
602     // are in a control flow statements as well as several style flags.
603     if (Line.First->isOneOf(tok::kw_else, tok::kw_case) ||
604         (Line.First->Next && Line.First->Next->is(tok::kw_else)))
605       return 0;
606     // default: in switch statement
607     if (Line.First->is(tok::kw_default)) {
608       const FormatToken *Tok = Line.First->getNextNonComment();
609       if (Tok && Tok->is(tok::colon))
610         return 0;
611     }
612     if (Line.First->isOneOf(tok::kw_if, tok::kw_while, tok::kw_do, tok::kw_try,
613                             tok::kw___try, tok::kw_catch, tok::kw___finally,
614                             tok::kw_for, tok::r_brace, Keywords.kw___except)) {
615       if (Style.AllowShortBlocksOnASingleLine == FormatStyle::SBS_Never)
616         return 0;
617       // Don't merge when we can't except the case when
618       // the control statement block is empty
619       if (!Style.AllowShortIfStatementsOnASingleLine &&
620           Line.startsWith(tok::kw_if) &&
621           !Style.BraceWrapping.AfterControlStatement &&
622           !I[1]->First->is(tok::r_brace))
623         return 0;
624       if (!Style.AllowShortIfStatementsOnASingleLine &&
625           Line.startsWith(tok::kw_if) &&
626           Style.BraceWrapping.AfterControlStatement ==
627               FormatStyle::BWACS_Always &&
628           I + 2 != E && !I[2]->First->is(tok::r_brace))
629         return 0;
630       if (!Style.AllowShortLoopsOnASingleLine &&
631           Line.First->isOneOf(tok::kw_while, tok::kw_do, tok::kw_for) &&
632           !Style.BraceWrapping.AfterControlStatement &&
633           !I[1]->First->is(tok::r_brace))
634         return 0;
635       if (!Style.AllowShortLoopsOnASingleLine &&
636           Line.First->isOneOf(tok::kw_while, tok::kw_do, tok::kw_for) &&
637           Style.BraceWrapping.AfterControlStatement ==
638               FormatStyle::BWACS_Always &&
639           I + 2 != E && !I[2]->First->is(tok::r_brace))
640         return 0;
641       // FIXME: Consider an option to allow short exception handling clauses on
642       // a single line.
643       // FIXME: This isn't covered by tests.
644       // FIXME: For catch, __except, __finally the first token on the line
645       // is '}', so this isn't correct here.
646       if (Line.First->isOneOf(tok::kw_try, tok::kw___try, tok::kw_catch,
647                               Keywords.kw___except, tok::kw___finally))
648         return 0;
649     }
650 
651     if (Line.Last->is(tok::l_brace)) {
652       FormatToken *Tok = I[1]->First;
653       if (Tok->is(tok::r_brace) && !Tok->MustBreakBefore &&
654           (Tok->getNextNonComment() == nullptr ||
655            Tok->getNextNonComment()->is(tok::semi))) {
656         // We merge empty blocks even if the line exceeds the column limit.
657         Tok->SpacesRequiredBefore = Style.SpaceInEmptyBlock ? 1 : 0;
658         Tok->CanBreakBefore = true;
659         return 1;
660       } else if (Limit != 0 && !Line.startsWithNamespace() &&
661                  !startsExternCBlock(Line)) {
662         // We don't merge short records.
663         FormatToken *RecordTok = Line.First;
664         // Skip record modifiers.
665         while (RecordTok->Next &&
666                RecordTok->isOneOf(
667                    tok::kw_typedef, tok::kw_export, Keywords.kw_declare,
668                    Keywords.kw_abstract, tok::kw_default, tok::kw_public,
669                    tok::kw_private, tok::kw_protected, Keywords.kw_internal))
670           RecordTok = RecordTok->Next;
671         if (RecordTok &&
672             RecordTok->isOneOf(tok::kw_class, tok::kw_union, tok::kw_struct,
673                                Keywords.kw_interface))
674           return 0;
675 
676         // Check that we still have three lines and they fit into the limit.
677         if (I + 2 == E || I[2]->Type == LT_Invalid)
678           return 0;
679         Limit = limitConsideringMacros(I + 2, E, Limit);
680 
681         if (!nextTwoLinesFitInto(I, Limit))
682           return 0;
683 
684         // Second, check that the next line does not contain any braces - if it
685         // does, readability declines when putting it into a single line.
686         if (I[1]->Last->is(TT_LineComment))
687           return 0;
688         do {
689           if (Tok->is(tok::l_brace) && Tok->BlockKind != BK_BracedInit)
690             return 0;
691           Tok = Tok->Next;
692         } while (Tok);
693 
694         // Last, check that the third line starts with a closing brace.
695         Tok = I[2]->First;
696         if (Tok->isNot(tok::r_brace))
697           return 0;
698 
699         // Don't merge "if (a) { .. } else {".
700         if (Tok->Next && Tok->Next->is(tok::kw_else))
701           return 0;
702 
703         // Don't merge a trailing multi-line control statement block like:
704         // } else if (foo &&
705         //            bar)
706         // { <-- current Line
707         //   baz();
708         // }
709         if (Line.First == Line.Last &&
710             Style.BraceWrapping.AfterControlStatement ==
711                 FormatStyle::BWACS_MultiLine)
712           return 0;
713 
714         return 2;
715       }
716     } else if (I[1]->First->is(tok::l_brace)) {
717       if (I[1]->Last->is(TT_LineComment))
718         return 0;
719 
720       // Check for Limit <= 2 to account for the " {".
721       if (Limit <= 2 || (Style.ColumnLimit == 0 && containsMustBreak(*I)))
722         return 0;
723       Limit -= 2;
724       unsigned MergedLines = 0;
725       if (Style.AllowShortBlocksOnASingleLine != FormatStyle::SBS_Never ||
726           (I[1]->First == I[1]->Last && I + 2 != E &&
727            I[2]->First->is(tok::r_brace))) {
728         MergedLines = tryMergeSimpleBlock(I + 1, E, Limit);
729         // If we managed to merge the block, count the statement header, which
730         // is on a separate line.
731         if (MergedLines > 0)
732           ++MergedLines;
733       }
734       return MergedLines;
735     }
736     return 0;
737   }
738 
739   /// Returns the modified column limit for \p I if it is inside a macro and
740   /// needs a trailing '\'.
741   unsigned
742   limitConsideringMacros(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
743                          SmallVectorImpl<AnnotatedLine *>::const_iterator E,
744                          unsigned Limit) {
745     if (I[0]->InPPDirective && I + 1 != E &&
746         !I[1]->First->HasUnescapedNewline && !I[1]->First->is(tok::eof)) {
747       return Limit < 2 ? 0 : Limit - 2;
748     }
749     return Limit;
750   }
751 
752   bool nextTwoLinesFitInto(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
753                            unsigned Limit) {
754     if (I[1]->First->MustBreakBefore || I[2]->First->MustBreakBefore)
755       return false;
756     return 1 + I[1]->Last->TotalLength + 1 + I[2]->Last->TotalLength <= Limit;
757   }
758 
759   bool containsMustBreak(const AnnotatedLine *Line) {
760     for (const FormatToken *Tok = Line->First; Tok; Tok = Tok->Next) {
761       if (Tok->MustBreakBefore)
762         return true;
763     }
764     return false;
765   }
766 
767   void join(AnnotatedLine &A, const AnnotatedLine &B) {
768     assert(!A.Last->Next);
769     assert(!B.First->Previous);
770     if (B.Affected)
771       A.Affected = true;
772     A.Last->Next = B.First;
773     B.First->Previous = A.Last;
774     B.First->CanBreakBefore = true;
775     unsigned LengthA = A.Last->TotalLength + B.First->SpacesRequiredBefore;
776     for (FormatToken *Tok = B.First; Tok; Tok = Tok->Next) {
777       Tok->TotalLength += LengthA;
778       A.Last = Tok;
779     }
780   }
781 
782   const FormatStyle &Style;
783   const AdditionalKeywords &Keywords;
784   const SmallVectorImpl<AnnotatedLine *>::const_iterator End;
785 
786   SmallVectorImpl<AnnotatedLine *>::const_iterator Next;
787   const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines;
788 };
789 
790 static void markFinalized(FormatToken *Tok) {
791   for (; Tok; Tok = Tok->Next) {
792     Tok->Finalized = true;
793     for (AnnotatedLine *Child : Tok->Children)
794       markFinalized(Child->First);
795   }
796 }
797 
798 #ifndef NDEBUG
799 static void printLineState(const LineState &State) {
800   llvm::dbgs() << "State: ";
801   for (const ParenState &P : State.Stack) {
802     llvm::dbgs() << (P.Tok ? P.Tok->TokenText : "F") << "|" << P.Indent << "|"
803                  << P.LastSpace << "|" << P.NestedBlockIndent << " ";
804   }
805   llvm::dbgs() << State.NextToken->TokenText << "\n";
806 }
807 #endif
808 
809 /// Base class for classes that format one \c AnnotatedLine.
810 class LineFormatter {
811 public:
812   LineFormatter(ContinuationIndenter *Indenter, WhitespaceManager *Whitespaces,
813                 const FormatStyle &Style,
814                 UnwrappedLineFormatter *BlockFormatter)
815       : Indenter(Indenter), Whitespaces(Whitespaces), Style(Style),
816         BlockFormatter(BlockFormatter) {}
817   virtual ~LineFormatter() {}
818 
819   /// Formats an \c AnnotatedLine and returns the penalty.
820   ///
821   /// If \p DryRun is \c false, directly applies the changes.
822   virtual unsigned formatLine(const AnnotatedLine &Line, unsigned FirstIndent,
823                               unsigned FirstStartColumn, bool DryRun) = 0;
824 
825 protected:
826   /// If the \p State's next token is an r_brace closing a nested block,
827   /// format the nested block before it.
828   ///
829   /// Returns \c true if all children could be placed successfully and adapts
830   /// \p Penalty as well as \p State. If \p DryRun is false, also directly
831   /// creates changes using \c Whitespaces.
832   ///
833   /// The crucial idea here is that children always get formatted upon
834   /// encountering the closing brace right after the nested block. Now, if we
835   /// are currently trying to keep the "}" on the same line (i.e. \p NewLine is
836   /// \c false), the entire block has to be kept on the same line (which is only
837   /// possible if it fits on the line, only contains a single statement, etc.
838   ///
839   /// If \p NewLine is true, we format the nested block on separate lines, i.e.
840   /// break after the "{", format all lines with correct indentation and the put
841   /// the closing "}" on yet another new line.
842   ///
843   /// This enables us to keep the simple structure of the
844   /// \c UnwrappedLineFormatter, where we only have two options for each token:
845   /// break or don't break.
846   bool formatChildren(LineState &State, bool NewLine, bool DryRun,
847                       unsigned &Penalty) {
848     const FormatToken *LBrace = State.NextToken->getPreviousNonComment();
849     FormatToken &Previous = *State.NextToken->Previous;
850     if (!LBrace || LBrace->isNot(tok::l_brace) ||
851         LBrace->BlockKind != BK_Block || Previous.Children.size() == 0)
852       // The previous token does not open a block. Nothing to do. We don't
853       // assert so that we can simply call this function for all tokens.
854       return true;
855 
856     if (NewLine) {
857       int AdditionalIndent = State.Stack.back().Indent -
858                              Previous.Children[0]->Level * Style.IndentWidth;
859 
860       Penalty +=
861           BlockFormatter->format(Previous.Children, DryRun, AdditionalIndent,
862                                  /*FixBadIndentation=*/true);
863       return true;
864     }
865 
866     if (Previous.Children[0]->First->MustBreakBefore)
867       return false;
868 
869     // Cannot merge into one line if this line ends on a comment.
870     if (Previous.is(tok::comment))
871       return false;
872 
873     // Cannot merge multiple statements into a single line.
874     if (Previous.Children.size() > 1)
875       return false;
876 
877     const AnnotatedLine *Child = Previous.Children[0];
878     // We can't put the closing "}" on a line with a trailing comment.
879     if (Child->Last->isTrailingComment())
880       return false;
881 
882     // If the child line exceeds the column limit, we wouldn't want to merge it.
883     // We add +2 for the trailing " }".
884     if (Style.ColumnLimit > 0 &&
885         Child->Last->TotalLength + State.Column + 2 > Style.ColumnLimit)
886       return false;
887 
888     if (!DryRun) {
889       Whitespaces->replaceWhitespace(
890           *Child->First, /*Newlines=*/0, /*Spaces=*/1,
891           /*StartOfTokenColumn=*/State.Column, State.Line->InPPDirective);
892     }
893     Penalty +=
894         formatLine(*Child, State.Column + 1, /*FirstStartColumn=*/0, DryRun);
895 
896     State.Column += 1 + Child->Last->TotalLength;
897     return true;
898   }
899 
900   ContinuationIndenter *Indenter;
901 
902 private:
903   WhitespaceManager *Whitespaces;
904   const FormatStyle &Style;
905   UnwrappedLineFormatter *BlockFormatter;
906 };
907 
908 /// Formatter that keeps the existing line breaks.
909 class NoColumnLimitLineFormatter : public LineFormatter {
910 public:
911   NoColumnLimitLineFormatter(ContinuationIndenter *Indenter,
912                              WhitespaceManager *Whitespaces,
913                              const FormatStyle &Style,
914                              UnwrappedLineFormatter *BlockFormatter)
915       : LineFormatter(Indenter, Whitespaces, Style, BlockFormatter) {}
916 
917   /// Formats the line, simply keeping all of the input's line breaking
918   /// decisions.
919   unsigned formatLine(const AnnotatedLine &Line, unsigned FirstIndent,
920                       unsigned FirstStartColumn, bool DryRun) override {
921     assert(!DryRun);
922     LineState State = Indenter->getInitialState(FirstIndent, FirstStartColumn,
923                                                 &Line, /*DryRun=*/false);
924     while (State.NextToken) {
925       bool Newline =
926           Indenter->mustBreak(State) ||
927           (Indenter->canBreak(State) && State.NextToken->NewlinesBefore > 0);
928       unsigned Penalty = 0;
929       formatChildren(State, Newline, /*DryRun=*/false, Penalty);
930       Indenter->addTokenToState(State, Newline, /*DryRun=*/false);
931     }
932     return 0;
933   }
934 };
935 
936 /// Formatter that puts all tokens into a single line without breaks.
937 class NoLineBreakFormatter : public LineFormatter {
938 public:
939   NoLineBreakFormatter(ContinuationIndenter *Indenter,
940                        WhitespaceManager *Whitespaces, const FormatStyle &Style,
941                        UnwrappedLineFormatter *BlockFormatter)
942       : LineFormatter(Indenter, Whitespaces, Style, BlockFormatter) {}
943 
944   /// Puts all tokens into a single line.
945   unsigned formatLine(const AnnotatedLine &Line, unsigned FirstIndent,
946                       unsigned FirstStartColumn, bool DryRun) override {
947     unsigned Penalty = 0;
948     LineState State =
949         Indenter->getInitialState(FirstIndent, FirstStartColumn, &Line, DryRun);
950     while (State.NextToken) {
951       formatChildren(State, /*NewLine=*/false, DryRun, Penalty);
952       Indenter->addTokenToState(
953           State, /*Newline=*/State.NextToken->MustBreakBefore, DryRun);
954     }
955     return Penalty;
956   }
957 };
958 
959 /// Finds the best way to break lines.
960 class OptimizingLineFormatter : public LineFormatter {
961 public:
962   OptimizingLineFormatter(ContinuationIndenter *Indenter,
963                           WhitespaceManager *Whitespaces,
964                           const FormatStyle &Style,
965                           UnwrappedLineFormatter *BlockFormatter)
966       : LineFormatter(Indenter, Whitespaces, Style, BlockFormatter) {}
967 
968   /// Formats the line by finding the best line breaks with line lengths
969   /// below the column limit.
970   unsigned formatLine(const AnnotatedLine &Line, unsigned FirstIndent,
971                       unsigned FirstStartColumn, bool DryRun) override {
972     LineState State =
973         Indenter->getInitialState(FirstIndent, FirstStartColumn, &Line, DryRun);
974 
975     // If the ObjC method declaration does not fit on a line, we should format
976     // it with one arg per line.
977     if (State.Line->Type == LT_ObjCMethodDecl)
978       State.Stack.back().BreakBeforeParameter = true;
979 
980     // Find best solution in solution space.
981     return analyzeSolutionSpace(State, DryRun);
982   }
983 
984 private:
985   struct CompareLineStatePointers {
986     bool operator()(LineState *obj1, LineState *obj2) const {
987       return *obj1 < *obj2;
988     }
989   };
990 
991   /// A pair of <penalty, count> that is used to prioritize the BFS on.
992   ///
993   /// In case of equal penalties, we want to prefer states that were inserted
994   /// first. During state generation we make sure that we insert states first
995   /// that break the line as late as possible.
996   typedef std::pair<unsigned, unsigned> OrderedPenalty;
997 
998   /// An edge in the solution space from \c Previous->State to \c State,
999   /// inserting a newline dependent on the \c NewLine.
1000   struct StateNode {
1001     StateNode(const LineState &State, bool NewLine, StateNode *Previous)
1002         : State(State), NewLine(NewLine), Previous(Previous) {}
1003     LineState State;
1004     bool NewLine;
1005     StateNode *Previous;
1006   };
1007 
1008   /// An item in the prioritized BFS search queue. The \c StateNode's
1009   /// \c State has the given \c OrderedPenalty.
1010   typedef std::pair<OrderedPenalty, StateNode *> QueueItem;
1011 
1012   /// The BFS queue type.
1013   typedef std::priority_queue<QueueItem, std::vector<QueueItem>,
1014                               std::greater<QueueItem>>
1015       QueueType;
1016 
1017   /// Analyze the entire solution space starting from \p InitialState.
1018   ///
1019   /// This implements a variant of Dijkstra's algorithm on the graph that spans
1020   /// the solution space (\c LineStates are the nodes). The algorithm tries to
1021   /// find the shortest path (the one with lowest penalty) from \p InitialState
1022   /// to a state where all tokens are placed. Returns the penalty.
1023   ///
1024   /// If \p DryRun is \c false, directly applies the changes.
1025   unsigned analyzeSolutionSpace(LineState &InitialState, bool DryRun) {
1026     std::set<LineState *, CompareLineStatePointers> Seen;
1027 
1028     // Increasing count of \c StateNode items we have created. This is used to
1029     // create a deterministic order independent of the container.
1030     unsigned Count = 0;
1031     QueueType Queue;
1032 
1033     // Insert start element into queue.
1034     StateNode *Node =
1035         new (Allocator.Allocate()) StateNode(InitialState, false, nullptr);
1036     Queue.push(QueueItem(OrderedPenalty(0, Count), Node));
1037     ++Count;
1038 
1039     unsigned Penalty = 0;
1040 
1041     // While not empty, take first element and follow edges.
1042     while (!Queue.empty()) {
1043       Penalty = Queue.top().first.first;
1044       StateNode *Node = Queue.top().second;
1045       if (!Node->State.NextToken) {
1046         LLVM_DEBUG(llvm::dbgs()
1047                    << "\n---\nPenalty for line: " << Penalty << "\n");
1048         break;
1049       }
1050       Queue.pop();
1051 
1052       // Cut off the analysis of certain solutions if the analysis gets too
1053       // complex. See description of IgnoreStackForComparison.
1054       if (Count > 50000)
1055         Node->State.IgnoreStackForComparison = true;
1056 
1057       if (!Seen.insert(&Node->State).second)
1058         // State already examined with lower penalty.
1059         continue;
1060 
1061       FormatDecision LastFormat = Node->State.NextToken->Decision;
1062       if (LastFormat == FD_Unformatted || LastFormat == FD_Continue)
1063         addNextStateToQueue(Penalty, Node, /*NewLine=*/false, &Count, &Queue);
1064       if (LastFormat == FD_Unformatted || LastFormat == FD_Break)
1065         addNextStateToQueue(Penalty, Node, /*NewLine=*/true, &Count, &Queue);
1066     }
1067 
1068     if (Queue.empty()) {
1069       // We were unable to find a solution, do nothing.
1070       // FIXME: Add diagnostic?
1071       LLVM_DEBUG(llvm::dbgs() << "Could not find a solution.\n");
1072       return 0;
1073     }
1074 
1075     // Reconstruct the solution.
1076     if (!DryRun)
1077       reconstructPath(InitialState, Queue.top().second);
1078 
1079     LLVM_DEBUG(llvm::dbgs()
1080                << "Total number of analyzed states: " << Count << "\n");
1081     LLVM_DEBUG(llvm::dbgs() << "---\n");
1082 
1083     return Penalty;
1084   }
1085 
1086   /// Add the following state to the analysis queue \c Queue.
1087   ///
1088   /// Assume the current state is \p PreviousNode and has been reached with a
1089   /// penalty of \p Penalty. Insert a line break if \p NewLine is \c true.
1090   void addNextStateToQueue(unsigned Penalty, StateNode *PreviousNode,
1091                            bool NewLine, unsigned *Count, QueueType *Queue) {
1092     if (NewLine && !Indenter->canBreak(PreviousNode->State))
1093       return;
1094     if (!NewLine && Indenter->mustBreak(PreviousNode->State))
1095       return;
1096 
1097     StateNode *Node = new (Allocator.Allocate())
1098         StateNode(PreviousNode->State, NewLine, PreviousNode);
1099     if (!formatChildren(Node->State, NewLine, /*DryRun=*/true, Penalty))
1100       return;
1101 
1102     Penalty += Indenter->addTokenToState(Node->State, NewLine, true);
1103 
1104     Queue->push(QueueItem(OrderedPenalty(Penalty, *Count), Node));
1105     ++(*Count);
1106   }
1107 
1108   /// Applies the best formatting by reconstructing the path in the
1109   /// solution space that leads to \c Best.
1110   void reconstructPath(LineState &State, StateNode *Best) {
1111     std::deque<StateNode *> Path;
1112     // We do not need a break before the initial token.
1113     while (Best->Previous) {
1114       Path.push_front(Best);
1115       Best = Best->Previous;
1116     }
1117     for (auto I = Path.begin(), E = Path.end(); I != E; ++I) {
1118       unsigned Penalty = 0;
1119       formatChildren(State, (*I)->NewLine, /*DryRun=*/false, Penalty);
1120       Penalty += Indenter->addTokenToState(State, (*I)->NewLine, false);
1121 
1122       LLVM_DEBUG({
1123         printLineState((*I)->Previous->State);
1124         if ((*I)->NewLine) {
1125           llvm::dbgs() << "Penalty for placing "
1126                        << (*I)->Previous->State.NextToken->Tok.getName()
1127                        << " on a new line: " << Penalty << "\n";
1128         }
1129       });
1130     }
1131   }
1132 
1133   llvm::SpecificBumpPtrAllocator<StateNode> Allocator;
1134 };
1135 
1136 } // anonymous namespace
1137 
1138 unsigned UnwrappedLineFormatter::format(
1139     const SmallVectorImpl<AnnotatedLine *> &Lines, bool DryRun,
1140     int AdditionalIndent, bool FixBadIndentation, unsigned FirstStartColumn,
1141     unsigned NextStartColumn, unsigned LastStartColumn) {
1142   LineJoiner Joiner(Style, Keywords, Lines);
1143 
1144   // Try to look up already computed penalty in DryRun-mode.
1145   std::pair<const SmallVectorImpl<AnnotatedLine *> *, unsigned> CacheKey(
1146       &Lines, AdditionalIndent);
1147   auto CacheIt = PenaltyCache.find(CacheKey);
1148   if (DryRun && CacheIt != PenaltyCache.end())
1149     return CacheIt->second;
1150 
1151   assert(!Lines.empty());
1152   unsigned Penalty = 0;
1153   LevelIndentTracker IndentTracker(Style, Keywords, Lines[0]->Level,
1154                                    AdditionalIndent);
1155   const AnnotatedLine *PreviousLine = nullptr;
1156   const AnnotatedLine *NextLine = nullptr;
1157 
1158   // The minimum level of consecutive lines that have been formatted.
1159   unsigned RangeMinLevel = UINT_MAX;
1160 
1161   bool FirstLine = true;
1162   for (const AnnotatedLine *Line =
1163            Joiner.getNextMergedLine(DryRun, IndentTracker);
1164        Line; Line = NextLine, FirstLine = false) {
1165     const AnnotatedLine &TheLine = *Line;
1166     unsigned Indent = IndentTracker.getIndent();
1167 
1168     // We continue formatting unchanged lines to adjust their indent, e.g. if a
1169     // scope was added. However, we need to carefully stop doing this when we
1170     // exit the scope of affected lines to prevent indenting a the entire
1171     // remaining file if it currently missing a closing brace.
1172     bool PreviousRBrace =
1173         PreviousLine && PreviousLine->startsWith(tok::r_brace);
1174     bool ContinueFormatting =
1175         TheLine.Level > RangeMinLevel ||
1176         (TheLine.Level == RangeMinLevel && !PreviousRBrace &&
1177          !TheLine.startsWith(tok::r_brace));
1178 
1179     bool FixIndentation = (FixBadIndentation || ContinueFormatting) &&
1180                           Indent != TheLine.First->OriginalColumn;
1181     bool ShouldFormat = TheLine.Affected || FixIndentation;
1182     // We cannot format this line; if the reason is that the line had a
1183     // parsing error, remember that.
1184     if (ShouldFormat && TheLine.Type == LT_Invalid && Status) {
1185       Status->FormatComplete = false;
1186       Status->Line =
1187           SourceMgr.getSpellingLineNumber(TheLine.First->Tok.getLocation());
1188     }
1189 
1190     if (ShouldFormat && TheLine.Type != LT_Invalid) {
1191       if (!DryRun) {
1192         bool LastLine = Line->First->is(tok::eof);
1193         formatFirstToken(TheLine, PreviousLine, Lines, Indent,
1194                          LastLine ? LastStartColumn : NextStartColumn + Indent);
1195       }
1196 
1197       NextLine = Joiner.getNextMergedLine(DryRun, IndentTracker);
1198       unsigned ColumnLimit = getColumnLimit(TheLine.InPPDirective, NextLine);
1199       bool FitsIntoOneLine =
1200           TheLine.Last->TotalLength + Indent <= ColumnLimit ||
1201           (TheLine.Type == LT_ImportStatement &&
1202            (Style.Language != FormatStyle::LK_JavaScript ||
1203             !Style.JavaScriptWrapImports)) ||
1204           (Style.isCSharp() &&
1205            TheLine.InPPDirective); // don't split #regions in C#
1206       if (Style.ColumnLimit == 0)
1207         NoColumnLimitLineFormatter(Indenter, Whitespaces, Style, this)
1208             .formatLine(TheLine, NextStartColumn + Indent,
1209                         FirstLine ? FirstStartColumn : 0, DryRun);
1210       else if (FitsIntoOneLine)
1211         Penalty += NoLineBreakFormatter(Indenter, Whitespaces, Style, this)
1212                        .formatLine(TheLine, NextStartColumn + Indent,
1213                                    FirstLine ? FirstStartColumn : 0, DryRun);
1214       else
1215         Penalty += OptimizingLineFormatter(Indenter, Whitespaces, Style, this)
1216                        .formatLine(TheLine, NextStartColumn + Indent,
1217                                    FirstLine ? FirstStartColumn : 0, DryRun);
1218       RangeMinLevel = std::min(RangeMinLevel, TheLine.Level);
1219     } else {
1220       // If no token in the current line is affected, we still need to format
1221       // affected children.
1222       if (TheLine.ChildrenAffected)
1223         for (const FormatToken *Tok = TheLine.First; Tok; Tok = Tok->Next)
1224           if (!Tok->Children.empty())
1225             format(Tok->Children, DryRun);
1226 
1227       // Adapt following lines on the current indent level to the same level
1228       // unless the current \c AnnotatedLine is not at the beginning of a line.
1229       bool StartsNewLine =
1230           TheLine.First->NewlinesBefore > 0 || TheLine.First->IsFirst;
1231       if (StartsNewLine)
1232         IndentTracker.adjustToUnmodifiedLine(TheLine);
1233       if (!DryRun) {
1234         bool ReformatLeadingWhitespace =
1235             StartsNewLine && ((PreviousLine && PreviousLine->Affected) ||
1236                               TheLine.LeadingEmptyLinesAffected);
1237         // Format the first token.
1238         if (ReformatLeadingWhitespace)
1239           formatFirstToken(TheLine, PreviousLine, Lines,
1240                            TheLine.First->OriginalColumn,
1241                            TheLine.First->OriginalColumn);
1242         else
1243           Whitespaces->addUntouchableToken(*TheLine.First,
1244                                            TheLine.InPPDirective);
1245 
1246         // Notify the WhitespaceManager about the unchanged whitespace.
1247         for (FormatToken *Tok = TheLine.First->Next; Tok; Tok = Tok->Next)
1248           Whitespaces->addUntouchableToken(*Tok, TheLine.InPPDirective);
1249       }
1250       NextLine = Joiner.getNextMergedLine(DryRun, IndentTracker);
1251       RangeMinLevel = UINT_MAX;
1252     }
1253     if (!DryRun)
1254       markFinalized(TheLine.First);
1255     PreviousLine = &TheLine;
1256   }
1257   PenaltyCache[CacheKey] = Penalty;
1258   return Penalty;
1259 }
1260 
1261 void UnwrappedLineFormatter::formatFirstToken(
1262     const AnnotatedLine &Line, const AnnotatedLine *PreviousLine,
1263     const SmallVectorImpl<AnnotatedLine *> &Lines, unsigned Indent,
1264     unsigned NewlineIndent) {
1265   FormatToken &RootToken = *Line.First;
1266   if (RootToken.is(tok::eof)) {
1267     unsigned Newlines = std::min(RootToken.NewlinesBefore, 1u);
1268     unsigned TokenIndent = Newlines ? NewlineIndent : 0;
1269     Whitespaces->replaceWhitespace(RootToken, Newlines, TokenIndent,
1270                                    TokenIndent);
1271     return;
1272   }
1273   unsigned Newlines =
1274       std::min(RootToken.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1);
1275   // Remove empty lines before "}" where applicable.
1276   if (RootToken.is(tok::r_brace) &&
1277       (!RootToken.Next ||
1278        (RootToken.Next->is(tok::semi) && !RootToken.Next->Next)) &&
1279       // Do not remove empty lines before namespace closing "}".
1280       !getNamespaceToken(&Line, Lines))
1281     Newlines = std::min(Newlines, 1u);
1282   // Remove empty lines at the start of nested blocks (lambdas/arrow functions)
1283   if (PreviousLine == nullptr && Line.Level > 0)
1284     Newlines = std::min(Newlines, 1u);
1285   if (Newlines == 0 && !RootToken.IsFirst)
1286     Newlines = 1;
1287   if (RootToken.IsFirst && !RootToken.HasUnescapedNewline)
1288     Newlines = 0;
1289 
1290   // Remove empty lines after "{".
1291   if (!Style.KeepEmptyLinesAtTheStartOfBlocks && PreviousLine &&
1292       PreviousLine->Last->is(tok::l_brace) &&
1293       !PreviousLine->startsWithNamespace() &&
1294       !startsExternCBlock(*PreviousLine))
1295     Newlines = 1;
1296 
1297   // Insert extra new line before access specifiers.
1298   if (PreviousLine && PreviousLine->Last->isOneOf(tok::semi, tok::r_brace) &&
1299       RootToken.isAccessSpecifier() && RootToken.NewlinesBefore == 1)
1300     ++Newlines;
1301 
1302   // Remove empty lines after access specifiers.
1303   if (PreviousLine && PreviousLine->First->isAccessSpecifier() &&
1304       (!PreviousLine->InPPDirective || !RootToken.HasUnescapedNewline))
1305     Newlines = std::min(1u, Newlines);
1306 
1307   if (Newlines)
1308     Indent = NewlineIndent;
1309 
1310   // If in Whitemsmiths mode, indent start and end of blocks
1311   if (Style.BreakBeforeBraces == FormatStyle::BS_Whitesmiths) {
1312     if (RootToken.isOneOf(tok::l_brace, tok::r_brace, tok::kw_case))
1313       Indent += Style.IndentWidth;
1314   }
1315 
1316   // Preprocessor directives get indented before the hash only if specified
1317   if (Style.IndentPPDirectives != FormatStyle::PPDIS_BeforeHash &&
1318       (Line.Type == LT_PreprocessorDirective ||
1319        Line.Type == LT_ImportStatement))
1320     Indent = 0;
1321 
1322   Whitespaces->replaceWhitespace(RootToken, Newlines, Indent, Indent,
1323                                  Line.InPPDirective &&
1324                                      !RootToken.HasUnescapedNewline);
1325 }
1326 
1327 unsigned
1328 UnwrappedLineFormatter::getColumnLimit(bool InPPDirective,
1329                                        const AnnotatedLine *NextLine) const {
1330   // In preprocessor directives reserve two chars for trailing " \" if the
1331   // next line continues the preprocessor directive.
1332   bool ContinuesPPDirective =
1333       InPPDirective &&
1334       // If there is no next line, this is likely a child line and the parent
1335       // continues the preprocessor directive.
1336       (!NextLine ||
1337        (NextLine->InPPDirective &&
1338         // If there is an unescaped newline between this line and the next, the
1339         // next line starts a new preprocessor directive.
1340         !NextLine->First->HasUnescapedNewline));
1341   return Style.ColumnLimit - (ContinuesPPDirective ? 2 : 0);
1342 }
1343 
1344 } // namespace format
1345 } // namespace clang
1346