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