xref: /freebsd/contrib/llvm-project/clang/lib/Format/UnwrappedLineFormatter.cpp (revision cfd6422a5217410fbd66f7a7a8a64d9d85e61229)
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 function block with left brace unwrapped
298     if (TheLine->Last->is(TT_FunctionLBrace) &&
299         TheLine->First != TheLine->Last) {
300       return MergeShortFunctions ? tryMergeSimpleBlock(I, E, Limit) : 0;
301     }
302     // Try to merge a control statement block with left brace unwrapped
303     if (TheLine->Last->is(tok::l_brace) && TheLine->First != TheLine->Last &&
304         TheLine->First->isOneOf(tok::kw_if, tok::kw_while, tok::kw_for)) {
305       return Style.AllowShortBlocksOnASingleLine != FormatStyle::SBS_Never
306                  ? tryMergeSimpleBlock(I, E, Limit)
307                  : 0;
308     }
309     // Try to merge a control statement block with left brace wrapped
310     if (I[1]->First->is(tok::l_brace) &&
311         (TheLine->First->isOneOf(tok::kw_if, tok::kw_while, tok::kw_for,
312                                  tok::kw_switch, tok::kw_try, tok::kw_do) ||
313          (TheLine->First->is(tok::r_brace) && TheLine->First->Next &&
314           TheLine->First->Next->isOneOf(tok::kw_else, tok::kw_catch))) &&
315         Style.BraceWrapping.AfterControlStatement ==
316             FormatStyle::BWACS_MultiLine) {
317       // If possible, merge the next line's wrapped left brace with the current
318       // line. Otherwise, leave it on the next line, as this is a multi-line
319       // control statement.
320       return (Style.ColumnLimit == 0 ||
321               TheLine->Last->TotalLength <= Style.ColumnLimit)
322                  ? 1
323                  : 0;
324     } else if (I[1]->First->is(tok::l_brace) &&
325                TheLine->First->isOneOf(tok::kw_if, tok::kw_while,
326                                        tok::kw_for)) {
327       return (Style.BraceWrapping.AfterControlStatement ==
328               FormatStyle::BWACS_Always)
329                  ? tryMergeSimpleBlock(I, E, Limit)
330                  : 0;
331     } else if (I[1]->First->is(tok::l_brace) &&
332                TheLine->First->isOneOf(tok::kw_else, tok::kw_catch) &&
333                Style.BraceWrapping.AfterControlStatement ==
334                    FormatStyle::BWACS_MultiLine) {
335       // This case if different from the upper BWACS_MultiLine processing
336       // in that a preceding r_brace is not on the same line as else/catch
337       // most likely because of BeforeElse/BeforeCatch set to true.
338       // If the line length doesn't fit ColumnLimit, leave l_brace on the
339       // next line to respect the BWACS_MultiLine.
340       return (Style.ColumnLimit == 0 ||
341               TheLine->Last->TotalLength <= Style.ColumnLimit)
342                  ? 1
343                  : 0;
344     }
345     // Don't merge block with left brace wrapped after ObjC special blocks
346     if (TheLine->First->is(tok::l_brace) && I != AnnotatedLines.begin() &&
347         I[-1]->First->is(tok::at) && I[-1]->First->Next) {
348       tok::ObjCKeywordKind kwId = I[-1]->First->Next->Tok.getObjCKeywordID();
349       if (kwId == clang::tok::objc_autoreleasepool ||
350           kwId == clang::tok::objc_synchronized)
351         return 0;
352     }
353     // Don't merge block with left brace wrapped after case labels
354     if (TheLine->First->is(tok::l_brace) && I != AnnotatedLines.begin() &&
355         I[-1]->First->isOneOf(tok::kw_case, tok::kw_default))
356       return 0;
357     // Try to merge a block with left brace wrapped that wasn't yet covered
358     if (TheLine->Last->is(tok::l_brace)) {
359       return !Style.BraceWrapping.AfterFunction ||
360                      (I[1]->First->is(tok::r_brace) &&
361                       !Style.BraceWrapping.SplitEmptyRecord)
362                  ? tryMergeSimpleBlock(I, E, Limit)
363                  : 0;
364     }
365     // Try to merge a function block with left brace wrapped
366     if (I[1]->First->is(TT_FunctionLBrace) &&
367         Style.BraceWrapping.AfterFunction) {
368       if (I[1]->Last->is(TT_LineComment))
369         return 0;
370 
371       // Check for Limit <= 2 to account for the " {".
372       if (Limit <= 2 || (Style.ColumnLimit == 0 && containsMustBreak(TheLine)))
373         return 0;
374       Limit -= 2;
375 
376       unsigned MergedLines = 0;
377       if (MergeShortFunctions ||
378           (Style.AllowShortFunctionsOnASingleLine >= FormatStyle::SFS_Empty &&
379            I[1]->First == I[1]->Last && I + 2 != E &&
380            I[2]->First->is(tok::r_brace))) {
381         MergedLines = tryMergeSimpleBlock(I + 1, E, Limit);
382         // If we managed to merge the block, count the function header, which is
383         // on a separate line.
384         if (MergedLines > 0)
385           ++MergedLines;
386       }
387       return MergedLines;
388     }
389     if (TheLine->First->is(tok::kw_if)) {
390       return Style.AllowShortIfStatementsOnASingleLine
391                  ? tryMergeSimpleControlStatement(I, E, Limit)
392                  : 0;
393     }
394     if (TheLine->First->isOneOf(tok::kw_for, tok::kw_while, tok::kw_do)) {
395       return Style.AllowShortLoopsOnASingleLine
396                  ? tryMergeSimpleControlStatement(I, E, Limit)
397                  : 0;
398     }
399     if (TheLine->First->isOneOf(tok::kw_case, tok::kw_default)) {
400       return Style.AllowShortCaseLabelsOnASingleLine
401                  ? tryMergeShortCaseLabels(I, E, Limit)
402                  : 0;
403     }
404     if (TheLine->InPPDirective &&
405         (TheLine->First->HasUnescapedNewline || TheLine->First->IsFirst)) {
406       return tryMergeSimplePPDirective(I, E, Limit);
407     }
408     return 0;
409   }
410 
411   unsigned
412   tryMergeSimplePPDirective(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
413                             SmallVectorImpl<AnnotatedLine *>::const_iterator E,
414                             unsigned Limit) {
415     if (Limit == 0)
416       return 0;
417     if (I + 2 != E && I[2]->InPPDirective && !I[2]->First->HasUnescapedNewline)
418       return 0;
419     if (1 + I[1]->Last->TotalLength > Limit)
420       return 0;
421     return 1;
422   }
423 
424   unsigned tryMergeSimpleControlStatement(
425       SmallVectorImpl<AnnotatedLine *>::const_iterator I,
426       SmallVectorImpl<AnnotatedLine *>::const_iterator E, unsigned Limit) {
427     if (Limit == 0)
428       return 0;
429     if (Style.BraceWrapping.AfterControlStatement ==
430             FormatStyle::BWACS_Always &&
431         I[1]->First->is(tok::l_brace) &&
432         Style.AllowShortBlocksOnASingleLine == FormatStyle::SBS_Never)
433       return 0;
434     if (I[1]->InPPDirective != (*I)->InPPDirective ||
435         (I[1]->InPPDirective && I[1]->First->HasUnescapedNewline))
436       return 0;
437     Limit = limitConsideringMacros(I + 1, E, Limit);
438     AnnotatedLine &Line = **I;
439     if (!Line.First->is(tok::kw_do) && Line.Last->isNot(tok::r_paren))
440       return 0;
441     // Only merge do while if do is the only statement on the line.
442     if (Line.First->is(tok::kw_do) && !Line.Last->is(tok::kw_do))
443       return 0;
444     if (1 + I[1]->Last->TotalLength > Limit)
445       return 0;
446     if (I[1]->First->isOneOf(tok::semi, tok::kw_if, tok::kw_for, tok::kw_while,
447                              TT_LineComment))
448       return 0;
449     // Only inline simple if's (no nested if or else), unless specified
450     if (Style.AllowShortIfStatementsOnASingleLine != FormatStyle::SIS_Always) {
451       if (I + 2 != E && Line.startsWith(tok::kw_if) &&
452           I[2]->First->is(tok::kw_else))
453         return 0;
454     }
455     return 1;
456   }
457 
458   unsigned
459   tryMergeShortCaseLabels(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
460                           SmallVectorImpl<AnnotatedLine *>::const_iterator E,
461                           unsigned Limit) {
462     if (Limit == 0 || I + 1 == E ||
463         I[1]->First->isOneOf(tok::kw_case, tok::kw_default))
464       return 0;
465     if (I[0]->Last->is(tok::l_brace) || I[1]->First->is(tok::l_brace))
466       return 0;
467     unsigned NumStmts = 0;
468     unsigned Length = 0;
469     bool EndsWithComment = false;
470     bool InPPDirective = I[0]->InPPDirective;
471     const unsigned Level = I[0]->Level;
472     for (; NumStmts < 3; ++NumStmts) {
473       if (I + 1 + NumStmts == E)
474         break;
475       const AnnotatedLine *Line = I[1 + NumStmts];
476       if (Line->InPPDirective != InPPDirective)
477         break;
478       if (Line->First->isOneOf(tok::kw_case, tok::kw_default, tok::r_brace))
479         break;
480       if (Line->First->isOneOf(tok::kw_if, tok::kw_for, tok::kw_switch,
481                                tok::kw_while) ||
482           EndsWithComment)
483         return 0;
484       if (Line->First->is(tok::comment)) {
485         if (Level != Line->Level)
486           return 0;
487         SmallVectorImpl<AnnotatedLine *>::const_iterator J = I + 2 + NumStmts;
488         for (; J != E; ++J) {
489           Line = *J;
490           if (Line->InPPDirective != InPPDirective)
491             break;
492           if (Line->First->isOneOf(tok::kw_case, tok::kw_default, tok::r_brace))
493             break;
494           if (Line->First->isNot(tok::comment) || Level != Line->Level)
495             return 0;
496         }
497         break;
498       }
499       if (Line->Last->is(tok::comment))
500         EndsWithComment = true;
501       Length += I[1 + NumStmts]->Last->TotalLength + 1; // 1 for the space.
502     }
503     if (NumStmts == 0 || NumStmts == 3 || Length > Limit)
504       return 0;
505     return NumStmts;
506   }
507 
508   unsigned
509   tryMergeSimpleBlock(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
510                       SmallVectorImpl<AnnotatedLine *>::const_iterator E,
511                       unsigned Limit) {
512     AnnotatedLine &Line = **I;
513 
514     // Don't merge ObjC @ keywords and methods.
515     // FIXME: If an option to allow short exception handling clauses on a single
516     // line is added, change this to not return for @try and friends.
517     if (Style.Language != FormatStyle::LK_Java &&
518         Line.First->isOneOf(tok::at, tok::minus, tok::plus))
519       return 0;
520 
521     // Check that the current line allows merging. This depends on whether we
522     // are in a control flow statements as well as several style flags.
523     if (Line.First->isOneOf(tok::kw_else, tok::kw_case) ||
524         (Line.First->Next && Line.First->Next->is(tok::kw_else)))
525       return 0;
526     // default: in switch statement
527     if (Line.First->is(tok::kw_default)) {
528       const FormatToken *Tok = Line.First->getNextNonComment();
529       if (Tok && Tok->is(tok::colon))
530         return 0;
531     }
532     if (Line.First->isOneOf(tok::kw_if, tok::kw_while, tok::kw_do, tok::kw_try,
533                             tok::kw___try, tok::kw_catch, tok::kw___finally,
534                             tok::kw_for, tok::r_brace, Keywords.kw___except)) {
535       if (Style.AllowShortBlocksOnASingleLine == FormatStyle::SBS_Never)
536         return 0;
537       // Don't merge when we can't except the case when
538       // the control statement block is empty
539       if (!Style.AllowShortIfStatementsOnASingleLine &&
540           Line.startsWith(tok::kw_if) &&
541           !Style.BraceWrapping.AfterControlStatement &&
542           !I[1]->First->is(tok::r_brace))
543         return 0;
544       if (!Style.AllowShortIfStatementsOnASingleLine &&
545           Line.startsWith(tok::kw_if) &&
546           Style.BraceWrapping.AfterControlStatement ==
547               FormatStyle::BWACS_Always &&
548           I + 2 != E && !I[2]->First->is(tok::r_brace))
549         return 0;
550       if (!Style.AllowShortLoopsOnASingleLine &&
551           Line.First->isOneOf(tok::kw_while, tok::kw_do, tok::kw_for) &&
552           !Style.BraceWrapping.AfterControlStatement &&
553           !I[1]->First->is(tok::r_brace))
554         return 0;
555       if (!Style.AllowShortLoopsOnASingleLine &&
556           Line.First->isOneOf(tok::kw_while, tok::kw_do, tok::kw_for) &&
557           Style.BraceWrapping.AfterControlStatement ==
558               FormatStyle::BWACS_Always &&
559           I + 2 != E && !I[2]->First->is(tok::r_brace))
560         return 0;
561       // FIXME: Consider an option to allow short exception handling clauses on
562       // a single line.
563       // FIXME: This isn't covered by tests.
564       // FIXME: For catch, __except, __finally the first token on the line
565       // is '}', so this isn't correct here.
566       if (Line.First->isOneOf(tok::kw_try, tok::kw___try, tok::kw_catch,
567                               Keywords.kw___except, tok::kw___finally))
568         return 0;
569     }
570 
571     if (Line.Last->is(tok::l_brace)) {
572       FormatToken *Tok = I[1]->First;
573       if (Tok->is(tok::r_brace) && !Tok->MustBreakBefore &&
574           (Tok->getNextNonComment() == nullptr ||
575            Tok->getNextNonComment()->is(tok::semi))) {
576         // We merge empty blocks even if the line exceeds the column limit.
577         Tok->SpacesRequiredBefore = Style.SpaceInEmptyBlock ? 1 : 0;
578         Tok->CanBreakBefore = true;
579         return 1;
580       } else if (Limit != 0 && !Line.startsWithNamespace() &&
581                  !startsExternCBlock(Line)) {
582         // We don't merge short records.
583         FormatToken *RecordTok = Line.First;
584         // Skip record modifiers.
585         while (RecordTok->Next &&
586                RecordTok->isOneOf(
587                    tok::kw_typedef, tok::kw_export, Keywords.kw_declare,
588                    Keywords.kw_abstract, tok::kw_default, tok::kw_public,
589                    tok::kw_private, tok::kw_protected, Keywords.kw_internal))
590           RecordTok = RecordTok->Next;
591         if (RecordTok &&
592             RecordTok->isOneOf(tok::kw_class, tok::kw_union, tok::kw_struct,
593                                Keywords.kw_interface))
594           return 0;
595 
596         // Check that we still have three lines and they fit into the limit.
597         if (I + 2 == E || I[2]->Type == LT_Invalid)
598           return 0;
599         Limit = limitConsideringMacros(I + 2, E, Limit);
600 
601         if (!nextTwoLinesFitInto(I, Limit))
602           return 0;
603 
604         // Second, check that the next line does not contain any braces - if it
605         // does, readability declines when putting it into a single line.
606         if (I[1]->Last->is(TT_LineComment))
607           return 0;
608         do {
609           if (Tok->is(tok::l_brace) && Tok->BlockKind != BK_BracedInit)
610             return 0;
611           Tok = Tok->Next;
612         } while (Tok);
613 
614         // Last, check that the third line starts with a closing brace.
615         Tok = I[2]->First;
616         if (Tok->isNot(tok::r_brace))
617           return 0;
618 
619         // Don't merge "if (a) { .. } else {".
620         if (Tok->Next && Tok->Next->is(tok::kw_else))
621           return 0;
622 
623         // Don't merge a trailing multi-line control statement block like:
624         // } else if (foo &&
625         //            bar)
626         // { <-- current Line
627         //   baz();
628         // }
629         if (Line.First == Line.Last &&
630             Style.BraceWrapping.AfterControlStatement ==
631                 FormatStyle::BWACS_MultiLine)
632           return 0;
633 
634         return 2;
635       }
636     } else if (I[1]->First->is(tok::l_brace)) {
637       if (I[1]->Last->is(TT_LineComment))
638         return 0;
639 
640       // Check for Limit <= 2 to account for the " {".
641       if (Limit <= 2 || (Style.ColumnLimit == 0 && containsMustBreak(*I)))
642         return 0;
643       Limit -= 2;
644       unsigned MergedLines = 0;
645       if (Style.AllowShortBlocksOnASingleLine != FormatStyle::SBS_Never ||
646           (I[1]->First == I[1]->Last && I + 2 != E &&
647            I[2]->First->is(tok::r_brace))) {
648         MergedLines = tryMergeSimpleBlock(I + 1, E, Limit);
649         // If we managed to merge the block, count the statement header, which
650         // is on a separate line.
651         if (MergedLines > 0)
652           ++MergedLines;
653       }
654       return MergedLines;
655     }
656     return 0;
657   }
658 
659   /// Returns the modified column limit for \p I if it is inside a macro and
660   /// needs a trailing '\'.
661   unsigned
662   limitConsideringMacros(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
663                          SmallVectorImpl<AnnotatedLine *>::const_iterator E,
664                          unsigned Limit) {
665     if (I[0]->InPPDirective && I + 1 != E &&
666         !I[1]->First->HasUnescapedNewline && !I[1]->First->is(tok::eof)) {
667       return Limit < 2 ? 0 : Limit - 2;
668     }
669     return Limit;
670   }
671 
672   bool nextTwoLinesFitInto(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
673                            unsigned Limit) {
674     if (I[1]->First->MustBreakBefore || I[2]->First->MustBreakBefore)
675       return false;
676     return 1 + I[1]->Last->TotalLength + 1 + I[2]->Last->TotalLength <= Limit;
677   }
678 
679   bool containsMustBreak(const AnnotatedLine *Line) {
680     for (const FormatToken *Tok = Line->First; Tok; Tok = Tok->Next) {
681       if (Tok->MustBreakBefore)
682         return true;
683     }
684     return false;
685   }
686 
687   void join(AnnotatedLine &A, const AnnotatedLine &B) {
688     assert(!A.Last->Next);
689     assert(!B.First->Previous);
690     if (B.Affected)
691       A.Affected = true;
692     A.Last->Next = B.First;
693     B.First->Previous = A.Last;
694     B.First->CanBreakBefore = true;
695     unsigned LengthA = A.Last->TotalLength + B.First->SpacesRequiredBefore;
696     for (FormatToken *Tok = B.First; Tok; Tok = Tok->Next) {
697       Tok->TotalLength += LengthA;
698       A.Last = Tok;
699     }
700   }
701 
702   const FormatStyle &Style;
703   const AdditionalKeywords &Keywords;
704   const SmallVectorImpl<AnnotatedLine *>::const_iterator End;
705 
706   SmallVectorImpl<AnnotatedLine *>::const_iterator Next;
707   const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines;
708 };
709 
710 static void markFinalized(FormatToken *Tok) {
711   for (; Tok; Tok = Tok->Next) {
712     Tok->Finalized = true;
713     for (AnnotatedLine *Child : Tok->Children)
714       markFinalized(Child->First);
715   }
716 }
717 
718 #ifndef NDEBUG
719 static void printLineState(const LineState &State) {
720   llvm::dbgs() << "State: ";
721   for (const ParenState &P : State.Stack) {
722     llvm::dbgs() << (P.Tok ? P.Tok->TokenText : "F") << "|" << P.Indent << "|"
723                  << P.LastSpace << "|" << P.NestedBlockIndent << " ";
724   }
725   llvm::dbgs() << State.NextToken->TokenText << "\n";
726 }
727 #endif
728 
729 /// Base class for classes that format one \c AnnotatedLine.
730 class LineFormatter {
731 public:
732   LineFormatter(ContinuationIndenter *Indenter, WhitespaceManager *Whitespaces,
733                 const FormatStyle &Style,
734                 UnwrappedLineFormatter *BlockFormatter)
735       : Indenter(Indenter), Whitespaces(Whitespaces), Style(Style),
736         BlockFormatter(BlockFormatter) {}
737   virtual ~LineFormatter() {}
738 
739   /// Formats an \c AnnotatedLine and returns the penalty.
740   ///
741   /// If \p DryRun is \c false, directly applies the changes.
742   virtual unsigned formatLine(const AnnotatedLine &Line, unsigned FirstIndent,
743                               unsigned FirstStartColumn, bool DryRun) = 0;
744 
745 protected:
746   /// If the \p State's next token is an r_brace closing a nested block,
747   /// format the nested block before it.
748   ///
749   /// Returns \c true if all children could be placed successfully and adapts
750   /// \p Penalty as well as \p State. If \p DryRun is false, also directly
751   /// creates changes using \c Whitespaces.
752   ///
753   /// The crucial idea here is that children always get formatted upon
754   /// encountering the closing brace right after the nested block. Now, if we
755   /// are currently trying to keep the "}" on the same line (i.e. \p NewLine is
756   /// \c false), the entire block has to be kept on the same line (which is only
757   /// possible if it fits on the line, only contains a single statement, etc.
758   ///
759   /// If \p NewLine is true, we format the nested block on separate lines, i.e.
760   /// break after the "{", format all lines with correct indentation and the put
761   /// the closing "}" on yet another new line.
762   ///
763   /// This enables us to keep the simple structure of the
764   /// \c UnwrappedLineFormatter, where we only have two options for each token:
765   /// break or don't break.
766   bool formatChildren(LineState &State, bool NewLine, bool DryRun,
767                       unsigned &Penalty) {
768     const FormatToken *LBrace = State.NextToken->getPreviousNonComment();
769     FormatToken &Previous = *State.NextToken->Previous;
770     if (!LBrace || LBrace->isNot(tok::l_brace) ||
771         LBrace->BlockKind != BK_Block || Previous.Children.size() == 0)
772       // The previous token does not open a block. Nothing to do. We don't
773       // assert so that we can simply call this function for all tokens.
774       return true;
775 
776     if (NewLine) {
777       int AdditionalIndent = State.Stack.back().Indent -
778                              Previous.Children[0]->Level * Style.IndentWidth;
779 
780       Penalty +=
781           BlockFormatter->format(Previous.Children, DryRun, AdditionalIndent,
782                                  /*FixBadIndentation=*/true);
783       return true;
784     }
785 
786     if (Previous.Children[0]->First->MustBreakBefore)
787       return false;
788 
789     // Cannot merge into one line if this line ends on a comment.
790     if (Previous.is(tok::comment))
791       return false;
792 
793     // Cannot merge multiple statements into a single line.
794     if (Previous.Children.size() > 1)
795       return false;
796 
797     const AnnotatedLine *Child = Previous.Children[0];
798     // We can't put the closing "}" on a line with a trailing comment.
799     if (Child->Last->isTrailingComment())
800       return false;
801 
802     // If the child line exceeds the column limit, we wouldn't want to merge it.
803     // We add +2 for the trailing " }".
804     if (Style.ColumnLimit > 0 &&
805         Child->Last->TotalLength + State.Column + 2 > Style.ColumnLimit)
806       return false;
807 
808     if (!DryRun) {
809       Whitespaces->replaceWhitespace(
810           *Child->First, /*Newlines=*/0, /*Spaces=*/1,
811           /*StartOfTokenColumn=*/State.Column, /*IsAligned=*/false,
812           State.Line->InPPDirective);
813     }
814     Penalty +=
815         formatLine(*Child, State.Column + 1, /*FirstStartColumn=*/0, DryRun);
816 
817     State.Column += 1 + Child->Last->TotalLength;
818     return true;
819   }
820 
821   ContinuationIndenter *Indenter;
822 
823 private:
824   WhitespaceManager *Whitespaces;
825   const FormatStyle &Style;
826   UnwrappedLineFormatter *BlockFormatter;
827 };
828 
829 /// Formatter that keeps the existing line breaks.
830 class NoColumnLimitLineFormatter : public LineFormatter {
831 public:
832   NoColumnLimitLineFormatter(ContinuationIndenter *Indenter,
833                              WhitespaceManager *Whitespaces,
834                              const FormatStyle &Style,
835                              UnwrappedLineFormatter *BlockFormatter)
836       : LineFormatter(Indenter, Whitespaces, Style, BlockFormatter) {}
837 
838   /// Formats the line, simply keeping all of the input's line breaking
839   /// decisions.
840   unsigned formatLine(const AnnotatedLine &Line, unsigned FirstIndent,
841                       unsigned FirstStartColumn, bool DryRun) override {
842     assert(!DryRun);
843     LineState State = Indenter->getInitialState(FirstIndent, FirstStartColumn,
844                                                 &Line, /*DryRun=*/false);
845     while (State.NextToken) {
846       bool Newline =
847           Indenter->mustBreak(State) ||
848           (Indenter->canBreak(State) && State.NextToken->NewlinesBefore > 0);
849       unsigned Penalty = 0;
850       formatChildren(State, Newline, /*DryRun=*/false, Penalty);
851       Indenter->addTokenToState(State, Newline, /*DryRun=*/false);
852     }
853     return 0;
854   }
855 };
856 
857 /// Formatter that puts all tokens into a single line without breaks.
858 class NoLineBreakFormatter : public LineFormatter {
859 public:
860   NoLineBreakFormatter(ContinuationIndenter *Indenter,
861                        WhitespaceManager *Whitespaces, const FormatStyle &Style,
862                        UnwrappedLineFormatter *BlockFormatter)
863       : LineFormatter(Indenter, Whitespaces, Style, BlockFormatter) {}
864 
865   /// Puts all tokens into a single line.
866   unsigned formatLine(const AnnotatedLine &Line, unsigned FirstIndent,
867                       unsigned FirstStartColumn, bool DryRun) override {
868     unsigned Penalty = 0;
869     LineState State =
870         Indenter->getInitialState(FirstIndent, FirstStartColumn, &Line, DryRun);
871     while (State.NextToken) {
872       formatChildren(State, /*NewLine=*/false, DryRun, Penalty);
873       Indenter->addTokenToState(
874           State, /*Newline=*/State.NextToken->MustBreakBefore, DryRun);
875     }
876     return Penalty;
877   }
878 };
879 
880 /// Finds the best way to break lines.
881 class OptimizingLineFormatter : public LineFormatter {
882 public:
883   OptimizingLineFormatter(ContinuationIndenter *Indenter,
884                           WhitespaceManager *Whitespaces,
885                           const FormatStyle &Style,
886                           UnwrappedLineFormatter *BlockFormatter)
887       : LineFormatter(Indenter, Whitespaces, Style, BlockFormatter) {}
888 
889   /// Formats the line by finding the best line breaks with line lengths
890   /// below the column limit.
891   unsigned formatLine(const AnnotatedLine &Line, unsigned FirstIndent,
892                       unsigned FirstStartColumn, bool DryRun) override {
893     LineState State =
894         Indenter->getInitialState(FirstIndent, FirstStartColumn, &Line, DryRun);
895 
896     // If the ObjC method declaration does not fit on a line, we should format
897     // it with one arg per line.
898     if (State.Line->Type == LT_ObjCMethodDecl)
899       State.Stack.back().BreakBeforeParameter = true;
900 
901     // Find best solution in solution space.
902     return analyzeSolutionSpace(State, DryRun);
903   }
904 
905 private:
906   struct CompareLineStatePointers {
907     bool operator()(LineState *obj1, LineState *obj2) const {
908       return *obj1 < *obj2;
909     }
910   };
911 
912   /// A pair of <penalty, count> that is used to prioritize the BFS on.
913   ///
914   /// In case of equal penalties, we want to prefer states that were inserted
915   /// first. During state generation we make sure that we insert states first
916   /// that break the line as late as possible.
917   typedef std::pair<unsigned, unsigned> OrderedPenalty;
918 
919   /// An edge in the solution space from \c Previous->State to \c State,
920   /// inserting a newline dependent on the \c NewLine.
921   struct StateNode {
922     StateNode(const LineState &State, bool NewLine, StateNode *Previous)
923         : State(State), NewLine(NewLine), Previous(Previous) {}
924     LineState State;
925     bool NewLine;
926     StateNode *Previous;
927   };
928 
929   /// An item in the prioritized BFS search queue. The \c StateNode's
930   /// \c State has the given \c OrderedPenalty.
931   typedef std::pair<OrderedPenalty, StateNode *> QueueItem;
932 
933   /// The BFS queue type.
934   typedef std::priority_queue<QueueItem, std::vector<QueueItem>,
935                               std::greater<QueueItem>>
936       QueueType;
937 
938   /// Analyze the entire solution space starting from \p InitialState.
939   ///
940   /// This implements a variant of Dijkstra's algorithm on the graph that spans
941   /// the solution space (\c LineStates are the nodes). The algorithm tries to
942   /// find the shortest path (the one with lowest penalty) from \p InitialState
943   /// to a state where all tokens are placed. Returns the penalty.
944   ///
945   /// If \p DryRun is \c false, directly applies the changes.
946   unsigned analyzeSolutionSpace(LineState &InitialState, bool DryRun) {
947     std::set<LineState *, CompareLineStatePointers> Seen;
948 
949     // Increasing count of \c StateNode items we have created. This is used to
950     // create a deterministic order independent of the container.
951     unsigned Count = 0;
952     QueueType Queue;
953 
954     // Insert start element into queue.
955     StateNode *Node =
956         new (Allocator.Allocate()) StateNode(InitialState, false, nullptr);
957     Queue.push(QueueItem(OrderedPenalty(0, Count), Node));
958     ++Count;
959 
960     unsigned Penalty = 0;
961 
962     // While not empty, take first element and follow edges.
963     while (!Queue.empty()) {
964       Penalty = Queue.top().first.first;
965       StateNode *Node = Queue.top().second;
966       if (!Node->State.NextToken) {
967         LLVM_DEBUG(llvm::dbgs()
968                    << "\n---\nPenalty for line: " << Penalty << "\n");
969         break;
970       }
971       Queue.pop();
972 
973       // Cut off the analysis of certain solutions if the analysis gets too
974       // complex. See description of IgnoreStackForComparison.
975       if (Count > 50000)
976         Node->State.IgnoreStackForComparison = true;
977 
978       if (!Seen.insert(&Node->State).second)
979         // State already examined with lower penalty.
980         continue;
981 
982       FormatDecision LastFormat = Node->State.NextToken->Decision;
983       if (LastFormat == FD_Unformatted || LastFormat == FD_Continue)
984         addNextStateToQueue(Penalty, Node, /*NewLine=*/false, &Count, &Queue);
985       if (LastFormat == FD_Unformatted || LastFormat == FD_Break)
986         addNextStateToQueue(Penalty, Node, /*NewLine=*/true, &Count, &Queue);
987     }
988 
989     if (Queue.empty()) {
990       // We were unable to find a solution, do nothing.
991       // FIXME: Add diagnostic?
992       LLVM_DEBUG(llvm::dbgs() << "Could not find a solution.\n");
993       return 0;
994     }
995 
996     // Reconstruct the solution.
997     if (!DryRun)
998       reconstructPath(InitialState, Queue.top().second);
999 
1000     LLVM_DEBUG(llvm::dbgs()
1001                << "Total number of analyzed states: " << Count << "\n");
1002     LLVM_DEBUG(llvm::dbgs() << "---\n");
1003 
1004     return Penalty;
1005   }
1006 
1007   /// Add the following state to the analysis queue \c Queue.
1008   ///
1009   /// Assume the current state is \p PreviousNode and has been reached with a
1010   /// penalty of \p Penalty. Insert a line break if \p NewLine is \c true.
1011   void addNextStateToQueue(unsigned Penalty, StateNode *PreviousNode,
1012                            bool NewLine, unsigned *Count, QueueType *Queue) {
1013     if (NewLine && !Indenter->canBreak(PreviousNode->State))
1014       return;
1015     if (!NewLine && Indenter->mustBreak(PreviousNode->State))
1016       return;
1017 
1018     StateNode *Node = new (Allocator.Allocate())
1019         StateNode(PreviousNode->State, NewLine, PreviousNode);
1020     if (!formatChildren(Node->State, NewLine, /*DryRun=*/true, Penalty))
1021       return;
1022 
1023     Penalty += Indenter->addTokenToState(Node->State, NewLine, true);
1024 
1025     Queue->push(QueueItem(OrderedPenalty(Penalty, *Count), Node));
1026     ++(*Count);
1027   }
1028 
1029   /// Applies the best formatting by reconstructing the path in the
1030   /// solution space that leads to \c Best.
1031   void reconstructPath(LineState &State, StateNode *Best) {
1032     std::deque<StateNode *> Path;
1033     // We do not need a break before the initial token.
1034     while (Best->Previous) {
1035       Path.push_front(Best);
1036       Best = Best->Previous;
1037     }
1038     for (auto I = Path.begin(), E = Path.end(); I != E; ++I) {
1039       unsigned Penalty = 0;
1040       formatChildren(State, (*I)->NewLine, /*DryRun=*/false, Penalty);
1041       Penalty += Indenter->addTokenToState(State, (*I)->NewLine, false);
1042 
1043       LLVM_DEBUG({
1044         printLineState((*I)->Previous->State);
1045         if ((*I)->NewLine) {
1046           llvm::dbgs() << "Penalty for placing "
1047                        << (*I)->Previous->State.NextToken->Tok.getName()
1048                        << " on a new line: " << Penalty << "\n";
1049         }
1050       });
1051     }
1052   }
1053 
1054   llvm::SpecificBumpPtrAllocator<StateNode> Allocator;
1055 };
1056 
1057 } // anonymous namespace
1058 
1059 unsigned UnwrappedLineFormatter::format(
1060     const SmallVectorImpl<AnnotatedLine *> &Lines, bool DryRun,
1061     int AdditionalIndent, bool FixBadIndentation, unsigned FirstStartColumn,
1062     unsigned NextStartColumn, unsigned LastStartColumn) {
1063   LineJoiner Joiner(Style, Keywords, Lines);
1064 
1065   // Try to look up already computed penalty in DryRun-mode.
1066   std::pair<const SmallVectorImpl<AnnotatedLine *> *, unsigned> CacheKey(
1067       &Lines, AdditionalIndent);
1068   auto CacheIt = PenaltyCache.find(CacheKey);
1069   if (DryRun && CacheIt != PenaltyCache.end())
1070     return CacheIt->second;
1071 
1072   assert(!Lines.empty());
1073   unsigned Penalty = 0;
1074   LevelIndentTracker IndentTracker(Style, Keywords, Lines[0]->Level,
1075                                    AdditionalIndent);
1076   const AnnotatedLine *PreviousLine = nullptr;
1077   const AnnotatedLine *NextLine = nullptr;
1078 
1079   // The minimum level of consecutive lines that have been formatted.
1080   unsigned RangeMinLevel = UINT_MAX;
1081 
1082   bool FirstLine = true;
1083   for (const AnnotatedLine *Line =
1084            Joiner.getNextMergedLine(DryRun, IndentTracker);
1085        Line; Line = NextLine, FirstLine = false) {
1086     const AnnotatedLine &TheLine = *Line;
1087     unsigned Indent = IndentTracker.getIndent();
1088 
1089     // We continue formatting unchanged lines to adjust their indent, e.g. if a
1090     // scope was added. However, we need to carefully stop doing this when we
1091     // exit the scope of affected lines to prevent indenting a the entire
1092     // remaining file if it currently missing a closing brace.
1093     bool PreviousRBrace =
1094         PreviousLine && PreviousLine->startsWith(tok::r_brace);
1095     bool ContinueFormatting =
1096         TheLine.Level > RangeMinLevel ||
1097         (TheLine.Level == RangeMinLevel && !PreviousRBrace &&
1098          !TheLine.startsWith(tok::r_brace));
1099 
1100     bool FixIndentation = (FixBadIndentation || ContinueFormatting) &&
1101                           Indent != TheLine.First->OriginalColumn;
1102     bool ShouldFormat = TheLine.Affected || FixIndentation;
1103     // We cannot format this line; if the reason is that the line had a
1104     // parsing error, remember that.
1105     if (ShouldFormat && TheLine.Type == LT_Invalid && Status) {
1106       Status->FormatComplete = false;
1107       Status->Line =
1108           SourceMgr.getSpellingLineNumber(TheLine.First->Tok.getLocation());
1109     }
1110 
1111     if (ShouldFormat && TheLine.Type != LT_Invalid) {
1112       if (!DryRun) {
1113         bool LastLine = Line->First->is(tok::eof);
1114         formatFirstToken(TheLine, PreviousLine, Lines, Indent,
1115                          LastLine ? LastStartColumn : NextStartColumn + Indent);
1116       }
1117 
1118       NextLine = Joiner.getNextMergedLine(DryRun, IndentTracker);
1119       unsigned ColumnLimit = getColumnLimit(TheLine.InPPDirective, NextLine);
1120       bool FitsIntoOneLine =
1121           TheLine.Last->TotalLength + Indent <= ColumnLimit ||
1122           (TheLine.Type == LT_ImportStatement &&
1123            (Style.Language != FormatStyle::LK_JavaScript ||
1124             !Style.JavaScriptWrapImports)) ||
1125           (Style.isCSharp() &&
1126            TheLine.InPPDirective); // don't split #regions in C#
1127       if (Style.ColumnLimit == 0)
1128         NoColumnLimitLineFormatter(Indenter, Whitespaces, Style, this)
1129             .formatLine(TheLine, NextStartColumn + Indent,
1130                         FirstLine ? FirstStartColumn : 0, DryRun);
1131       else if (FitsIntoOneLine)
1132         Penalty += NoLineBreakFormatter(Indenter, Whitespaces, Style, this)
1133                        .formatLine(TheLine, NextStartColumn + Indent,
1134                                    FirstLine ? FirstStartColumn : 0, DryRun);
1135       else
1136         Penalty += OptimizingLineFormatter(Indenter, Whitespaces, Style, this)
1137                        .formatLine(TheLine, NextStartColumn + Indent,
1138                                    FirstLine ? FirstStartColumn : 0, DryRun);
1139       RangeMinLevel = std::min(RangeMinLevel, TheLine.Level);
1140     } else {
1141       // If no token in the current line is affected, we still need to format
1142       // affected children.
1143       if (TheLine.ChildrenAffected)
1144         for (const FormatToken *Tok = TheLine.First; Tok; Tok = Tok->Next)
1145           if (!Tok->Children.empty())
1146             format(Tok->Children, DryRun);
1147 
1148       // Adapt following lines on the current indent level to the same level
1149       // unless the current \c AnnotatedLine is not at the beginning of a line.
1150       bool StartsNewLine =
1151           TheLine.First->NewlinesBefore > 0 || TheLine.First->IsFirst;
1152       if (StartsNewLine)
1153         IndentTracker.adjustToUnmodifiedLine(TheLine);
1154       if (!DryRun) {
1155         bool ReformatLeadingWhitespace =
1156             StartsNewLine && ((PreviousLine && PreviousLine->Affected) ||
1157                               TheLine.LeadingEmptyLinesAffected);
1158         // Format the first token.
1159         if (ReformatLeadingWhitespace)
1160           formatFirstToken(TheLine, PreviousLine, Lines,
1161                            TheLine.First->OriginalColumn,
1162                            TheLine.First->OriginalColumn);
1163         else
1164           Whitespaces->addUntouchableToken(*TheLine.First,
1165                                            TheLine.InPPDirective);
1166 
1167         // Notify the WhitespaceManager about the unchanged whitespace.
1168         for (FormatToken *Tok = TheLine.First->Next; Tok; Tok = Tok->Next)
1169           Whitespaces->addUntouchableToken(*Tok, TheLine.InPPDirective);
1170       }
1171       NextLine = Joiner.getNextMergedLine(DryRun, IndentTracker);
1172       RangeMinLevel = UINT_MAX;
1173     }
1174     if (!DryRun)
1175       markFinalized(TheLine.First);
1176     PreviousLine = &TheLine;
1177   }
1178   PenaltyCache[CacheKey] = Penalty;
1179   return Penalty;
1180 }
1181 
1182 void UnwrappedLineFormatter::formatFirstToken(
1183     const AnnotatedLine &Line, const AnnotatedLine *PreviousLine,
1184     const SmallVectorImpl<AnnotatedLine *> &Lines, unsigned Indent,
1185     unsigned NewlineIndent) {
1186   FormatToken &RootToken = *Line.First;
1187   if (RootToken.is(tok::eof)) {
1188     unsigned Newlines = std::min(RootToken.NewlinesBefore, 1u);
1189     unsigned TokenIndent = Newlines ? NewlineIndent : 0;
1190     Whitespaces->replaceWhitespace(RootToken, Newlines, TokenIndent,
1191                                    TokenIndent);
1192     return;
1193   }
1194   unsigned Newlines =
1195       std::min(RootToken.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1);
1196   // Remove empty lines before "}" where applicable.
1197   if (RootToken.is(tok::r_brace) &&
1198       (!RootToken.Next ||
1199        (RootToken.Next->is(tok::semi) && !RootToken.Next->Next)) &&
1200       // Do not remove empty lines before namespace closing "}".
1201       !getNamespaceToken(&Line, Lines))
1202     Newlines = std::min(Newlines, 1u);
1203   // Remove empty lines at the start of nested blocks (lambdas/arrow functions)
1204   if (PreviousLine == nullptr && Line.Level > 0)
1205     Newlines = std::min(Newlines, 1u);
1206   if (Newlines == 0 && !RootToken.IsFirst)
1207     Newlines = 1;
1208   if (RootToken.IsFirst && !RootToken.HasUnescapedNewline)
1209     Newlines = 0;
1210 
1211   // Remove empty lines after "{".
1212   if (!Style.KeepEmptyLinesAtTheStartOfBlocks && PreviousLine &&
1213       PreviousLine->Last->is(tok::l_brace) &&
1214       !PreviousLine->startsWithNamespace() &&
1215       !startsExternCBlock(*PreviousLine))
1216     Newlines = 1;
1217 
1218   // Insert extra new line before access specifiers.
1219   if (PreviousLine && PreviousLine->Last->isOneOf(tok::semi, tok::r_brace) &&
1220       RootToken.isAccessSpecifier() && RootToken.NewlinesBefore == 1)
1221     ++Newlines;
1222 
1223   // Remove empty lines after access specifiers.
1224   if (PreviousLine && PreviousLine->First->isAccessSpecifier() &&
1225       (!PreviousLine->InPPDirective || !RootToken.HasUnescapedNewline))
1226     Newlines = std::min(1u, Newlines);
1227 
1228   if (Newlines)
1229     Indent = NewlineIndent;
1230 
1231   // If in Whitemsmiths mode, indent start and end of blocks
1232   if (Style.BreakBeforeBraces == FormatStyle::BS_Whitesmiths) {
1233     if (RootToken.isOneOf(tok::l_brace, tok::r_brace, tok::kw_case,
1234                           tok::kw_default))
1235       Indent += Style.IndentWidth;
1236   }
1237 
1238   // Preprocessor directives get indented before the hash only if specified
1239   if (Style.IndentPPDirectives != FormatStyle::PPDIS_BeforeHash &&
1240       (Line.Type == LT_PreprocessorDirective ||
1241        Line.Type == LT_ImportStatement))
1242     Indent = 0;
1243 
1244   Whitespaces->replaceWhitespace(RootToken, Newlines, Indent, Indent,
1245                                  /*IsAligned=*/false,
1246                                  Line.InPPDirective &&
1247                                      !RootToken.HasUnescapedNewline);
1248 }
1249 
1250 unsigned
1251 UnwrappedLineFormatter::getColumnLimit(bool InPPDirective,
1252                                        const AnnotatedLine *NextLine) const {
1253   // In preprocessor directives reserve two chars for trailing " \" if the
1254   // next line continues the preprocessor directive.
1255   bool ContinuesPPDirective =
1256       InPPDirective &&
1257       // If there is no next line, this is likely a child line and the parent
1258       // continues the preprocessor directive.
1259       (!NextLine ||
1260        (NextLine->InPPDirective &&
1261         // If there is an unescaped newline between this line and the next, the
1262         // next line starts a new preprocessor directive.
1263         !NextLine->First->HasUnescapedNewline));
1264   return Style.ColumnLimit - (ContinuesPPDirective ? 2 : 0);
1265 }
1266 
1267 } // namespace format
1268 } // namespace clang
1269