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