xref: /openbsd-src/gnu/llvm/clang/lib/Format/ContinuationIndenter.cpp (revision 12c855180aad702bbcca06e0398d774beeafb155)
1e5dd7070Spatrick //===--- ContinuationIndenter.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 /// \file
10e5dd7070Spatrick /// This file implements the continuation indenter.
11e5dd7070Spatrick ///
12e5dd7070Spatrick //===----------------------------------------------------------------------===//
13e5dd7070Spatrick 
14e5dd7070Spatrick #include "ContinuationIndenter.h"
15e5dd7070Spatrick #include "BreakableToken.h"
16e5dd7070Spatrick #include "FormatInternal.h"
17*12c85518Srobert #include "FormatToken.h"
18e5dd7070Spatrick #include "WhitespaceManager.h"
19e5dd7070Spatrick #include "clang/Basic/OperatorPrecedence.h"
20e5dd7070Spatrick #include "clang/Basic/SourceManager.h"
21e5dd7070Spatrick #include "clang/Format/Format.h"
22*12c85518Srobert #include "llvm/ADT/StringSet.h"
23e5dd7070Spatrick #include "llvm/Support/Debug.h"
24*12c85518Srobert #include <optional>
25e5dd7070Spatrick 
26e5dd7070Spatrick #define DEBUG_TYPE "format-indenter"
27e5dd7070Spatrick 
28e5dd7070Spatrick namespace clang {
29e5dd7070Spatrick namespace format {
30e5dd7070Spatrick 
31e5dd7070Spatrick // Returns true if a TT_SelectorName should be indented when wrapped,
32e5dd7070Spatrick // false otherwise.
shouldIndentWrappedSelectorName(const FormatStyle & Style,LineType LineType)33e5dd7070Spatrick static bool shouldIndentWrappedSelectorName(const FormatStyle &Style,
34e5dd7070Spatrick                                             LineType LineType) {
35e5dd7070Spatrick   return Style.IndentWrappedFunctionNames || LineType == LT_ObjCMethodDecl;
36e5dd7070Spatrick }
37e5dd7070Spatrick 
38e5dd7070Spatrick // Returns the length of everything up to the first possible line break after
39e5dd7070Spatrick // the ), ], } or > matching \c Tok.
getLengthToMatchingParen(const FormatToken & Tok,ArrayRef<ParenState> Stack)40e5dd7070Spatrick static unsigned getLengthToMatchingParen(const FormatToken &Tok,
41*12c85518Srobert                                          ArrayRef<ParenState> Stack) {
42e5dd7070Spatrick   // Normally whether or not a break before T is possible is calculated and
43e5dd7070Spatrick   // stored in T.CanBreakBefore. Braces, array initializers and text proto
44e5dd7070Spatrick   // messages like `key: < ... >` are an exception: a break is possible
45e5dd7070Spatrick   // before a closing brace R if a break was inserted after the corresponding
46e5dd7070Spatrick   // opening brace. The information about whether or not a break is needed
47e5dd7070Spatrick   // before a closing brace R is stored in the ParenState field
48e5dd7070Spatrick   // S.BreakBeforeClosingBrace where S is the state that R closes.
49e5dd7070Spatrick   //
50e5dd7070Spatrick   // In order to decide whether there can be a break before encountered right
51e5dd7070Spatrick   // braces, this implementation iterates over the sequence of tokens and over
52e5dd7070Spatrick   // the paren stack in lockstep, keeping track of the stack level which visited
53e5dd7070Spatrick   // right braces correspond to in MatchingStackIndex.
54e5dd7070Spatrick   //
55e5dd7070Spatrick   // For example, consider:
56e5dd7070Spatrick   // L. <- line number
57e5dd7070Spatrick   // 1. {
58e5dd7070Spatrick   // 2. {1},
59e5dd7070Spatrick   // 3. {2},
60e5dd7070Spatrick   // 4. {{3}}}
61e5dd7070Spatrick   //     ^ where we call this method with this token.
62e5dd7070Spatrick   // The paren stack at this point contains 3 brace levels:
63e5dd7070Spatrick   //  0. { at line 1, BreakBeforeClosingBrace: true
64e5dd7070Spatrick   //  1. first { at line 4, BreakBeforeClosingBrace: false
65e5dd7070Spatrick   //  2. second { at line 4, BreakBeforeClosingBrace: false,
66e5dd7070Spatrick   //  where there might be fake parens levels in-between these levels.
67e5dd7070Spatrick   // The algorithm will start at the first } on line 4, which is the matching
68e5dd7070Spatrick   // brace of the initial left brace and at level 2 of the stack. Then,
69e5dd7070Spatrick   // examining BreakBeforeClosingBrace: false at level 2, it will continue to
70e5dd7070Spatrick   // the second } on line 4, and will traverse the stack downwards until it
71e5dd7070Spatrick   // finds the matching { on level 1. Then, examining BreakBeforeClosingBrace:
72e5dd7070Spatrick   // false at level 1, it will continue to the third } on line 4 and will
73e5dd7070Spatrick   // traverse the stack downwards until it finds the matching { on level 0.
74e5dd7070Spatrick   // Then, examining BreakBeforeClosingBrace: true at level 0, the algorithm
75e5dd7070Spatrick   // will stop and will use the second } on line 4 to determine the length to
76e5dd7070Spatrick   // return, as in this example the range will include the tokens: {3}}
77e5dd7070Spatrick   //
78e5dd7070Spatrick   // The algorithm will only traverse the stack if it encounters braces, array
79e5dd7070Spatrick   // initializer squares or text proto angle brackets.
80e5dd7070Spatrick   if (!Tok.MatchingParen)
81e5dd7070Spatrick     return 0;
82e5dd7070Spatrick   FormatToken *End = Tok.MatchingParen;
83e5dd7070Spatrick   // Maintains a stack level corresponding to the current End token.
84e5dd7070Spatrick   int MatchingStackIndex = Stack.size() - 1;
85e5dd7070Spatrick   // Traverses the stack downwards, looking for the level to which LBrace
86e5dd7070Spatrick   // corresponds. Returns either a pointer to the matching level or nullptr if
87e5dd7070Spatrick   // LParen is not found in the initial portion of the stack up to
88e5dd7070Spatrick   // MatchingStackIndex.
89e5dd7070Spatrick   auto FindParenState = [&](const FormatToken *LBrace) -> const ParenState * {
90e5dd7070Spatrick     while (MatchingStackIndex >= 0 && Stack[MatchingStackIndex].Tok != LBrace)
91e5dd7070Spatrick       --MatchingStackIndex;
92e5dd7070Spatrick     return MatchingStackIndex >= 0 ? &Stack[MatchingStackIndex] : nullptr;
93e5dd7070Spatrick   };
94e5dd7070Spatrick   for (; End->Next; End = End->Next) {
95e5dd7070Spatrick     if (End->Next->CanBreakBefore)
96e5dd7070Spatrick       break;
97e5dd7070Spatrick     if (!End->Next->closesScope())
98e5dd7070Spatrick       continue;
99e5dd7070Spatrick     if (End->Next->MatchingParen &&
100e5dd7070Spatrick         End->Next->MatchingParen->isOneOf(
101e5dd7070Spatrick             tok::l_brace, TT_ArrayInitializerLSquare, tok::less)) {
102e5dd7070Spatrick       const ParenState *State = FindParenState(End->Next->MatchingParen);
103e5dd7070Spatrick       if (State && State->BreakBeforeClosingBrace)
104e5dd7070Spatrick         break;
105e5dd7070Spatrick     }
106e5dd7070Spatrick   }
107e5dd7070Spatrick   return End->TotalLength - Tok.TotalLength + 1;
108e5dd7070Spatrick }
109e5dd7070Spatrick 
getLengthToNextOperator(const FormatToken & Tok)110e5dd7070Spatrick static unsigned getLengthToNextOperator(const FormatToken &Tok) {
111e5dd7070Spatrick   if (!Tok.NextOperator)
112e5dd7070Spatrick     return 0;
113e5dd7070Spatrick   return Tok.NextOperator->TotalLength - Tok.TotalLength;
114e5dd7070Spatrick }
115e5dd7070Spatrick 
116e5dd7070Spatrick // Returns \c true if \c Tok is the "." or "->" of a call and starts the next
117e5dd7070Spatrick // segment of a builder type call.
startsSegmentOfBuilderTypeCall(const FormatToken & Tok)118e5dd7070Spatrick static bool startsSegmentOfBuilderTypeCall(const FormatToken &Tok) {
119e5dd7070Spatrick   return Tok.isMemberAccess() && Tok.Previous && Tok.Previous->closesScope();
120e5dd7070Spatrick }
121e5dd7070Spatrick 
122e5dd7070Spatrick // Returns \c true if \c Current starts a new parameter.
startsNextParameter(const FormatToken & Current,const FormatStyle & Style)123e5dd7070Spatrick static bool startsNextParameter(const FormatToken &Current,
124e5dd7070Spatrick                                 const FormatStyle &Style) {
125e5dd7070Spatrick   const FormatToken &Previous = *Current.Previous;
126e5dd7070Spatrick   if (Current.is(TT_CtorInitializerComma) &&
127*12c85518Srobert       Style.BreakConstructorInitializers == FormatStyle::BCIS_BeforeComma) {
128e5dd7070Spatrick     return true;
129*12c85518Srobert   }
130e5dd7070Spatrick   if (Style.Language == FormatStyle::LK_Proto && Current.is(TT_SelectorName))
131e5dd7070Spatrick     return true;
132e5dd7070Spatrick   return Previous.is(tok::comma) && !Current.isTrailingComment() &&
133e5dd7070Spatrick          ((Previous.isNot(TT_CtorInitializerComma) ||
134e5dd7070Spatrick            Style.BreakConstructorInitializers !=
135e5dd7070Spatrick                FormatStyle::BCIS_BeforeComma) &&
136e5dd7070Spatrick           (Previous.isNot(TT_InheritanceComma) ||
137e5dd7070Spatrick            Style.BreakInheritanceList != FormatStyle::BILS_BeforeComma));
138e5dd7070Spatrick }
139e5dd7070Spatrick 
opensProtoMessageField(const FormatToken & LessTok,const FormatStyle & Style)140e5dd7070Spatrick static bool opensProtoMessageField(const FormatToken &LessTok,
141e5dd7070Spatrick                                    const FormatStyle &Style) {
142e5dd7070Spatrick   if (LessTok.isNot(tok::less))
143e5dd7070Spatrick     return false;
144e5dd7070Spatrick   return Style.Language == FormatStyle::LK_TextProto ||
145e5dd7070Spatrick          (Style.Language == FormatStyle::LK_Proto &&
146e5dd7070Spatrick           (LessTok.NestingLevel > 0 ||
147e5dd7070Spatrick            (LessTok.Previous && LessTok.Previous->is(tok::equal))));
148e5dd7070Spatrick }
149e5dd7070Spatrick 
150*12c85518Srobert // Returns the delimiter of a raw string literal, or std::nullopt if TokenText
151*12c85518Srobert // is not the text of a raw string literal. The delimiter could be the empty
152*12c85518Srobert // string.  For example, the delimiter of R"deli(cont)deli" is deli.
getRawStringDelimiter(StringRef TokenText)153*12c85518Srobert static std::optional<StringRef> getRawStringDelimiter(StringRef TokenText) {
154e5dd7070Spatrick   if (TokenText.size() < 5 // The smallest raw string possible is 'R"()"'.
155*12c85518Srobert       || !TokenText.startswith("R\"") || !TokenText.endswith("\"")) {
156*12c85518Srobert     return std::nullopt;
157*12c85518Srobert   }
158e5dd7070Spatrick 
159e5dd7070Spatrick   // A raw string starts with 'R"<delimiter>(' and delimiter is ascii and has
160e5dd7070Spatrick   // size at most 16 by the standard, so the first '(' must be among the first
161e5dd7070Spatrick   // 19 bytes.
162e5dd7070Spatrick   size_t LParenPos = TokenText.substr(0, 19).find_first_of('(');
163e5dd7070Spatrick   if (LParenPos == StringRef::npos)
164*12c85518Srobert     return std::nullopt;
165e5dd7070Spatrick   StringRef Delimiter = TokenText.substr(2, LParenPos - 2);
166e5dd7070Spatrick 
167e5dd7070Spatrick   // Check that the string ends in ')Delimiter"'.
168e5dd7070Spatrick   size_t RParenPos = TokenText.size() - Delimiter.size() - 2;
169e5dd7070Spatrick   if (TokenText[RParenPos] != ')')
170*12c85518Srobert     return std::nullopt;
171e5dd7070Spatrick   if (!TokenText.substr(RParenPos + 1).startswith(Delimiter))
172*12c85518Srobert     return std::nullopt;
173e5dd7070Spatrick   return Delimiter;
174e5dd7070Spatrick }
175e5dd7070Spatrick 
176e5dd7070Spatrick // Returns the canonical delimiter for \p Language, or the empty string if no
177e5dd7070Spatrick // canonical delimiter is specified.
178e5dd7070Spatrick static StringRef
getCanonicalRawStringDelimiter(const FormatStyle & Style,FormatStyle::LanguageKind Language)179e5dd7070Spatrick getCanonicalRawStringDelimiter(const FormatStyle &Style,
180e5dd7070Spatrick                                FormatStyle::LanguageKind Language) {
181*12c85518Srobert   for (const auto &Format : Style.RawStringFormats)
182e5dd7070Spatrick     if (Format.Language == Language)
183e5dd7070Spatrick       return StringRef(Format.CanonicalDelimiter);
184e5dd7070Spatrick   return "";
185e5dd7070Spatrick }
186e5dd7070Spatrick 
RawStringFormatStyleManager(const FormatStyle & CodeStyle)187e5dd7070Spatrick RawStringFormatStyleManager::RawStringFormatStyleManager(
188e5dd7070Spatrick     const FormatStyle &CodeStyle) {
189e5dd7070Spatrick   for (const auto &RawStringFormat : CodeStyle.RawStringFormats) {
190*12c85518Srobert     std::optional<FormatStyle> LanguageStyle =
191e5dd7070Spatrick         CodeStyle.GetLanguageStyle(RawStringFormat.Language);
192e5dd7070Spatrick     if (!LanguageStyle) {
193e5dd7070Spatrick       FormatStyle PredefinedStyle;
194e5dd7070Spatrick       if (!getPredefinedStyle(RawStringFormat.BasedOnStyle,
195e5dd7070Spatrick                               RawStringFormat.Language, &PredefinedStyle)) {
196e5dd7070Spatrick         PredefinedStyle = getLLVMStyle();
197e5dd7070Spatrick         PredefinedStyle.Language = RawStringFormat.Language;
198e5dd7070Spatrick       }
199e5dd7070Spatrick       LanguageStyle = PredefinedStyle;
200e5dd7070Spatrick     }
201e5dd7070Spatrick     LanguageStyle->ColumnLimit = CodeStyle.ColumnLimit;
202*12c85518Srobert     for (StringRef Delimiter : RawStringFormat.Delimiters)
203e5dd7070Spatrick       DelimiterStyle.insert({Delimiter, *LanguageStyle});
204*12c85518Srobert     for (StringRef EnclosingFunction : RawStringFormat.EnclosingFunctions)
205e5dd7070Spatrick       EnclosingFunctionStyle.insert({EnclosingFunction, *LanguageStyle});
206e5dd7070Spatrick   }
207e5dd7070Spatrick }
208e5dd7070Spatrick 
209*12c85518Srobert std::optional<FormatStyle>
getDelimiterStyle(StringRef Delimiter) const210e5dd7070Spatrick RawStringFormatStyleManager::getDelimiterStyle(StringRef Delimiter) const {
211e5dd7070Spatrick   auto It = DelimiterStyle.find(Delimiter);
212e5dd7070Spatrick   if (It == DelimiterStyle.end())
213*12c85518Srobert     return std::nullopt;
214e5dd7070Spatrick   return It->second;
215e5dd7070Spatrick }
216e5dd7070Spatrick 
217*12c85518Srobert std::optional<FormatStyle>
getEnclosingFunctionStyle(StringRef EnclosingFunction) const218e5dd7070Spatrick RawStringFormatStyleManager::getEnclosingFunctionStyle(
219e5dd7070Spatrick     StringRef EnclosingFunction) const {
220e5dd7070Spatrick   auto It = EnclosingFunctionStyle.find(EnclosingFunction);
221e5dd7070Spatrick   if (It == EnclosingFunctionStyle.end())
222*12c85518Srobert     return std::nullopt;
223e5dd7070Spatrick   return It->second;
224e5dd7070Spatrick }
225e5dd7070Spatrick 
ContinuationIndenter(const FormatStyle & Style,const AdditionalKeywords & Keywords,const SourceManager & SourceMgr,WhitespaceManager & Whitespaces,encoding::Encoding Encoding,bool BinPackInconclusiveFunctions)226e5dd7070Spatrick ContinuationIndenter::ContinuationIndenter(const FormatStyle &Style,
227e5dd7070Spatrick                                            const AdditionalKeywords &Keywords,
228e5dd7070Spatrick                                            const SourceManager &SourceMgr,
229e5dd7070Spatrick                                            WhitespaceManager &Whitespaces,
230e5dd7070Spatrick                                            encoding::Encoding Encoding,
231e5dd7070Spatrick                                            bool BinPackInconclusiveFunctions)
232e5dd7070Spatrick     : Style(Style), Keywords(Keywords), SourceMgr(SourceMgr),
233e5dd7070Spatrick       Whitespaces(Whitespaces), Encoding(Encoding),
234e5dd7070Spatrick       BinPackInconclusiveFunctions(BinPackInconclusiveFunctions),
235e5dd7070Spatrick       CommentPragmasRegex(Style.CommentPragmas), RawStringFormats(Style) {}
236e5dd7070Spatrick 
getInitialState(unsigned FirstIndent,unsigned FirstStartColumn,const AnnotatedLine * Line,bool DryRun)237e5dd7070Spatrick LineState ContinuationIndenter::getInitialState(unsigned FirstIndent,
238e5dd7070Spatrick                                                 unsigned FirstStartColumn,
239e5dd7070Spatrick                                                 const AnnotatedLine *Line,
240e5dd7070Spatrick                                                 bool DryRun) {
241e5dd7070Spatrick   LineState State;
242e5dd7070Spatrick   State.FirstIndent = FirstIndent;
243e5dd7070Spatrick   if (FirstStartColumn && Line->First->NewlinesBefore == 0)
244e5dd7070Spatrick     State.Column = FirstStartColumn;
245e5dd7070Spatrick   else
246e5dd7070Spatrick     State.Column = FirstIndent;
247e5dd7070Spatrick   // With preprocessor directive indentation, the line starts on column 0
248e5dd7070Spatrick   // since it's indented after the hash, but FirstIndent is set to the
249e5dd7070Spatrick   // preprocessor indent.
250e5dd7070Spatrick   if (Style.IndentPPDirectives == FormatStyle::PPDIS_AfterHash &&
251e5dd7070Spatrick       (Line->Type == LT_PreprocessorDirective ||
252*12c85518Srobert        Line->Type == LT_ImportStatement)) {
253e5dd7070Spatrick     State.Column = 0;
254*12c85518Srobert   }
255e5dd7070Spatrick   State.Line = Line;
256e5dd7070Spatrick   State.NextToken = Line->First;
257e5dd7070Spatrick   State.Stack.push_back(ParenState(/*Tok=*/nullptr, FirstIndent, FirstIndent,
258e5dd7070Spatrick                                    /*AvoidBinPacking=*/false,
259e5dd7070Spatrick                                    /*NoLineBreak=*/false));
260e5dd7070Spatrick   State.NoContinuation = false;
261e5dd7070Spatrick   State.StartOfStringLiteral = 0;
262e5dd7070Spatrick   State.StartOfLineLevel = 0;
263e5dd7070Spatrick   State.LowestLevelOnLine = 0;
264e5dd7070Spatrick   State.IgnoreStackForComparison = false;
265e5dd7070Spatrick 
266e5dd7070Spatrick   if (Style.Language == FormatStyle::LK_TextProto) {
267e5dd7070Spatrick     // We need this in order to deal with the bin packing of text fields at
268e5dd7070Spatrick     // global scope.
269*12c85518Srobert     auto &CurrentState = State.Stack.back();
270*12c85518Srobert     CurrentState.AvoidBinPacking = true;
271*12c85518Srobert     CurrentState.BreakBeforeParameter = true;
272*12c85518Srobert     CurrentState.AlignColons = false;
273e5dd7070Spatrick   }
274e5dd7070Spatrick 
275e5dd7070Spatrick   // The first token has already been indented and thus consumed.
276e5dd7070Spatrick   moveStateToNextToken(State, DryRun, /*Newline=*/false);
277e5dd7070Spatrick   return State;
278e5dd7070Spatrick }
279e5dd7070Spatrick 
canBreak(const LineState & State)280e5dd7070Spatrick bool ContinuationIndenter::canBreak(const LineState &State) {
281e5dd7070Spatrick   const FormatToken &Current = *State.NextToken;
282e5dd7070Spatrick   const FormatToken &Previous = *Current.Previous;
283*12c85518Srobert   const auto &CurrentState = State.Stack.back();
284e5dd7070Spatrick   assert(&Previous == Current.Previous);
285*12c85518Srobert   if (!Current.CanBreakBefore && !(CurrentState.BreakBeforeClosingBrace &&
286*12c85518Srobert                                    Current.closesBlockOrBlockTypeList(Style))) {
287e5dd7070Spatrick     return false;
288*12c85518Srobert   }
289e5dd7070Spatrick   // The opening "{" of a braced list has to be on the same line as the first
290e5dd7070Spatrick   // element if it is nested in another braced init list or function call.
291e5dd7070Spatrick   if (!Current.MustBreakBefore && Previous.is(tok::l_brace) &&
292a9ac8606Spatrick       Previous.isNot(TT_DictLiteral) && Previous.is(BK_BracedInit) &&
293e5dd7070Spatrick       Previous.Previous &&
294*12c85518Srobert       Previous.Previous->isOneOf(tok::l_brace, tok::l_paren, tok::comma)) {
295e5dd7070Spatrick     return false;
296*12c85518Srobert   }
297e5dd7070Spatrick   // This prevents breaks like:
298e5dd7070Spatrick   //   ...
299e5dd7070Spatrick   //   SomeParameter, OtherParameter).DoSomething(
300e5dd7070Spatrick   //   ...
301e5dd7070Spatrick   // As they hide "DoSomething" and are generally bad for readability.
302e5dd7070Spatrick   if (Previous.opensScope() && Previous.isNot(tok::l_brace) &&
303e5dd7070Spatrick       State.LowestLevelOnLine < State.StartOfLineLevel &&
304*12c85518Srobert       State.LowestLevelOnLine < Current.NestingLevel) {
305e5dd7070Spatrick     return false;
306*12c85518Srobert   }
307*12c85518Srobert   if (Current.isMemberAccess() && CurrentState.ContainsUnwrappedBuilder)
308e5dd7070Spatrick     return false;
309e5dd7070Spatrick 
310e5dd7070Spatrick   // Don't create a 'hanging' indent if there are multiple blocks in a single
311e5dd7070Spatrick   // statement.
312e5dd7070Spatrick   if (Previous.is(tok::l_brace) && State.Stack.size() > 1 &&
313e5dd7070Spatrick       State.Stack[State.Stack.size() - 2].NestedBlockInlined &&
314*12c85518Srobert       State.Stack[State.Stack.size() - 2].HasMultipleNestedBlocks) {
315e5dd7070Spatrick     return false;
316*12c85518Srobert   }
317e5dd7070Spatrick 
318e5dd7070Spatrick   // Don't break after very short return types (e.g. "void") as that is often
319e5dd7070Spatrick   // unexpected.
320e5dd7070Spatrick   if (Current.is(TT_FunctionDeclarationName) && State.Column < 6) {
321e5dd7070Spatrick     if (Style.AlwaysBreakAfterReturnType == FormatStyle::RTBS_None)
322e5dd7070Spatrick       return false;
323e5dd7070Spatrick   }
324e5dd7070Spatrick 
325e5dd7070Spatrick   // If binary operators are moved to the next line (including commas for some
326e5dd7070Spatrick   // styles of constructor initializers), that's always ok.
327e5dd7070Spatrick   if (!Current.isOneOf(TT_BinaryOperator, tok::comma) &&
328*12c85518Srobert       CurrentState.NoLineBreakInOperand) {
329e5dd7070Spatrick     return false;
330*12c85518Srobert   }
331e5dd7070Spatrick 
332e5dd7070Spatrick   if (Previous.is(tok::l_square) && Previous.is(TT_ObjCMethodExpr))
333e5dd7070Spatrick     return false;
334e5dd7070Spatrick 
335*12c85518Srobert   if (Current.is(TT_ConditionalExpr) && Previous.is(tok::r_paren) &&
336*12c85518Srobert       Previous.MatchingParen && Previous.MatchingParen->Previous &&
337*12c85518Srobert       Previous.MatchingParen->Previous->MatchingParen &&
338*12c85518Srobert       Previous.MatchingParen->Previous->MatchingParen->is(TT_LambdaLBrace)) {
339*12c85518Srobert     // We have a lambda within a conditional expression, allow breaking here.
340*12c85518Srobert     assert(Previous.MatchingParen->Previous->is(tok::r_brace));
341*12c85518Srobert     return true;
342*12c85518Srobert   }
343*12c85518Srobert 
344*12c85518Srobert   return !CurrentState.NoLineBreak;
345e5dd7070Spatrick }
346e5dd7070Spatrick 
mustBreak(const LineState & State)347e5dd7070Spatrick bool ContinuationIndenter::mustBreak(const LineState &State) {
348e5dd7070Spatrick   const FormatToken &Current = *State.NextToken;
349e5dd7070Spatrick   const FormatToken &Previous = *Current.Previous;
350*12c85518Srobert   const auto &CurrentState = State.Stack.back();
351ec727ea7Spatrick   if (Style.BraceWrapping.BeforeLambdaBody && Current.CanBreakBefore &&
352ec727ea7Spatrick       Current.is(TT_LambdaLBrace) && Previous.isNot(TT_LineComment)) {
353ec727ea7Spatrick     auto LambdaBodyLength = getLengthToMatchingParen(Current, State.Stack);
354*12c85518Srobert     return LambdaBodyLength > getColumnLimit(State);
355ec727ea7Spatrick   }
356*12c85518Srobert   if (Current.MustBreakBefore ||
357*12c85518Srobert       (Current.is(TT_InlineASMColon) &&
358*12c85518Srobert        (Style.BreakBeforeInlineASMColon == FormatStyle::BBIAS_Always ||
359*12c85518Srobert         Style.BreakBeforeInlineASMColon == FormatStyle::BBIAS_OnlyMultiline))) {
360e5dd7070Spatrick     return true;
361*12c85518Srobert   }
362*12c85518Srobert   if (CurrentState.BreakBeforeClosingBrace &&
363*12c85518Srobert       Current.closesBlockOrBlockTypeList(Style)) {
364e5dd7070Spatrick     return true;
365*12c85518Srobert   }
366*12c85518Srobert   if (CurrentState.BreakBeforeClosingParen && Current.is(tok::r_paren))
367e5dd7070Spatrick     return true;
368e5dd7070Spatrick   if (Style.Language == FormatStyle::LK_ObjC &&
369ec727ea7Spatrick       Style.ObjCBreakBeforeNestedBlockParam &&
370e5dd7070Spatrick       Current.ObjCSelectorNameParts > 1 &&
371e5dd7070Spatrick       Current.startsSequence(TT_SelectorName, tok::colon, tok::caret)) {
372e5dd7070Spatrick     return true;
373e5dd7070Spatrick   }
374ec727ea7Spatrick   // Avoid producing inconsistent states by requiring breaks where they are not
375ec727ea7Spatrick   // permitted for C# generic type constraints.
376*12c85518Srobert   if (CurrentState.IsCSharpGenericTypeConstraint &&
377*12c85518Srobert       Previous.isNot(TT_CSharpGenericTypeConstraintComma)) {
378ec727ea7Spatrick     return false;
379*12c85518Srobert   }
380e5dd7070Spatrick   if ((startsNextParameter(Current, Style) || Previous.is(tok::semi) ||
381e5dd7070Spatrick        (Previous.is(TT_TemplateCloser) && Current.is(TT_StartOfName) &&
382e5dd7070Spatrick         Style.isCpp() &&
383e5dd7070Spatrick         // FIXME: This is a temporary workaround for the case where clang-format
384e5dd7070Spatrick         // sets BreakBeforeParameter to avoid bin packing and this creates a
385e5dd7070Spatrick         // completely unnecessary line break after a template type that isn't
386e5dd7070Spatrick         // line-wrapped.
387e5dd7070Spatrick         (Previous.NestingLevel == 1 || Style.BinPackParameters)) ||
388e5dd7070Spatrick        (Style.BreakBeforeTernaryOperators && Current.is(TT_ConditionalExpr) &&
389e5dd7070Spatrick         Previous.isNot(tok::question)) ||
390e5dd7070Spatrick        (!Style.BreakBeforeTernaryOperators &&
391e5dd7070Spatrick         Previous.is(TT_ConditionalExpr))) &&
392*12c85518Srobert       CurrentState.BreakBeforeParameter && !Current.isTrailingComment() &&
393*12c85518Srobert       !Current.isOneOf(tok::r_paren, tok::r_brace)) {
394e5dd7070Spatrick     return true;
395*12c85518Srobert   }
396*12c85518Srobert   if (CurrentState.IsChainedConditional &&
397ec727ea7Spatrick       ((Style.BreakBeforeTernaryOperators && Current.is(TT_ConditionalExpr) &&
398ec727ea7Spatrick         Current.is(tok::colon)) ||
399ec727ea7Spatrick        (!Style.BreakBeforeTernaryOperators && Previous.is(TT_ConditionalExpr) &&
400*12c85518Srobert         Previous.is(tok::colon)))) {
401ec727ea7Spatrick     return true;
402*12c85518Srobert   }
403e5dd7070Spatrick   if (((Previous.is(TT_DictLiteral) && Previous.is(tok::l_brace)) ||
404e5dd7070Spatrick        (Previous.is(TT_ArrayInitializerLSquare) &&
405e5dd7070Spatrick         Previous.ParameterCount > 1) ||
406e5dd7070Spatrick        opensProtoMessageField(Previous, Style)) &&
407e5dd7070Spatrick       Style.ColumnLimit > 0 &&
408e5dd7070Spatrick       getLengthToMatchingParen(Previous, State.Stack) + State.Column - 1 >
409*12c85518Srobert           getColumnLimit(State)) {
410e5dd7070Spatrick     return true;
411*12c85518Srobert   }
412e5dd7070Spatrick 
413e5dd7070Spatrick   const FormatToken &BreakConstructorInitializersToken =
414e5dd7070Spatrick       Style.BreakConstructorInitializers == FormatStyle::BCIS_AfterColon
415e5dd7070Spatrick           ? Previous
416e5dd7070Spatrick           : Current;
417e5dd7070Spatrick   if (BreakConstructorInitializersToken.is(TT_CtorInitializerColon) &&
418e5dd7070Spatrick       (State.Column + State.Line->Last->TotalLength - Previous.TotalLength >
419e5dd7070Spatrick            getColumnLimit(State) ||
420*12c85518Srobert        CurrentState.BreakBeforeParameter) &&
421*12c85518Srobert       (!Current.isTrailingComment() || Current.NewlinesBefore > 0) &&
422e5dd7070Spatrick       (Style.AllowShortFunctionsOnASingleLine != FormatStyle::SFS_All ||
423e5dd7070Spatrick        Style.BreakConstructorInitializers != FormatStyle::BCIS_BeforeColon ||
424*12c85518Srobert        Style.ColumnLimit != 0)) {
425e5dd7070Spatrick     return true;
426*12c85518Srobert   }
427e5dd7070Spatrick 
428e5dd7070Spatrick   if (Current.is(TT_ObjCMethodExpr) && !Previous.is(TT_SelectorName) &&
429*12c85518Srobert       State.Line->startsWith(TT_ObjCMethodSpecifier)) {
430e5dd7070Spatrick     return true;
431*12c85518Srobert   }
432e5dd7070Spatrick   if (Current.is(TT_SelectorName) && !Previous.is(tok::at) &&
433*12c85518Srobert       CurrentState.ObjCSelectorNameFound && CurrentState.BreakBeforeParameter &&
434a9ac8606Spatrick       (Style.ObjCBreakBeforeNestedBlockParam ||
435*12c85518Srobert        !Current.startsSequence(TT_SelectorName, tok::colon, tok::caret))) {
436e5dd7070Spatrick     return true;
437*12c85518Srobert   }
438e5dd7070Spatrick 
439e5dd7070Spatrick   unsigned NewLineColumn = getNewLineColumn(State);
440e5dd7070Spatrick   if (Current.isMemberAccess() && Style.ColumnLimit != 0 &&
441e5dd7070Spatrick       State.Column + getLengthToNextOperator(Current) > Style.ColumnLimit &&
442e5dd7070Spatrick       (State.Column > NewLineColumn ||
443*12c85518Srobert        Current.NestingLevel < State.StartOfLineLevel)) {
444e5dd7070Spatrick     return true;
445*12c85518Srobert   }
446e5dd7070Spatrick 
447e5dd7070Spatrick   if (startsSegmentOfBuilderTypeCall(Current) &&
448*12c85518Srobert       (CurrentState.CallContinuation != 0 ||
449*12c85518Srobert        CurrentState.BreakBeforeParameter) &&
450e5dd7070Spatrick       // JavaScript is treated different here as there is a frequent pattern:
451e5dd7070Spatrick       //   SomeFunction(function() {
452e5dd7070Spatrick       //     ...
453e5dd7070Spatrick       //   }.bind(...));
454e5dd7070Spatrick       // FIXME: We should find a more generic solution to this problem.
455*12c85518Srobert       !(State.Column <= NewLineColumn && Style.isJavaScript()) &&
456*12c85518Srobert       !(Previous.closesScopeAfterBlock() && State.Column <= NewLineColumn)) {
457e5dd7070Spatrick     return true;
458*12c85518Srobert   }
459e5dd7070Spatrick 
460e5dd7070Spatrick   // If the template declaration spans multiple lines, force wrap before the
461*12c85518Srobert   // function/class declaration.
462*12c85518Srobert   if (Previous.ClosesTemplateDeclaration && CurrentState.BreakBeforeParameter &&
463*12c85518Srobert       Current.CanBreakBefore) {
464e5dd7070Spatrick     return true;
465*12c85518Srobert   }
466e5dd7070Spatrick 
467ec727ea7Spatrick   if (!State.Line->First->is(tok::kw_enum) && State.Column <= NewLineColumn)
468e5dd7070Spatrick     return false;
469e5dd7070Spatrick 
470e5dd7070Spatrick   if (Style.AlwaysBreakBeforeMultilineStrings &&
471e5dd7070Spatrick       (NewLineColumn == State.FirstIndent + Style.ContinuationIndentWidth ||
472e5dd7070Spatrick        Previous.is(tok::comma) || Current.NestingLevel < 2) &&
473e5dd7070Spatrick       !Previous.isOneOf(tok::kw_return, tok::lessless, tok::at,
474e5dd7070Spatrick                         Keywords.kw_dollar) &&
475e5dd7070Spatrick       !Previous.isOneOf(TT_InlineASMColon, TT_ConditionalExpr) &&
476*12c85518Srobert       nextIsMultilineString(State)) {
477e5dd7070Spatrick     return true;
478*12c85518Srobert   }
479e5dd7070Spatrick 
480e5dd7070Spatrick   // Using CanBreakBefore here and below takes care of the decision whether the
481e5dd7070Spatrick   // current style uses wrapping before or after operators for the given
482e5dd7070Spatrick   // operator.
483e5dd7070Spatrick   if (Previous.is(TT_BinaryOperator) && Current.CanBreakBefore) {
484*12c85518Srobert     const auto PreviousPrecedence = Previous.getPrecedence();
485*12c85518Srobert     if (PreviousPrecedence != prec::Assignment &&
486*12c85518Srobert         CurrentState.BreakBeforeParameter && !Current.isTrailingComment()) {
487*12c85518Srobert       const bool LHSIsBinaryExpr =
488*12c85518Srobert           Previous.Previous && Previous.Previous->EndsBinaryExpression;
489*12c85518Srobert       if (LHSIsBinaryExpr)
490*12c85518Srobert         return true;
491e5dd7070Spatrick       // If we need to break somewhere inside the LHS of a binary expression, we
492e5dd7070Spatrick       // should also break after the operator. Otherwise, the formatting would
493e5dd7070Spatrick       // hide the operator precedence, e.g. in:
494e5dd7070Spatrick       //   if (aaaaaaaaaaaaaa ==
495e5dd7070Spatrick       //           bbbbbbbbbbbbbb && c) {..
496e5dd7070Spatrick       // For comparisons, we only apply this rule, if the LHS is a binary
497e5dd7070Spatrick       // expression itself as otherwise, the line breaks seem superfluous.
498e5dd7070Spatrick       // We need special cases for ">>" which we have split into two ">" while
499e5dd7070Spatrick       // lexing in order to make template parsing easier.
500*12c85518Srobert       const bool IsComparison =
501*12c85518Srobert           (PreviousPrecedence == prec::Relational ||
502*12c85518Srobert            PreviousPrecedence == prec::Equality ||
503*12c85518Srobert            PreviousPrecedence == prec::Spaceship) &&
504e5dd7070Spatrick           Previous.Previous &&
505e5dd7070Spatrick           Previous.Previous->isNot(TT_BinaryOperator); // For >>.
506*12c85518Srobert       if (!IsComparison)
507e5dd7070Spatrick         return true;
508*12c85518Srobert     }
509e5dd7070Spatrick   } else if (Current.is(TT_BinaryOperator) && Current.CanBreakBefore &&
510*12c85518Srobert              CurrentState.BreakBeforeParameter) {
511e5dd7070Spatrick     return true;
512e5dd7070Spatrick   }
513e5dd7070Spatrick 
514e5dd7070Spatrick   // Same as above, but for the first "<<" operator.
515e5dd7070Spatrick   if (Current.is(tok::lessless) && Current.isNot(TT_OverloadedOperator) &&
516*12c85518Srobert       CurrentState.BreakBeforeParameter && CurrentState.FirstLessLess == 0) {
517e5dd7070Spatrick     return true;
518*12c85518Srobert   }
519e5dd7070Spatrick 
520e5dd7070Spatrick   if (Current.NestingLevel == 0 && !Current.isTrailingComment()) {
521*12c85518Srobert     // Always break after "template <...>"(*) and leading annotations. This is
522*12c85518Srobert     // only for cases where the entire line does not fit on a single line as a
523e5dd7070Spatrick     // different LineFormatter would be used otherwise.
524*12c85518Srobert     // *: Except when another option interferes with that, like concepts.
525*12c85518Srobert     if (Previous.ClosesTemplateDeclaration) {
526*12c85518Srobert       if (Current.is(tok::kw_concept)) {
527*12c85518Srobert         switch (Style.BreakBeforeConceptDeclarations) {
528*12c85518Srobert         case FormatStyle::BBCDS_Allowed:
529*12c85518Srobert           break;
530*12c85518Srobert         case FormatStyle::BBCDS_Always:
531e5dd7070Spatrick           return true;
532*12c85518Srobert         case FormatStyle::BBCDS_Never:
533*12c85518Srobert           return false;
534*12c85518Srobert         }
535*12c85518Srobert       }
536*12c85518Srobert       if (Current.is(TT_RequiresClause)) {
537*12c85518Srobert         switch (Style.RequiresClausePosition) {
538*12c85518Srobert         case FormatStyle::RCPS_SingleLine:
539*12c85518Srobert         case FormatStyle::RCPS_WithPreceding:
540*12c85518Srobert           return false;
541*12c85518Srobert         default:
542*12c85518Srobert           return true;
543*12c85518Srobert         }
544*12c85518Srobert       }
545*12c85518Srobert       return Style.AlwaysBreakTemplateDeclarations != FormatStyle::BTDS_No;
546*12c85518Srobert     }
547*12c85518Srobert     if (Previous.is(TT_FunctionAnnotationRParen) &&
548*12c85518Srobert         State.Line->Type != LT_PreprocessorDirective) {
549*12c85518Srobert       return true;
550*12c85518Srobert     }
551e5dd7070Spatrick     if (Previous.is(TT_LeadingJavaAnnotation) && Current.isNot(tok::l_paren) &&
552*12c85518Srobert         Current.isNot(TT_LeadingJavaAnnotation)) {
553*12c85518Srobert       return true;
554*12c85518Srobert     }
555*12c85518Srobert   }
556*12c85518Srobert 
557*12c85518Srobert   if (Style.isJavaScript() && Previous.is(tok::r_paren) &&
558*12c85518Srobert       Previous.is(TT_JavaAnnotation)) {
559*12c85518Srobert     // Break after the closing parenthesis of TypeScript decorators before
560*12c85518Srobert     // functions, getters and setters.
561*12c85518Srobert     static const llvm::StringSet<> BreakBeforeDecoratedTokens = {"get", "set",
562*12c85518Srobert                                                                  "function"};
563*12c85518Srobert     if (BreakBeforeDecoratedTokens.contains(Current.TokenText))
564e5dd7070Spatrick       return true;
565e5dd7070Spatrick   }
566e5dd7070Spatrick 
567e5dd7070Spatrick   // If the return type spans multiple lines, wrap before the function name.
568e5dd7070Spatrick   if (((Current.is(TT_FunctionDeclarationName) &&
569*12c85518Srobert         !State.Line->ReturnTypeWrapped &&
570*12c85518Srobert         // Don't break before a C# function when no break after return type.
571e5dd7070Spatrick         (!Style.isCSharp() ||
572*12c85518Srobert          Style.AlwaysBreakAfterReturnType != FormatStyle::RTBS_None) &&
573*12c85518Srobert         // Don't always break between a JavaScript `function` and the function
574*12c85518Srobert         // name.
575*12c85518Srobert         !Style.isJavaScript()) ||
576e5dd7070Spatrick        (Current.is(tok::kw_operator) && !Previous.is(tok::coloncolon))) &&
577*12c85518Srobert       !Previous.is(tok::kw_template) && CurrentState.BreakBeforeParameter) {
578e5dd7070Spatrick     return true;
579*12c85518Srobert   }
580e5dd7070Spatrick 
581e5dd7070Spatrick   // The following could be precomputed as they do not depend on the state.
582e5dd7070Spatrick   // However, as they should take effect only if the UnwrappedLine does not fit
583e5dd7070Spatrick   // into the ColumnLimit, they are checked here in the ContinuationIndenter.
584a9ac8606Spatrick   if (Style.ColumnLimit != 0 && Previous.is(BK_Block) &&
585*12c85518Srobert       Previous.is(tok::l_brace) &&
586*12c85518Srobert       !Current.isOneOf(tok::r_brace, tok::comment)) {
587e5dd7070Spatrick     return true;
588*12c85518Srobert   }
589e5dd7070Spatrick 
590e5dd7070Spatrick   if (Current.is(tok::lessless) &&
591e5dd7070Spatrick       ((Previous.is(tok::identifier) && Previous.TokenText == "endl") ||
592e5dd7070Spatrick        (Previous.Tok.isLiteral() && (Previous.TokenText.endswith("\\n\"") ||
593*12c85518Srobert                                      Previous.TokenText == "\'\\n\'")))) {
594e5dd7070Spatrick     return true;
595*12c85518Srobert   }
596e5dd7070Spatrick 
597e5dd7070Spatrick   if (Previous.is(TT_BlockComment) && Previous.IsMultiline)
598e5dd7070Spatrick     return true;
599e5dd7070Spatrick 
600e5dd7070Spatrick   if (State.NoContinuation)
601e5dd7070Spatrick     return true;
602e5dd7070Spatrick 
603e5dd7070Spatrick   return false;
604e5dd7070Spatrick }
605e5dd7070Spatrick 
addTokenToState(LineState & State,bool Newline,bool DryRun,unsigned ExtraSpaces)606e5dd7070Spatrick unsigned ContinuationIndenter::addTokenToState(LineState &State, bool Newline,
607e5dd7070Spatrick                                                bool DryRun,
608e5dd7070Spatrick                                                unsigned ExtraSpaces) {
609e5dd7070Spatrick   const FormatToken &Current = *State.NextToken;
610*12c85518Srobert   assert(State.NextToken->Previous);
611*12c85518Srobert   const FormatToken &Previous = *State.NextToken->Previous;
612e5dd7070Spatrick 
613e5dd7070Spatrick   assert(!State.Stack.empty());
614e5dd7070Spatrick   State.NoContinuation = false;
615e5dd7070Spatrick 
616e5dd7070Spatrick   if ((Current.is(TT_ImplicitStringLiteral) &&
617*12c85518Srobert        (Previous.Tok.getIdentifierInfo() == nullptr ||
618*12c85518Srobert         Previous.Tok.getIdentifierInfo()->getPPKeywordID() ==
619e5dd7070Spatrick             tok::pp_not_keyword))) {
620e5dd7070Spatrick     unsigned EndColumn =
621e5dd7070Spatrick         SourceMgr.getSpellingColumnNumber(Current.WhitespaceRange.getEnd());
622e5dd7070Spatrick     if (Current.LastNewlineOffset != 0) {
623e5dd7070Spatrick       // If there is a newline within this token, the final column will solely
624e5dd7070Spatrick       // determined by the current end column.
625e5dd7070Spatrick       State.Column = EndColumn;
626e5dd7070Spatrick     } else {
627e5dd7070Spatrick       unsigned StartColumn =
628e5dd7070Spatrick           SourceMgr.getSpellingColumnNumber(Current.WhitespaceRange.getBegin());
629e5dd7070Spatrick       assert(EndColumn >= StartColumn);
630e5dd7070Spatrick       State.Column += EndColumn - StartColumn;
631e5dd7070Spatrick     }
632e5dd7070Spatrick     moveStateToNextToken(State, DryRun, /*Newline=*/false);
633e5dd7070Spatrick     return 0;
634e5dd7070Spatrick   }
635e5dd7070Spatrick 
636e5dd7070Spatrick   unsigned Penalty = 0;
637e5dd7070Spatrick   if (Newline)
638e5dd7070Spatrick     Penalty = addTokenOnNewLine(State, DryRun);
639e5dd7070Spatrick   else
640e5dd7070Spatrick     addTokenOnCurrentLine(State, DryRun, ExtraSpaces);
641e5dd7070Spatrick 
642e5dd7070Spatrick   return moveStateToNextToken(State, DryRun, Newline) + Penalty;
643e5dd7070Spatrick }
644e5dd7070Spatrick 
addTokenOnCurrentLine(LineState & State,bool DryRun,unsigned ExtraSpaces)645e5dd7070Spatrick void ContinuationIndenter::addTokenOnCurrentLine(LineState &State, bool DryRun,
646e5dd7070Spatrick                                                  unsigned ExtraSpaces) {
647e5dd7070Spatrick   FormatToken &Current = *State.NextToken;
648*12c85518Srobert   assert(State.NextToken->Previous);
649e5dd7070Spatrick   const FormatToken &Previous = *State.NextToken->Previous;
650*12c85518Srobert   auto &CurrentState = State.Stack.back();
651*12c85518Srobert 
652e5dd7070Spatrick   if (Current.is(tok::equal) &&
653e5dd7070Spatrick       (State.Line->First->is(tok::kw_for) || Current.NestingLevel == 0) &&
654*12c85518Srobert       CurrentState.VariablePos == 0) {
655*12c85518Srobert     CurrentState.VariablePos = State.Column;
656e5dd7070Spatrick     // Move over * and & if they are bound to the variable name.
657e5dd7070Spatrick     const FormatToken *Tok = &Previous;
658*12c85518Srobert     while (Tok && CurrentState.VariablePos >= Tok->ColumnWidth) {
659*12c85518Srobert       CurrentState.VariablePos -= Tok->ColumnWidth;
660e5dd7070Spatrick       if (Tok->SpacesRequiredBefore != 0)
661e5dd7070Spatrick         break;
662e5dd7070Spatrick       Tok = Tok->Previous;
663e5dd7070Spatrick     }
664e5dd7070Spatrick     if (Previous.PartOfMultiVariableDeclStmt)
665*12c85518Srobert       CurrentState.LastSpace = CurrentState.VariablePos;
666e5dd7070Spatrick   }
667e5dd7070Spatrick 
668e5dd7070Spatrick   unsigned Spaces = Current.SpacesRequiredBefore + ExtraSpaces;
669e5dd7070Spatrick 
670e5dd7070Spatrick   // Indent preprocessor directives after the hash if required.
671e5dd7070Spatrick   int PPColumnCorrection = 0;
672e5dd7070Spatrick   if (Style.IndentPPDirectives == FormatStyle::PPDIS_AfterHash &&
673e5dd7070Spatrick       Previous.is(tok::hash) && State.FirstIndent > 0 &&
674*12c85518Srobert       &Previous == State.Line->First &&
675e5dd7070Spatrick       (State.Line->Type == LT_PreprocessorDirective ||
676e5dd7070Spatrick        State.Line->Type == LT_ImportStatement)) {
677e5dd7070Spatrick     Spaces += State.FirstIndent;
678e5dd7070Spatrick 
679e5dd7070Spatrick     // For preprocessor indent with tabs, State.Column will be 1 because of the
680e5dd7070Spatrick     // hash. This causes second-level indents onward to have an extra space
681e5dd7070Spatrick     // after the tabs. We avoid this misalignment by subtracting 1 from the
682e5dd7070Spatrick     // column value passed to replaceWhitespace().
683e5dd7070Spatrick     if (Style.UseTab != FormatStyle::UT_Never)
684e5dd7070Spatrick       PPColumnCorrection = -1;
685e5dd7070Spatrick   }
686e5dd7070Spatrick 
687*12c85518Srobert   if (!DryRun) {
688e5dd7070Spatrick     Whitespaces.replaceWhitespace(Current, /*Newlines=*/0, Spaces,
689e5dd7070Spatrick                                   State.Column + Spaces + PPColumnCorrection);
690*12c85518Srobert   }
691e5dd7070Spatrick 
692e5dd7070Spatrick   // If "BreakBeforeInheritanceComma" mode, don't break within the inheritance
693e5dd7070Spatrick   // declaration unless there is multiple inheritance.
694e5dd7070Spatrick   if (Style.BreakInheritanceList == FormatStyle::BILS_BeforeComma &&
695*12c85518Srobert       Current.is(TT_InheritanceColon)) {
696*12c85518Srobert     CurrentState.NoLineBreak = true;
697*12c85518Srobert   }
698e5dd7070Spatrick   if (Style.BreakInheritanceList == FormatStyle::BILS_AfterColon &&
699*12c85518Srobert       Previous.is(TT_InheritanceColon)) {
700*12c85518Srobert     CurrentState.NoLineBreak = true;
701e5dd7070Spatrick   }
702e5dd7070Spatrick 
703*12c85518Srobert   if (Current.is(TT_SelectorName) && !CurrentState.ObjCSelectorNameFound) {
704*12c85518Srobert     unsigned MinIndent = std::max(
705*12c85518Srobert         State.FirstIndent + Style.ContinuationIndentWidth, CurrentState.Indent);
706*12c85518Srobert     unsigned FirstColonPos = State.Column + Spaces + Current.ColumnWidth;
707*12c85518Srobert     if (Current.LongestObjCSelectorName == 0)
708*12c85518Srobert       CurrentState.AlignColons = false;
709*12c85518Srobert     else if (MinIndent + Current.LongestObjCSelectorName > FirstColonPos)
710*12c85518Srobert       CurrentState.ColonPos = MinIndent + Current.LongestObjCSelectorName;
711*12c85518Srobert     else
712*12c85518Srobert       CurrentState.ColonPos = FirstColonPos;
713*12c85518Srobert   }
714*12c85518Srobert 
715*12c85518Srobert   // In "AlwaysBreak" or "BlockIndent" mode, enforce wrapping directly after the
716*12c85518Srobert   // parenthesis by disallowing any further line breaks if there is no line
717*12c85518Srobert   // break after the opening parenthesis. Don't break if it doesn't conserve
718*12c85518Srobert   // columns.
719*12c85518Srobert   if ((Style.AlignAfterOpenBracket == FormatStyle::BAS_AlwaysBreak ||
720*12c85518Srobert        Style.AlignAfterOpenBracket == FormatStyle::BAS_BlockIndent) &&
721e5dd7070Spatrick       (Previous.isOneOf(tok::l_paren, TT_TemplateOpener, tok::l_square) ||
722a9ac8606Spatrick        (Previous.is(tok::l_brace) && Previous.isNot(BK_Block) &&
723e5dd7070Spatrick         Style.Cpp11BracedListStyle)) &&
724e5dd7070Spatrick       State.Column > getNewLineColumn(State) &&
725*12c85518Srobert       (!Previous.Previous ||
726*12c85518Srobert        !Previous.Previous->isOneOf(TT_CastRParen, tok::kw_for, tok::kw_while,
727*12c85518Srobert                                    tok::kw_switch)) &&
728e5dd7070Spatrick       // Don't do this for simple (no expressions) one-argument function calls
729e5dd7070Spatrick       // as that feels like needlessly wasting whitespace, e.g.:
730e5dd7070Spatrick       //
731e5dd7070Spatrick       //   caaaaaaaaaaaall(
732e5dd7070Spatrick       //       caaaaaaaaaaaall(
733e5dd7070Spatrick       //           caaaaaaaaaaaall(
734e5dd7070Spatrick       //               caaaaaaaaaaaaaaaaaaaaaaall(aaaaaaaaaaaaaa, aaaaaaaaa))));
735e5dd7070Spatrick       Current.FakeLParens.size() > 0 &&
736*12c85518Srobert       Current.FakeLParens.back() > prec::Unknown) {
737*12c85518Srobert     CurrentState.NoLineBreak = true;
738*12c85518Srobert   }
739e5dd7070Spatrick   if (Previous.is(TT_TemplateString) && Previous.opensScope())
740*12c85518Srobert     CurrentState.NoLineBreak = true;
741e5dd7070Spatrick 
742e5dd7070Spatrick   if (Style.AlignAfterOpenBracket != FormatStyle::BAS_DontAlign &&
743*12c85518Srobert       !CurrentState.IsCSharpGenericTypeConstraint && Previous.opensScope() &&
744*12c85518Srobert       Previous.isNot(TT_ObjCMethodExpr) && Previous.isNot(TT_RequiresClause) &&
745a9ac8606Spatrick       (Current.isNot(TT_LineComment) || Previous.is(BK_BracedInit))) {
746*12c85518Srobert     CurrentState.Indent = State.Column + Spaces;
747*12c85518Srobert     CurrentState.IsAligned = true;
748ec727ea7Spatrick   }
749*12c85518Srobert   if (CurrentState.AvoidBinPacking && startsNextParameter(Current, Style))
750*12c85518Srobert     CurrentState.NoLineBreak = true;
751e5dd7070Spatrick   if (startsSegmentOfBuilderTypeCall(Current) &&
752*12c85518Srobert       State.Column > getNewLineColumn(State)) {
753*12c85518Srobert     CurrentState.ContainsUnwrappedBuilder = true;
754*12c85518Srobert   }
755e5dd7070Spatrick 
756e5dd7070Spatrick   if (Current.is(TT_LambdaArrow) && Style.Language == FormatStyle::LK_Java)
757*12c85518Srobert     CurrentState.NoLineBreak = true;
758e5dd7070Spatrick   if (Current.isMemberAccess() && Previous.is(tok::r_paren) &&
759e5dd7070Spatrick       (Previous.MatchingParen &&
760*12c85518Srobert        (Previous.TotalLength - Previous.MatchingParen->TotalLength > 10))) {
761e5dd7070Spatrick     // If there is a function call with long parameters, break before trailing
762e5dd7070Spatrick     // calls. This prevents things like:
763e5dd7070Spatrick     //   EXPECT_CALL(SomeLongParameter).Times(
764e5dd7070Spatrick     //       2);
765e5dd7070Spatrick     // We don't want to do this for short parameters as they can just be
766e5dd7070Spatrick     // indexes.
767*12c85518Srobert     CurrentState.NoLineBreak = true;
768*12c85518Srobert   }
769e5dd7070Spatrick 
770e5dd7070Spatrick   // Don't allow the RHS of an operator to be split over multiple lines unless
771e5dd7070Spatrick   // there is a line-break right after the operator.
772e5dd7070Spatrick   // Exclude relational operators, as there, it is always more desirable to
773e5dd7070Spatrick   // have the LHS 'left' of the RHS.
774e5dd7070Spatrick   const FormatToken *P = Current.getPreviousNonComment();
775e5dd7070Spatrick   if (!Current.is(tok::comment) && P &&
776e5dd7070Spatrick       (P->isOneOf(TT_BinaryOperator, tok::comma) ||
777e5dd7070Spatrick        (P->is(TT_ConditionalExpr) && P->is(tok::colon))) &&
778e5dd7070Spatrick       !P->isOneOf(TT_OverloadedOperator, TT_CtorInitializerComma) &&
779e5dd7070Spatrick       P->getPrecedence() != prec::Assignment &&
780e5dd7070Spatrick       P->getPrecedence() != prec::Relational &&
781e5dd7070Spatrick       P->getPrecedence() != prec::Spaceship) {
782e5dd7070Spatrick     bool BreakBeforeOperator =
783e5dd7070Spatrick         P->MustBreakBefore || P->is(tok::lessless) ||
784e5dd7070Spatrick         (P->is(TT_BinaryOperator) &&
785e5dd7070Spatrick          Style.BreakBeforeBinaryOperators != FormatStyle::BOS_None) ||
786e5dd7070Spatrick         (P->is(TT_ConditionalExpr) && Style.BreakBeforeTernaryOperators);
787e5dd7070Spatrick     // Don't do this if there are only two operands. In these cases, there is
788e5dd7070Spatrick     // always a nice vertical separation between them and the extra line break
789e5dd7070Spatrick     // does not help.
790e5dd7070Spatrick     bool HasTwoOperands =
791e5dd7070Spatrick         P->OperatorIndex == 0 && !P->NextOperator && !P->is(TT_ConditionalExpr);
792ec727ea7Spatrick     if ((!BreakBeforeOperator &&
793ec727ea7Spatrick          !(HasTwoOperands &&
794ec727ea7Spatrick            Style.AlignOperands != FormatStyle::OAS_DontAlign)) ||
795*12c85518Srobert         (!CurrentState.LastOperatorWrapped && BreakBeforeOperator)) {
796*12c85518Srobert       CurrentState.NoLineBreakInOperand = true;
797*12c85518Srobert     }
798e5dd7070Spatrick   }
799e5dd7070Spatrick 
800e5dd7070Spatrick   State.Column += Spaces;
801e5dd7070Spatrick   if (Current.isNot(tok::comment) && Previous.is(tok::l_paren) &&
802e5dd7070Spatrick       Previous.Previous &&
803e5dd7070Spatrick       (Previous.Previous->is(tok::kw_for) || Previous.Previous->isIf())) {
804e5dd7070Spatrick     // Treat the condition inside an if as if it was a second function
805e5dd7070Spatrick     // parameter, i.e. let nested calls have a continuation indent.
806*12c85518Srobert     CurrentState.LastSpace = State.Column;
807*12c85518Srobert     CurrentState.NestedBlockIndent = State.Column;
808e5dd7070Spatrick   } else if (!Current.isOneOf(tok::comment, tok::caret) &&
809e5dd7070Spatrick              ((Previous.is(tok::comma) &&
810e5dd7070Spatrick                !Previous.is(TT_OverloadedOperator)) ||
811e5dd7070Spatrick               (Previous.is(tok::colon) && Previous.is(TT_ObjCMethodExpr)))) {
812*12c85518Srobert     CurrentState.LastSpace = State.Column;
813e5dd7070Spatrick   } else if (Previous.is(TT_CtorInitializerColon) &&
814*12c85518Srobert              (!Current.isTrailingComment() || Current.NewlinesBefore > 0) &&
815e5dd7070Spatrick              Style.BreakConstructorInitializers ==
816e5dd7070Spatrick                  FormatStyle::BCIS_AfterColon) {
817*12c85518Srobert     CurrentState.Indent = State.Column;
818*12c85518Srobert     CurrentState.LastSpace = State.Column;
819e5dd7070Spatrick   } else if ((Previous.isOneOf(TT_BinaryOperator, TT_ConditionalExpr,
820e5dd7070Spatrick                                TT_CtorInitializerColon)) &&
821e5dd7070Spatrick              ((Previous.getPrecedence() != prec::Assignment &&
822e5dd7070Spatrick                (Previous.isNot(tok::lessless) || Previous.OperatorIndex != 0 ||
823e5dd7070Spatrick                 Previous.NextOperator)) ||
824e5dd7070Spatrick               Current.StartsBinaryExpression)) {
825e5dd7070Spatrick     // Indent relative to the RHS of the expression unless this is a simple
826e5dd7070Spatrick     // assignment without binary expression on the RHS. Also indent relative to
827e5dd7070Spatrick     // unary operators and the colons of constructor initializers.
828e5dd7070Spatrick     if (Style.BreakBeforeBinaryOperators == FormatStyle::BOS_None)
829*12c85518Srobert       CurrentState.LastSpace = State.Column;
830e5dd7070Spatrick   } else if (Previous.is(TT_InheritanceColon)) {
831*12c85518Srobert     CurrentState.Indent = State.Column;
832*12c85518Srobert     CurrentState.LastSpace = State.Column;
833ec727ea7Spatrick   } else if (Current.is(TT_CSharpGenericTypeConstraintColon)) {
834*12c85518Srobert     CurrentState.ColonPos = State.Column;
835e5dd7070Spatrick   } else if (Previous.opensScope()) {
836e5dd7070Spatrick     // If a function has a trailing call, indent all parameters from the
837e5dd7070Spatrick     // opening parenthesis. This avoids confusing indents like:
838e5dd7070Spatrick     //   OuterFunction(InnerFunctionCall( // break
839e5dd7070Spatrick     //       ParameterToInnerFunction))   // break
840e5dd7070Spatrick     //       .SecondInnerFunctionCall();
841e5dd7070Spatrick     if (Previous.MatchingParen) {
842e5dd7070Spatrick       const FormatToken *Next = Previous.MatchingParen->getNextNonComment();
843*12c85518Srobert       if (Next && Next->isMemberAccess() && State.Stack.size() > 1 &&
844*12c85518Srobert           State.Stack[State.Stack.size() - 2].CallContinuation == 0) {
845*12c85518Srobert         CurrentState.LastSpace = State.Column;
846e5dd7070Spatrick       }
847*12c85518Srobert     }
848e5dd7070Spatrick   }
849e5dd7070Spatrick }
850e5dd7070Spatrick 
addTokenOnNewLine(LineState & State,bool DryRun)851e5dd7070Spatrick unsigned ContinuationIndenter::addTokenOnNewLine(LineState &State,
852e5dd7070Spatrick                                                  bool DryRun) {
853e5dd7070Spatrick   FormatToken &Current = *State.NextToken;
854*12c85518Srobert   assert(State.NextToken->Previous);
855e5dd7070Spatrick   const FormatToken &Previous = *State.NextToken->Previous;
856*12c85518Srobert   auto &CurrentState = State.Stack.back();
857e5dd7070Spatrick 
858e5dd7070Spatrick   // Extra penalty that needs to be added because of the way certain line
859e5dd7070Spatrick   // breaks are chosen.
860e5dd7070Spatrick   unsigned Penalty = 0;
861e5dd7070Spatrick 
862e5dd7070Spatrick   const FormatToken *PreviousNonComment = Current.getPreviousNonComment();
863e5dd7070Spatrick   const FormatToken *NextNonComment = Previous.getNextNonComment();
864e5dd7070Spatrick   if (!NextNonComment)
865e5dd7070Spatrick     NextNonComment = &Current;
866e5dd7070Spatrick   // The first line break on any NestingLevel causes an extra penalty in order
867e5dd7070Spatrick   // prefer similar line breaks.
868*12c85518Srobert   if (!CurrentState.ContainsLineBreak)
869e5dd7070Spatrick     Penalty += 15;
870*12c85518Srobert   CurrentState.ContainsLineBreak = true;
871e5dd7070Spatrick 
872e5dd7070Spatrick   Penalty += State.NextToken->SplitPenalty;
873e5dd7070Spatrick 
874e5dd7070Spatrick   // Breaking before the first "<<" is generally not desirable if the LHS is
875e5dd7070Spatrick   // short. Also always add the penalty if the LHS is split over multiple lines
876e5dd7070Spatrick   // to avoid unnecessary line breaks that just work around this penalty.
877*12c85518Srobert   if (NextNonComment->is(tok::lessless) && CurrentState.FirstLessLess == 0 &&
878e5dd7070Spatrick       (State.Column <= Style.ColumnLimit / 3 ||
879*12c85518Srobert        CurrentState.BreakBeforeParameter)) {
880e5dd7070Spatrick     Penalty += Style.PenaltyBreakFirstLessLess;
881*12c85518Srobert   }
882e5dd7070Spatrick 
883e5dd7070Spatrick   State.Column = getNewLineColumn(State);
884e5dd7070Spatrick 
885a9ac8606Spatrick   // Add Penalty proportional to amount of whitespace away from FirstColumn
886a9ac8606Spatrick   // This tends to penalize several lines that are far-right indented,
887a9ac8606Spatrick   // and prefers a line-break prior to such a block, e.g:
888a9ac8606Spatrick   //
889a9ac8606Spatrick   // Constructor() :
890a9ac8606Spatrick   //   member(value), looooooooooooooooong_member(
891a9ac8606Spatrick   //                      looooooooooong_call(param_1, param_2, param_3))
892a9ac8606Spatrick   // would then become
893a9ac8606Spatrick   // Constructor() :
894a9ac8606Spatrick   //   member(value),
895a9ac8606Spatrick   //   looooooooooooooooong_member(
896a9ac8606Spatrick   //       looooooooooong_call(param_1, param_2, param_3))
897*12c85518Srobert   if (State.Column > State.FirstIndent) {
898a9ac8606Spatrick     Penalty +=
899a9ac8606Spatrick         Style.PenaltyIndentedWhitespace * (State.Column - State.FirstIndent);
900*12c85518Srobert   }
901a9ac8606Spatrick 
902e5dd7070Spatrick   // Indent nested blocks relative to this column, unless in a very specific
903e5dd7070Spatrick   // JavaScript special case where:
904e5dd7070Spatrick   //
905e5dd7070Spatrick   //   var loooooong_name =
906e5dd7070Spatrick   //       function() {
907e5dd7070Spatrick   //     // code
908e5dd7070Spatrick   //   }
909e5dd7070Spatrick   //
910e5dd7070Spatrick   // is common and should be formatted like a free-standing function. The same
911e5dd7070Spatrick   // goes for wrapping before the lambda return type arrow.
912e5dd7070Spatrick   if (!Current.is(TT_LambdaArrow) &&
913*12c85518Srobert       (!Style.isJavaScript() || Current.NestingLevel != 0 ||
914*12c85518Srobert        !PreviousNonComment || !PreviousNonComment->is(tok::equal) ||
915*12c85518Srobert        !Current.isOneOf(Keywords.kw_async, Keywords.kw_function))) {
916*12c85518Srobert     CurrentState.NestedBlockIndent = State.Column;
917*12c85518Srobert   }
918e5dd7070Spatrick 
919e5dd7070Spatrick   if (NextNonComment->isMemberAccess()) {
920*12c85518Srobert     if (CurrentState.CallContinuation == 0)
921*12c85518Srobert       CurrentState.CallContinuation = State.Column;
922e5dd7070Spatrick   } else if (NextNonComment->is(TT_SelectorName)) {
923*12c85518Srobert     if (!CurrentState.ObjCSelectorNameFound) {
924e5dd7070Spatrick       if (NextNonComment->LongestObjCSelectorName == 0) {
925*12c85518Srobert         CurrentState.AlignColons = false;
926e5dd7070Spatrick       } else {
927*12c85518Srobert         CurrentState.ColonPos =
928e5dd7070Spatrick             (shouldIndentWrappedSelectorName(Style, State.Line->Type)
929*12c85518Srobert                  ? std::max(CurrentState.Indent,
930e5dd7070Spatrick                             State.FirstIndent + Style.ContinuationIndentWidth)
931*12c85518Srobert                  : CurrentState.Indent) +
932e5dd7070Spatrick             std::max(NextNonComment->LongestObjCSelectorName,
933e5dd7070Spatrick                      NextNonComment->ColumnWidth);
934e5dd7070Spatrick       }
935*12c85518Srobert     } else if (CurrentState.AlignColons &&
936*12c85518Srobert                CurrentState.ColonPos <= NextNonComment->ColumnWidth) {
937*12c85518Srobert       CurrentState.ColonPos = State.Column + NextNonComment->ColumnWidth;
938e5dd7070Spatrick     }
939e5dd7070Spatrick   } else if (PreviousNonComment && PreviousNonComment->is(tok::colon) &&
940e5dd7070Spatrick              PreviousNonComment->isOneOf(TT_ObjCMethodExpr, TT_DictLiteral)) {
941e5dd7070Spatrick     // FIXME: This is hacky, find a better way. The problem is that in an ObjC
942e5dd7070Spatrick     // method expression, the block should be aligned to the line starting it,
943e5dd7070Spatrick     // e.g.:
944e5dd7070Spatrick     //   [aaaaaaaaaaaaaaa aaaaaaaaa: \\ break for some reason
945e5dd7070Spatrick     //                        ^(int *i) {
946e5dd7070Spatrick     //                            // ...
947e5dd7070Spatrick     //                        }];
948e5dd7070Spatrick     // Thus, we set LastSpace of the next higher NestingLevel, to which we move
949e5dd7070Spatrick     // when we consume all of the "}"'s FakeRParens at the "{".
950*12c85518Srobert     if (State.Stack.size() > 1) {
951e5dd7070Spatrick       State.Stack[State.Stack.size() - 2].LastSpace =
952*12c85518Srobert           std::max(CurrentState.LastSpace, CurrentState.Indent) +
953e5dd7070Spatrick           Style.ContinuationIndentWidth;
954e5dd7070Spatrick     }
955*12c85518Srobert   }
956e5dd7070Spatrick 
957e5dd7070Spatrick   if ((PreviousNonComment &&
958e5dd7070Spatrick        PreviousNonComment->isOneOf(tok::comma, tok::semi) &&
959*12c85518Srobert        !CurrentState.AvoidBinPacking) ||
960*12c85518Srobert       Previous.is(TT_BinaryOperator)) {
961*12c85518Srobert     CurrentState.BreakBeforeParameter = false;
962*12c85518Srobert   }
963e5dd7070Spatrick   if (PreviousNonComment &&
964*12c85518Srobert       (PreviousNonComment->isOneOf(TT_TemplateCloser, TT_JavaAnnotation) ||
965*12c85518Srobert        PreviousNonComment->ClosesRequiresClause) &&
966*12c85518Srobert       Current.NestingLevel == 0) {
967*12c85518Srobert     CurrentState.BreakBeforeParameter = false;
968*12c85518Srobert   }
969e5dd7070Spatrick   if (NextNonComment->is(tok::question) ||
970*12c85518Srobert       (PreviousNonComment && PreviousNonComment->is(tok::question))) {
971*12c85518Srobert     CurrentState.BreakBeforeParameter = true;
972*12c85518Srobert   }
973e5dd7070Spatrick   if (Current.is(TT_BinaryOperator) && Current.CanBreakBefore)
974*12c85518Srobert     CurrentState.BreakBeforeParameter = false;
975e5dd7070Spatrick 
976e5dd7070Spatrick   if (!DryRun) {
977e5dd7070Spatrick     unsigned MaxEmptyLinesToKeep = Style.MaxEmptyLinesToKeep + 1;
978e5dd7070Spatrick     if (Current.is(tok::r_brace) && Current.MatchingParen &&
979e5dd7070Spatrick         // Only strip trailing empty lines for l_braces that have children, i.e.
980e5dd7070Spatrick         // for function expressions (lambdas, arrows, etc).
981e5dd7070Spatrick         !Current.MatchingParen->Children.empty()) {
982e5dd7070Spatrick       // lambdas and arrow functions are expressions, thus their r_brace is not
983e5dd7070Spatrick       // on its own line, and thus not covered by UnwrappedLineFormatter's logic
984e5dd7070Spatrick       // about removing empty lines on closing blocks. Special case them here.
985e5dd7070Spatrick       MaxEmptyLinesToKeep = 1;
986e5dd7070Spatrick     }
987e5dd7070Spatrick     unsigned Newlines =
988e5dd7070Spatrick         std::max(1u, std::min(Current.NewlinesBefore, MaxEmptyLinesToKeep));
989e5dd7070Spatrick     bool ContinuePPDirective =
990e5dd7070Spatrick         State.Line->InPPDirective && State.Line->Type != LT_ImportStatement;
991e5dd7070Spatrick     Whitespaces.replaceWhitespace(Current, Newlines, State.Column, State.Column,
992*12c85518Srobert                                   CurrentState.IsAligned, ContinuePPDirective);
993e5dd7070Spatrick   }
994e5dd7070Spatrick 
995e5dd7070Spatrick   if (!Current.isTrailingComment())
996*12c85518Srobert     CurrentState.LastSpace = State.Column;
997*12c85518Srobert   if (Current.is(tok::lessless)) {
998e5dd7070Spatrick     // If we are breaking before a "<<", we always want to indent relative to
999e5dd7070Spatrick     // RHS. This is necessary only for "<<", as we special-case it and don't
1000e5dd7070Spatrick     // always indent relative to the RHS.
1001*12c85518Srobert     CurrentState.LastSpace += 3; // 3 -> width of "<< ".
1002*12c85518Srobert   }
1003e5dd7070Spatrick 
1004e5dd7070Spatrick   State.StartOfLineLevel = Current.NestingLevel;
1005e5dd7070Spatrick   State.LowestLevelOnLine = Current.NestingLevel;
1006e5dd7070Spatrick 
1007e5dd7070Spatrick   // Any break on this level means that the parent level has been broken
1008e5dd7070Spatrick   // and we need to avoid bin packing there.
1009e5dd7070Spatrick   bool NestedBlockSpecialCase =
1010ec727ea7Spatrick       (!Style.isCpp() && Current.is(tok::r_brace) && State.Stack.size() > 1 &&
1011ec727ea7Spatrick        State.Stack[State.Stack.size() - 2].NestedBlockInlined) ||
1012ec727ea7Spatrick       (Style.Language == FormatStyle::LK_ObjC && Current.is(tok::r_brace) &&
1013ec727ea7Spatrick        State.Stack.size() > 1 && !Style.ObjCBreakBeforeNestedBlockParam);
1014*12c85518Srobert   // Do not force parameter break for statements with requires expressions.
1015*12c85518Srobert   NestedBlockSpecialCase =
1016*12c85518Srobert       NestedBlockSpecialCase ||
1017*12c85518Srobert       (Current.MatchingParen &&
1018*12c85518Srobert        Current.MatchingParen->is(TT_RequiresExpressionLBrace));
1019e5dd7070Spatrick   if (!NestedBlockSpecialCase)
1020*12c85518Srobert     for (ParenState &PState : llvm::drop_end(State.Stack))
1021*12c85518Srobert       PState.BreakBeforeParameter = true;
1022e5dd7070Spatrick 
1023e5dd7070Spatrick   if (PreviousNonComment &&
1024e5dd7070Spatrick       !PreviousNonComment->isOneOf(tok::comma, tok::colon, tok::semi) &&
1025*12c85518Srobert       ((PreviousNonComment->isNot(TT_TemplateCloser) &&
1026*12c85518Srobert         !PreviousNonComment->ClosesRequiresClause) ||
1027e5dd7070Spatrick        Current.NestingLevel != 0) &&
1028e5dd7070Spatrick       !PreviousNonComment->isOneOf(
1029e5dd7070Spatrick           TT_BinaryOperator, TT_FunctionAnnotationRParen, TT_JavaAnnotation,
1030e5dd7070Spatrick           TT_LeadingJavaAnnotation) &&
1031*12c85518Srobert       Current.isNot(TT_BinaryOperator) && !PreviousNonComment->opensScope()) {
1032*12c85518Srobert     CurrentState.BreakBeforeParameter = true;
1033*12c85518Srobert   }
1034e5dd7070Spatrick 
1035e5dd7070Spatrick   // If we break after { or the [ of an array initializer, we should also break
1036e5dd7070Spatrick   // before the corresponding } or ].
1037e5dd7070Spatrick   if (PreviousNonComment &&
1038e5dd7070Spatrick       (PreviousNonComment->isOneOf(tok::l_brace, TT_ArrayInitializerLSquare) ||
1039*12c85518Srobert        opensProtoMessageField(*PreviousNonComment, Style))) {
1040*12c85518Srobert     CurrentState.BreakBeforeClosingBrace = true;
1041*12c85518Srobert   }
1042e5dd7070Spatrick 
1043*12c85518Srobert   if (PreviousNonComment && PreviousNonComment->is(tok::l_paren)) {
1044*12c85518Srobert     CurrentState.BreakBeforeClosingParen =
1045*12c85518Srobert         Style.AlignAfterOpenBracket == FormatStyle::BAS_BlockIndent;
1046*12c85518Srobert   }
1047*12c85518Srobert 
1048*12c85518Srobert   if (CurrentState.AvoidBinPacking) {
1049e5dd7070Spatrick     // If we are breaking after '(', '{', '<', or this is the break after a ':'
1050e5dd7070Spatrick     // to start a member initializater list in a constructor, this should not
1051e5dd7070Spatrick     // be considered bin packing unless the relevant AllowAll option is false or
1052e5dd7070Spatrick     // this is a dict/object literal.
1053e5dd7070Spatrick     bool PreviousIsBreakingCtorInitializerColon =
1054*12c85518Srobert         PreviousNonComment && PreviousNonComment->is(TT_CtorInitializerColon) &&
1055e5dd7070Spatrick         Style.BreakConstructorInitializers == FormatStyle::BCIS_AfterColon;
1056e5dd7070Spatrick     if (!(Previous.isOneOf(tok::l_paren, tok::l_brace, TT_BinaryOperator) ||
1057e5dd7070Spatrick           PreviousIsBreakingCtorInitializerColon) ||
1058e5dd7070Spatrick         (!Style.AllowAllParametersOfDeclarationOnNextLine &&
1059e5dd7070Spatrick          State.Line->MustBeDeclaration) ||
1060e5dd7070Spatrick         (!Style.AllowAllArgumentsOnNextLine &&
1061e5dd7070Spatrick          !State.Line->MustBeDeclaration) ||
1062*12c85518Srobert         (Style.PackConstructorInitializers != FormatStyle::PCIS_NextLine &&
1063e5dd7070Spatrick          PreviousIsBreakingCtorInitializerColon) ||
1064*12c85518Srobert         Previous.is(TT_DictLiteral)) {
1065*12c85518Srobert       CurrentState.BreakBeforeParameter = true;
1066*12c85518Srobert     }
1067e5dd7070Spatrick 
1068e5dd7070Spatrick     // If we are breaking after a ':' to start a member initializer list,
1069e5dd7070Spatrick     // and we allow all arguments on the next line, we should not break
1070e5dd7070Spatrick     // before the next parameter.
1071e5dd7070Spatrick     if (PreviousIsBreakingCtorInitializerColon &&
1072*12c85518Srobert         Style.PackConstructorInitializers == FormatStyle::PCIS_NextLine) {
1073*12c85518Srobert       CurrentState.BreakBeforeParameter = false;
1074*12c85518Srobert     }
1075e5dd7070Spatrick   }
1076e5dd7070Spatrick 
1077e5dd7070Spatrick   return Penalty;
1078e5dd7070Spatrick }
1079e5dd7070Spatrick 
getNewLineColumn(const LineState & State)1080e5dd7070Spatrick unsigned ContinuationIndenter::getNewLineColumn(const LineState &State) {
1081e5dd7070Spatrick   if (!State.NextToken || !State.NextToken->Previous)
1082e5dd7070Spatrick     return 0;
1083ec727ea7Spatrick 
1084e5dd7070Spatrick   FormatToken &Current = *State.NextToken;
1085*12c85518Srobert   const auto &CurrentState = State.Stack.back();
1086ec727ea7Spatrick 
1087*12c85518Srobert   if (CurrentState.IsCSharpGenericTypeConstraint &&
1088*12c85518Srobert       Current.isNot(TT_CSharpGenericTypeConstraint)) {
1089*12c85518Srobert     return CurrentState.ColonPos + 2;
1090*12c85518Srobert   }
1091ec727ea7Spatrick 
1092e5dd7070Spatrick   const FormatToken &Previous = *Current.Previous;
1093e5dd7070Spatrick   // If we are continuing an expression, we want to use the continuation indent.
1094e5dd7070Spatrick   unsigned ContinuationIndent =
1095*12c85518Srobert       std::max(CurrentState.LastSpace, CurrentState.Indent) +
1096e5dd7070Spatrick       Style.ContinuationIndentWidth;
1097e5dd7070Spatrick   const FormatToken *PreviousNonComment = Current.getPreviousNonComment();
1098e5dd7070Spatrick   const FormatToken *NextNonComment = Previous.getNextNonComment();
1099e5dd7070Spatrick   if (!NextNonComment)
1100e5dd7070Spatrick     NextNonComment = &Current;
1101e5dd7070Spatrick 
1102e5dd7070Spatrick   // Java specific bits.
1103e5dd7070Spatrick   if (Style.Language == FormatStyle::LK_Java &&
1104*12c85518Srobert       Current.isOneOf(Keywords.kw_implements, Keywords.kw_extends)) {
1105*12c85518Srobert     return std::max(CurrentState.LastSpace,
1106*12c85518Srobert                     CurrentState.Indent + Style.ContinuationIndentWidth);
1107*12c85518Srobert   }
1108e5dd7070Spatrick 
1109*12c85518Srobert   // After a goto label. Usually labels are on separate lines. However
1110*12c85518Srobert   // for Verilog the labels may be only recognized by the annotator and
1111*12c85518Srobert   // thus are on the same line as the current token.
1112*12c85518Srobert   if ((Style.isVerilog() && Keywords.isVerilogEndOfLabel(Previous)) ||
1113*12c85518Srobert       (Style.BreakBeforeBraces == FormatStyle::BS_Whitesmiths &&
1114*12c85518Srobert        State.Line->First->is(tok::kw_enum))) {
1115e5dd7070Spatrick     return (Style.IndentWidth * State.Line->First->IndentLevel) +
1116e5dd7070Spatrick            Style.IndentWidth;
1117*12c85518Srobert   }
1118e5dd7070Spatrick 
1119a9ac8606Spatrick   if (NextNonComment->is(tok::l_brace) && NextNonComment->is(BK_Block))
1120*12c85518Srobert     return Current.NestingLevel == 0 ? State.FirstIndent : CurrentState.Indent;
1121e5dd7070Spatrick   if ((Current.isOneOf(tok::r_brace, tok::r_square) ||
1122e5dd7070Spatrick        (Current.is(tok::greater) &&
1123e5dd7070Spatrick         (Style.Language == FormatStyle::LK_Proto ||
1124e5dd7070Spatrick          Style.Language == FormatStyle::LK_TextProto))) &&
1125e5dd7070Spatrick       State.Stack.size() > 1) {
1126e5dd7070Spatrick     if (Current.closesBlockOrBlockTypeList(Style))
1127e5dd7070Spatrick       return State.Stack[State.Stack.size() - 2].NestedBlockIndent;
1128a9ac8606Spatrick     if (Current.MatchingParen && Current.MatchingParen->is(BK_BracedInit))
1129e5dd7070Spatrick       return State.Stack[State.Stack.size() - 2].LastSpace;
1130e5dd7070Spatrick     return State.FirstIndent;
1131e5dd7070Spatrick   }
1132e5dd7070Spatrick   // Indent a closing parenthesis at the previous level if followed by a semi,
1133e5dd7070Spatrick   // const, or opening brace. This allows indentations such as:
1134e5dd7070Spatrick   //     foo(
1135e5dd7070Spatrick   //       a,
1136e5dd7070Spatrick   //     );
1137e5dd7070Spatrick   //     int Foo::getter(
1138e5dd7070Spatrick   //         //
1139e5dd7070Spatrick   //     ) const {
1140e5dd7070Spatrick   //       return foo;
1141e5dd7070Spatrick   //     }
1142e5dd7070Spatrick   //     function foo(
1143e5dd7070Spatrick   //       a,
1144e5dd7070Spatrick   //     ) {
1145e5dd7070Spatrick   //       code(); //
1146e5dd7070Spatrick   //     }
1147e5dd7070Spatrick   if (Current.is(tok::r_paren) && State.Stack.size() > 1 &&
1148e5dd7070Spatrick       (!Current.Next ||
1149*12c85518Srobert        Current.Next->isOneOf(tok::semi, tok::kw_const, tok::l_brace))) {
1150e5dd7070Spatrick     return State.Stack[State.Stack.size() - 2].LastSpace;
1151*12c85518Srobert   }
1152*12c85518Srobert   if (Style.AlignAfterOpenBracket == FormatStyle::BAS_BlockIndent &&
1153*12c85518Srobert       Current.is(tok::r_paren) && State.Stack.size() > 1) {
1154*12c85518Srobert     return State.Stack[State.Stack.size() - 2].LastSpace;
1155*12c85518Srobert   }
1156e5dd7070Spatrick   if (NextNonComment->is(TT_TemplateString) && NextNonComment->closesScope())
1157e5dd7070Spatrick     return State.Stack[State.Stack.size() - 2].LastSpace;
1158e5dd7070Spatrick   if (Current.is(tok::identifier) && Current.Next &&
1159e5dd7070Spatrick       (Current.Next->is(TT_DictLiteral) ||
1160e5dd7070Spatrick        ((Style.Language == FormatStyle::LK_Proto ||
1161e5dd7070Spatrick          Style.Language == FormatStyle::LK_TextProto) &&
1162*12c85518Srobert         Current.Next->isOneOf(tok::less, tok::l_brace)))) {
1163*12c85518Srobert     return CurrentState.Indent;
1164*12c85518Srobert   }
1165e5dd7070Spatrick   if (NextNonComment->is(TT_ObjCStringLiteral) &&
1166*12c85518Srobert       State.StartOfStringLiteral != 0) {
1167e5dd7070Spatrick     return State.StartOfStringLiteral - 1;
1168*12c85518Srobert   }
1169e5dd7070Spatrick   if (NextNonComment->isStringLiteral() && State.StartOfStringLiteral != 0)
1170e5dd7070Spatrick     return State.StartOfStringLiteral;
1171*12c85518Srobert   if (NextNonComment->is(tok::lessless) && CurrentState.FirstLessLess != 0)
1172*12c85518Srobert     return CurrentState.FirstLessLess;
1173e5dd7070Spatrick   if (NextNonComment->isMemberAccess()) {
1174*12c85518Srobert     if (CurrentState.CallContinuation == 0)
1175e5dd7070Spatrick       return ContinuationIndent;
1176*12c85518Srobert     return CurrentState.CallContinuation;
1177e5dd7070Spatrick   }
1178*12c85518Srobert   if (CurrentState.QuestionColumn != 0 &&
1179e5dd7070Spatrick       ((NextNonComment->is(tok::colon) &&
1180e5dd7070Spatrick         NextNonComment->is(TT_ConditionalExpr)) ||
1181ec727ea7Spatrick        Previous.is(TT_ConditionalExpr))) {
1182ec727ea7Spatrick     if (((NextNonComment->is(tok::colon) && NextNonComment->Next &&
1183ec727ea7Spatrick           !NextNonComment->Next->FakeLParens.empty() &&
1184ec727ea7Spatrick           NextNonComment->Next->FakeLParens.back() == prec::Conditional) ||
1185ec727ea7Spatrick          (Previous.is(tok::colon) && !Current.FakeLParens.empty() &&
1186ec727ea7Spatrick           Current.FakeLParens.back() == prec::Conditional)) &&
1187*12c85518Srobert         !CurrentState.IsWrappedConditional) {
1188ec727ea7Spatrick       // NOTE: we may tweak this slightly:
1189ec727ea7Spatrick       //    * not remove the 'lead' ContinuationIndentWidth
1190ec727ea7Spatrick       //    * always un-indent by the operator when
1191ec727ea7Spatrick       //    BreakBeforeTernaryOperators=true
1192*12c85518Srobert       unsigned Indent = CurrentState.Indent;
1193*12c85518Srobert       if (Style.AlignOperands != FormatStyle::OAS_DontAlign)
1194ec727ea7Spatrick         Indent -= Style.ContinuationIndentWidth;
1195*12c85518Srobert       if (Style.BreakBeforeTernaryOperators && CurrentState.UnindentOperator)
1196ec727ea7Spatrick         Indent -= 2;
1197ec727ea7Spatrick       return Indent;
1198ec727ea7Spatrick     }
1199*12c85518Srobert     return CurrentState.QuestionColumn;
1200ec727ea7Spatrick   }
1201*12c85518Srobert   if (Previous.is(tok::comma) && CurrentState.VariablePos != 0)
1202*12c85518Srobert     return CurrentState.VariablePos;
1203*12c85518Srobert   if (Current.is(TT_RequiresClause)) {
1204*12c85518Srobert     if (Style.IndentRequiresClause)
1205*12c85518Srobert       return CurrentState.Indent + Style.IndentWidth;
1206*12c85518Srobert     switch (Style.RequiresClausePosition) {
1207*12c85518Srobert     case FormatStyle::RCPS_OwnLine:
1208*12c85518Srobert     case FormatStyle::RCPS_WithFollowing:
1209*12c85518Srobert       return CurrentState.Indent;
1210*12c85518Srobert     default:
1211*12c85518Srobert       break;
1212*12c85518Srobert     }
1213*12c85518Srobert   }
1214*12c85518Srobert   if (NextNonComment->isOneOf(TT_CtorInitializerColon, TT_InheritanceColon,
1215*12c85518Srobert                               TT_InheritanceComma)) {
1216*12c85518Srobert     return State.FirstIndent + Style.ConstructorInitializerIndentWidth;
1217*12c85518Srobert   }
1218e5dd7070Spatrick   if ((PreviousNonComment &&
1219e5dd7070Spatrick        (PreviousNonComment->ClosesTemplateDeclaration ||
1220*12c85518Srobert         PreviousNonComment->ClosesRequiresClause ||
1221e5dd7070Spatrick         PreviousNonComment->isOneOf(
1222e5dd7070Spatrick             TT_AttributeParen, TT_AttributeSquare, TT_FunctionAnnotationRParen,
1223e5dd7070Spatrick             TT_JavaAnnotation, TT_LeadingJavaAnnotation))) ||
1224e5dd7070Spatrick       (!Style.IndentWrappedFunctionNames &&
1225*12c85518Srobert        NextNonComment->isOneOf(tok::kw_operator, TT_FunctionDeclarationName))) {
1226*12c85518Srobert     return std::max(CurrentState.LastSpace, CurrentState.Indent);
1227*12c85518Srobert   }
1228e5dd7070Spatrick   if (NextNonComment->is(TT_SelectorName)) {
1229*12c85518Srobert     if (!CurrentState.ObjCSelectorNameFound) {
1230*12c85518Srobert       unsigned MinIndent = CurrentState.Indent;
1231*12c85518Srobert       if (shouldIndentWrappedSelectorName(Style, State.Line->Type)) {
1232e5dd7070Spatrick         MinIndent = std::max(MinIndent,
1233e5dd7070Spatrick                              State.FirstIndent + Style.ContinuationIndentWidth);
1234*12c85518Srobert       }
1235e5dd7070Spatrick       // If LongestObjCSelectorName is 0, we are indenting the first
1236e5dd7070Spatrick       // part of an ObjC selector (or a selector component which is
1237e5dd7070Spatrick       // not colon-aligned due to block formatting).
1238e5dd7070Spatrick       //
1239e5dd7070Spatrick       // Otherwise, we are indenting a subsequent part of an ObjC
1240e5dd7070Spatrick       // selector which should be colon-aligned to the longest
1241e5dd7070Spatrick       // component of the ObjC selector.
1242e5dd7070Spatrick       //
1243e5dd7070Spatrick       // In either case, we want to respect Style.IndentWrappedFunctionNames.
1244e5dd7070Spatrick       return MinIndent +
1245e5dd7070Spatrick              std::max(NextNonComment->LongestObjCSelectorName,
1246e5dd7070Spatrick                       NextNonComment->ColumnWidth) -
1247e5dd7070Spatrick              NextNonComment->ColumnWidth;
1248e5dd7070Spatrick     }
1249*12c85518Srobert     if (!CurrentState.AlignColons)
1250*12c85518Srobert       return CurrentState.Indent;
1251*12c85518Srobert     if (CurrentState.ColonPos > NextNonComment->ColumnWidth)
1252*12c85518Srobert       return CurrentState.ColonPos - NextNonComment->ColumnWidth;
1253*12c85518Srobert     return CurrentState.Indent;
1254e5dd7070Spatrick   }
1255e5dd7070Spatrick   if (NextNonComment->is(tok::colon) && NextNonComment->is(TT_ObjCMethodExpr))
1256*12c85518Srobert     return CurrentState.ColonPos;
1257e5dd7070Spatrick   if (NextNonComment->is(TT_ArraySubscriptLSquare)) {
1258*12c85518Srobert     if (CurrentState.StartOfArraySubscripts != 0) {
1259*12c85518Srobert       return CurrentState.StartOfArraySubscripts;
1260*12c85518Srobert     } else if (Style.isCSharp()) { // C# allows `["key"] = value` inside object
1261ec727ea7Spatrick                                    // initializers.
1262*12c85518Srobert       return CurrentState.Indent;
1263*12c85518Srobert     }
1264e5dd7070Spatrick     return ContinuationIndent;
1265e5dd7070Spatrick   }
1266e5dd7070Spatrick 
1267*12c85518Srobert   if (State.Line->InPragmaDirective)
1268*12c85518Srobert     return CurrentState.Indent + Style.ContinuationIndentWidth;
1269*12c85518Srobert 
1270e5dd7070Spatrick   // This ensure that we correctly format ObjC methods calls without inputs,
1271e5dd7070Spatrick   // i.e. where the last element isn't selector like: [callee method];
1272e5dd7070Spatrick   if (NextNonComment->is(tok::identifier) && NextNonComment->FakeRParens == 0 &&
1273*12c85518Srobert       NextNonComment->Next && NextNonComment->Next->is(TT_ObjCMethodExpr)) {
1274*12c85518Srobert     return CurrentState.Indent;
1275*12c85518Srobert   }
1276e5dd7070Spatrick 
1277e5dd7070Spatrick   if (NextNonComment->isOneOf(TT_StartOfName, TT_PointerOrReference) ||
1278*12c85518Srobert       Previous.isOneOf(tok::coloncolon, tok::equal, TT_JsTypeColon)) {
1279e5dd7070Spatrick     return ContinuationIndent;
1280*12c85518Srobert   }
1281e5dd7070Spatrick   if (PreviousNonComment && PreviousNonComment->is(tok::colon) &&
1282*12c85518Srobert       PreviousNonComment->isOneOf(TT_ObjCMethodExpr, TT_DictLiteral)) {
1283e5dd7070Spatrick     return ContinuationIndent;
1284*12c85518Srobert   }
1285e5dd7070Spatrick   if (NextNonComment->is(TT_CtorInitializerComma))
1286*12c85518Srobert     return CurrentState.Indent;
1287e5dd7070Spatrick   if (PreviousNonComment && PreviousNonComment->is(TT_CtorInitializerColon) &&
1288*12c85518Srobert       Style.BreakConstructorInitializers == FormatStyle::BCIS_AfterColon) {
1289*12c85518Srobert     return CurrentState.Indent;
1290*12c85518Srobert   }
1291e5dd7070Spatrick   if (PreviousNonComment && PreviousNonComment->is(TT_InheritanceColon) &&
1292*12c85518Srobert       Style.BreakInheritanceList == FormatStyle::BILS_AfterColon) {
1293*12c85518Srobert     return CurrentState.Indent;
1294*12c85518Srobert   }
1295e5dd7070Spatrick   if (Previous.is(tok::r_paren) && !Current.isBinaryOperator() &&
1296*12c85518Srobert       !Current.isOneOf(tok::colon, tok::comment)) {
1297e5dd7070Spatrick     return ContinuationIndent;
1298*12c85518Srobert   }
1299e5dd7070Spatrick   if (Current.is(TT_ProtoExtensionLSquare))
1300*12c85518Srobert     return CurrentState.Indent;
1301*12c85518Srobert   if (Current.isBinaryOperator() && CurrentState.UnindentOperator) {
1302*12c85518Srobert     return CurrentState.Indent - Current.Tok.getLength() -
1303ec727ea7Spatrick            Current.SpacesRequiredBefore;
1304*12c85518Srobert   }
1305ec727ea7Spatrick   if (Current.isOneOf(tok::comment, TT_BlockComment, TT_LineComment) &&
1306*12c85518Srobert       NextNonComment->isBinaryOperator() && CurrentState.UnindentOperator) {
1307*12c85518Srobert     return CurrentState.Indent - NextNonComment->Tok.getLength() -
1308ec727ea7Spatrick            NextNonComment->SpacesRequiredBefore;
1309*12c85518Srobert   }
1310*12c85518Srobert   if (CurrentState.Indent == State.FirstIndent && PreviousNonComment &&
1311*12c85518Srobert       !PreviousNonComment->isOneOf(tok::r_brace, TT_CtorInitializerComma)) {
1312e5dd7070Spatrick     // Ensure that we fall back to the continuation indent width instead of
1313e5dd7070Spatrick     // just flushing continuations left.
1314*12c85518Srobert     return CurrentState.Indent + Style.ContinuationIndentWidth;
1315*12c85518Srobert   }
1316*12c85518Srobert   return CurrentState.Indent;
1317e5dd7070Spatrick }
1318e5dd7070Spatrick 
hasNestedBlockInlined(const FormatToken * Previous,const FormatToken & Current,const FormatStyle & Style)1319ec727ea7Spatrick static bool hasNestedBlockInlined(const FormatToken *Previous,
1320ec727ea7Spatrick                                   const FormatToken &Current,
1321ec727ea7Spatrick                                   const FormatStyle &Style) {
1322ec727ea7Spatrick   if (Previous->isNot(tok::l_paren))
1323ec727ea7Spatrick     return true;
1324ec727ea7Spatrick   if (Previous->ParameterCount > 1)
1325ec727ea7Spatrick     return true;
1326ec727ea7Spatrick 
1327*12c85518Srobert   // Also a nested block if contains a lambda inside function with 1 parameter.
1328*12c85518Srobert   return Style.BraceWrapping.BeforeLambdaBody && Current.is(TT_LambdaLSquare);
1329ec727ea7Spatrick }
1330ec727ea7Spatrick 
moveStateToNextToken(LineState & State,bool DryRun,bool Newline)1331e5dd7070Spatrick unsigned ContinuationIndenter::moveStateToNextToken(LineState &State,
1332e5dd7070Spatrick                                                     bool DryRun, bool Newline) {
1333e5dd7070Spatrick   assert(State.Stack.size());
1334e5dd7070Spatrick   const FormatToken &Current = *State.NextToken;
1335*12c85518Srobert   auto &CurrentState = State.Stack.back();
1336e5dd7070Spatrick 
1337ec727ea7Spatrick   if (Current.is(TT_CSharpGenericTypeConstraint))
1338*12c85518Srobert     CurrentState.IsCSharpGenericTypeConstraint = true;
1339e5dd7070Spatrick   if (Current.isOneOf(tok::comma, TT_BinaryOperator))
1340*12c85518Srobert     CurrentState.NoLineBreakInOperand = false;
1341ec727ea7Spatrick   if (Current.isOneOf(TT_InheritanceColon, TT_CSharpGenericTypeConstraintColon))
1342*12c85518Srobert     CurrentState.AvoidBinPacking = true;
1343e5dd7070Spatrick   if (Current.is(tok::lessless) && Current.isNot(TT_OverloadedOperator)) {
1344*12c85518Srobert     if (CurrentState.FirstLessLess == 0)
1345*12c85518Srobert       CurrentState.FirstLessLess = State.Column;
1346e5dd7070Spatrick     else
1347*12c85518Srobert       CurrentState.LastOperatorWrapped = Newline;
1348e5dd7070Spatrick   }
1349e5dd7070Spatrick   if (Current.is(TT_BinaryOperator) && Current.isNot(tok::lessless))
1350*12c85518Srobert     CurrentState.LastOperatorWrapped = Newline;
1351e5dd7070Spatrick   if (Current.is(TT_ConditionalExpr) && Current.Previous &&
1352*12c85518Srobert       !Current.Previous->is(TT_ConditionalExpr)) {
1353*12c85518Srobert     CurrentState.LastOperatorWrapped = Newline;
1354*12c85518Srobert   }
1355e5dd7070Spatrick   if (Current.is(TT_ArraySubscriptLSquare) &&
1356*12c85518Srobert       CurrentState.StartOfArraySubscripts == 0) {
1357*12c85518Srobert     CurrentState.StartOfArraySubscripts = State.Column;
1358*12c85518Srobert   }
1359*12c85518Srobert 
1360*12c85518Srobert   auto IsWrappedConditional = [](const FormatToken &Tok) {
1361*12c85518Srobert     if (!(Tok.is(TT_ConditionalExpr) && Tok.is(tok::question)))
1362*12c85518Srobert       return false;
1363*12c85518Srobert     if (Tok.MustBreakBefore)
1364*12c85518Srobert       return true;
1365*12c85518Srobert 
1366*12c85518Srobert     const FormatToken *Next = Tok.getNextNonComment();
1367*12c85518Srobert     return Next && Next->MustBreakBefore;
1368*12c85518Srobert   };
1369*12c85518Srobert   if (IsWrappedConditional(Current))
1370*12c85518Srobert     CurrentState.IsWrappedConditional = true;
1371e5dd7070Spatrick   if (Style.BreakBeforeTernaryOperators && Current.is(tok::question))
1372*12c85518Srobert     CurrentState.QuestionColumn = State.Column;
1373e5dd7070Spatrick   if (!Style.BreakBeforeTernaryOperators && Current.isNot(tok::colon)) {
1374e5dd7070Spatrick     const FormatToken *Previous = Current.Previous;
1375e5dd7070Spatrick     while (Previous && Previous->isTrailingComment())
1376e5dd7070Spatrick       Previous = Previous->Previous;
1377e5dd7070Spatrick     if (Previous && Previous->is(tok::question))
1378*12c85518Srobert       CurrentState.QuestionColumn = State.Column;
1379e5dd7070Spatrick   }
1380e5dd7070Spatrick   if (!Current.opensScope() && !Current.closesScope() &&
1381*12c85518Srobert       !Current.is(TT_PointerOrReference)) {
1382e5dd7070Spatrick     State.LowestLevelOnLine =
1383e5dd7070Spatrick         std::min(State.LowestLevelOnLine, Current.NestingLevel);
1384*12c85518Srobert   }
1385e5dd7070Spatrick   if (Current.isMemberAccess())
1386*12c85518Srobert     CurrentState.StartOfFunctionCall = !Current.NextOperator ? 0 : State.Column;
1387e5dd7070Spatrick   if (Current.is(TT_SelectorName))
1388*12c85518Srobert     CurrentState.ObjCSelectorNameFound = true;
1389e5dd7070Spatrick   if (Current.is(TT_CtorInitializerColon) &&
1390e5dd7070Spatrick       Style.BreakConstructorInitializers != FormatStyle::BCIS_AfterColon) {
1391e5dd7070Spatrick     // Indent 2 from the column, so:
1392e5dd7070Spatrick     // SomeClass::SomeClass()
1393e5dd7070Spatrick     //     : First(...), ...
1394e5dd7070Spatrick     //       Next(...)
1395e5dd7070Spatrick     //       ^ line up here.
1396*12c85518Srobert     CurrentState.Indent = State.Column + (Style.BreakConstructorInitializers ==
1397*12c85518Srobert                                                   FormatStyle::BCIS_BeforeComma
1398e5dd7070Spatrick                                               ? 0
1399e5dd7070Spatrick                                               : 2);
1400*12c85518Srobert     CurrentState.NestedBlockIndent = CurrentState.Indent;
1401*12c85518Srobert     if (Style.PackConstructorInitializers > FormatStyle::PCIS_BinPack) {
1402*12c85518Srobert       CurrentState.AvoidBinPacking = true;
1403*12c85518Srobert       CurrentState.BreakBeforeParameter =
1404*12c85518Srobert           Style.PackConstructorInitializers != FormatStyle::PCIS_NextLine;
1405e5dd7070Spatrick     } else {
1406*12c85518Srobert       CurrentState.BreakBeforeParameter = false;
1407e5dd7070Spatrick     }
1408e5dd7070Spatrick   }
1409e5dd7070Spatrick   if (Current.is(TT_CtorInitializerColon) &&
1410e5dd7070Spatrick       Style.BreakConstructorInitializers == FormatStyle::BCIS_AfterColon) {
1411*12c85518Srobert     CurrentState.Indent =
1412e5dd7070Spatrick         State.FirstIndent + Style.ConstructorInitializerIndentWidth;
1413*12c85518Srobert     CurrentState.NestedBlockIndent = CurrentState.Indent;
1414*12c85518Srobert     if (Style.PackConstructorInitializers > FormatStyle::PCIS_BinPack)
1415*12c85518Srobert       CurrentState.AvoidBinPacking = true;
1416e5dd7070Spatrick   }
1417*12c85518Srobert   if (Current.is(TT_InheritanceColon)) {
1418*12c85518Srobert     CurrentState.Indent =
1419e5dd7070Spatrick         State.FirstIndent + Style.ConstructorInitializerIndentWidth;
1420*12c85518Srobert   }
1421e5dd7070Spatrick   if (Current.isOneOf(TT_BinaryOperator, TT_ConditionalExpr) && Newline)
1422*12c85518Srobert     CurrentState.NestedBlockIndent = State.Column + Current.ColumnWidth + 1;
1423e5dd7070Spatrick   if (Current.isOneOf(TT_LambdaLSquare, TT_LambdaArrow))
1424*12c85518Srobert     CurrentState.LastSpace = State.Column;
1425*12c85518Srobert   if (Current.is(TT_RequiresExpression) &&
1426*12c85518Srobert       Style.RequiresExpressionIndentation == FormatStyle::REI_Keyword) {
1427*12c85518Srobert     CurrentState.NestedBlockIndent = State.Column;
1428*12c85518Srobert   }
1429e5dd7070Spatrick 
1430e5dd7070Spatrick   // Insert scopes created by fake parenthesis.
1431e5dd7070Spatrick   const FormatToken *Previous = Current.getPreviousNonComment();
1432e5dd7070Spatrick 
1433e5dd7070Spatrick   // Add special behavior to support a format commonly used for JavaScript
1434e5dd7070Spatrick   // closures:
1435e5dd7070Spatrick   //   SomeFunction(function() {
1436e5dd7070Spatrick   //     foo();
1437e5dd7070Spatrick   //     bar();
1438e5dd7070Spatrick   //   }, a, b, c);
1439*12c85518Srobert   if (Current.isNot(tok::comment) && !Current.ClosesRequiresClause &&
1440*12c85518Srobert       Previous && Previous->isOneOf(tok::l_brace, TT_ArrayInitializerLSquare) &&
1441e5dd7070Spatrick       !Previous->is(TT_DictLiteral) && State.Stack.size() > 1 &&
1442*12c85518Srobert       !CurrentState.HasMultipleNestedBlocks) {
1443e5dd7070Spatrick     if (State.Stack[State.Stack.size() - 2].NestedBlockInlined && Newline)
1444*12c85518Srobert       for (ParenState &PState : llvm::drop_end(State.Stack))
1445*12c85518Srobert         PState.NoLineBreak = true;
1446e5dd7070Spatrick     State.Stack[State.Stack.size() - 2].NestedBlockInlined = false;
1447e5dd7070Spatrick   }
1448*12c85518Srobert   if (Previous && (Previous->isOneOf(TT_BinaryOperator, TT_ConditionalExpr) ||
1449*12c85518Srobert                    (Previous->isOneOf(tok::l_paren, tok::comma, tok::colon) &&
1450*12c85518Srobert                     !Previous->isOneOf(TT_DictLiteral, TT_ObjCMethodExpr)))) {
1451*12c85518Srobert     CurrentState.NestedBlockInlined =
1452ec727ea7Spatrick         !Newline && hasNestedBlockInlined(Previous, Current, Style);
1453e5dd7070Spatrick   }
1454e5dd7070Spatrick 
1455e5dd7070Spatrick   moveStatePastFakeLParens(State, Newline);
1456e5dd7070Spatrick   moveStatePastScopeCloser(State);
1457*12c85518Srobert   // Do not use CurrentState here, since the two functions before may change the
1458*12c85518Srobert   // Stack.
1459e5dd7070Spatrick   bool AllowBreak = !State.Stack.back().NoLineBreak &&
1460e5dd7070Spatrick                     !State.Stack.back().NoLineBreakInOperand;
1461e5dd7070Spatrick   moveStatePastScopeOpener(State, Newline);
1462e5dd7070Spatrick   moveStatePastFakeRParens(State);
1463e5dd7070Spatrick 
1464e5dd7070Spatrick   if (Current.is(TT_ObjCStringLiteral) && State.StartOfStringLiteral == 0)
1465e5dd7070Spatrick     State.StartOfStringLiteral = State.Column + 1;
1466*12c85518Srobert   if (Current.is(TT_CSharpStringLiteral) && State.StartOfStringLiteral == 0) {
1467e5dd7070Spatrick     State.StartOfStringLiteral = State.Column + 1;
1468*12c85518Srobert   } else if (Current.isStringLiteral() && State.StartOfStringLiteral == 0) {
1469e5dd7070Spatrick     State.StartOfStringLiteral = State.Column;
1470*12c85518Srobert   } else if (!Current.isOneOf(tok::comment, tok::identifier, tok::hash) &&
1471*12c85518Srobert              !Current.isStringLiteral()) {
1472e5dd7070Spatrick     State.StartOfStringLiteral = 0;
1473*12c85518Srobert   }
1474e5dd7070Spatrick 
1475e5dd7070Spatrick   State.Column += Current.ColumnWidth;
1476e5dd7070Spatrick   State.NextToken = State.NextToken->Next;
1477e5dd7070Spatrick 
1478e5dd7070Spatrick   unsigned Penalty =
1479e5dd7070Spatrick       handleEndOfLine(Current, State, DryRun, AllowBreak, Newline);
1480e5dd7070Spatrick 
1481e5dd7070Spatrick   if (Current.Role)
1482e5dd7070Spatrick     Current.Role->formatFromToken(State, this, DryRun);
1483e5dd7070Spatrick   // If the previous has a special role, let it consume tokens as appropriate.
1484e5dd7070Spatrick   // It is necessary to start at the previous token for the only implemented
1485e5dd7070Spatrick   // role (comma separated list). That way, the decision whether or not to break
1486e5dd7070Spatrick   // after the "{" is already done and both options are tried and evaluated.
1487e5dd7070Spatrick   // FIXME: This is ugly, find a better way.
1488e5dd7070Spatrick   if (Previous && Previous->Role)
1489e5dd7070Spatrick     Penalty += Previous->Role->formatAfterToken(State, this, DryRun);
1490e5dd7070Spatrick 
1491e5dd7070Spatrick   return Penalty;
1492e5dd7070Spatrick }
1493e5dd7070Spatrick 
moveStatePastFakeLParens(LineState & State,bool Newline)1494e5dd7070Spatrick void ContinuationIndenter::moveStatePastFakeLParens(LineState &State,
1495e5dd7070Spatrick                                                     bool Newline) {
1496e5dd7070Spatrick   const FormatToken &Current = *State.NextToken;
1497*12c85518Srobert   if (Current.FakeLParens.empty())
1498*12c85518Srobert     return;
1499*12c85518Srobert 
1500e5dd7070Spatrick   const FormatToken *Previous = Current.getPreviousNonComment();
1501e5dd7070Spatrick 
1502e5dd7070Spatrick   // Don't add extra indentation for the first fake parenthesis after
1503*12c85518Srobert   // 'return', assignments, opening <({[, or requires clauses. The indentation
1504*12c85518Srobert   // for these cases is special cased.
1505e5dd7070Spatrick   bool SkipFirstExtraIndent =
1506*12c85518Srobert       Previous &&
1507*12c85518Srobert       (Previous->opensScope() ||
1508*12c85518Srobert        Previous->isOneOf(tok::semi, tok::kw_return, TT_RequiresClause) ||
1509e5dd7070Spatrick        (Previous->getPrecedence() == prec::Assignment &&
1510ec727ea7Spatrick         Style.AlignOperands != FormatStyle::OAS_DontAlign) ||
1511*12c85518Srobert        Previous->is(TT_ObjCMethodExpr));
1512*12c85518Srobert   for (const auto &PrecedenceLevel : llvm::reverse(Current.FakeLParens)) {
1513*12c85518Srobert     const auto &CurrentState = State.Stack.back();
1514*12c85518Srobert     ParenState NewParenState = CurrentState;
1515e5dd7070Spatrick     NewParenState.Tok = nullptr;
1516e5dd7070Spatrick     NewParenState.ContainsLineBreak = false;
1517e5dd7070Spatrick     NewParenState.LastOperatorWrapped = true;
1518ec727ea7Spatrick     NewParenState.IsChainedConditional = false;
1519ec727ea7Spatrick     NewParenState.IsWrappedConditional = false;
1520ec727ea7Spatrick     NewParenState.UnindentOperator = false;
1521e5dd7070Spatrick     NewParenState.NoLineBreak =
1522*12c85518Srobert         NewParenState.NoLineBreak || CurrentState.NoLineBreakInOperand;
1523e5dd7070Spatrick 
1524e5dd7070Spatrick     // Don't propagate AvoidBinPacking into subexpressions of arg/param lists.
1525*12c85518Srobert     if (PrecedenceLevel > prec::Comma)
1526e5dd7070Spatrick       NewParenState.AvoidBinPacking = false;
1527e5dd7070Spatrick 
1528e5dd7070Spatrick     // Indent from 'LastSpace' unless these are fake parentheses encapsulating
1529e5dd7070Spatrick     // a builder type call after 'return' or, if the alignment after opening
1530e5dd7070Spatrick     // brackets is disabled.
1531e5dd7070Spatrick     if (!Current.isTrailingComment() &&
1532ec727ea7Spatrick         (Style.AlignOperands != FormatStyle::OAS_DontAlign ||
1533*12c85518Srobert          PrecedenceLevel < prec::Assignment) &&
1534e5dd7070Spatrick         (!Previous || Previous->isNot(tok::kw_return) ||
1535*12c85518Srobert          (Style.Language != FormatStyle::LK_Java && PrecedenceLevel > 0)) &&
1536e5dd7070Spatrick         (Style.AlignAfterOpenBracket != FormatStyle::BAS_DontAlign ||
1537*12c85518Srobert          PrecedenceLevel != prec::Comma || Current.NestingLevel == 0)) {
1538*12c85518Srobert       NewParenState.Indent = std::max(
1539*12c85518Srobert           std::max(State.Column, NewParenState.Indent), CurrentState.LastSpace);
1540ec727ea7Spatrick     }
1541ec727ea7Spatrick 
1542*12c85518Srobert     // Special case for generic selection expressions, its comma-separated
1543*12c85518Srobert     // expressions are not aligned to the opening paren like regular calls, but
1544*12c85518Srobert     // rather continuation-indented relative to the _Generic keyword.
1545*12c85518Srobert     if (Previous && Previous->endsSequence(tok::l_paren, tok::kw__Generic))
1546*12c85518Srobert       NewParenState.Indent = CurrentState.LastSpace;
1547*12c85518Srobert 
1548a9ac8606Spatrick     if (Previous &&
1549ec727ea7Spatrick         (Previous->getPrecedence() == prec::Assignment ||
1550*12c85518Srobert          Previous->isOneOf(tok::kw_return, TT_RequiresClause) ||
1551*12c85518Srobert          (PrecedenceLevel == prec::Conditional && Previous->is(tok::question) &&
1552ec727ea7Spatrick           Previous->is(TT_ConditionalExpr))) &&
1553a9ac8606Spatrick         !Newline) {
1554a9ac8606Spatrick       // If BreakBeforeBinaryOperators is set, un-indent a bit to account for
1555*12c85518Srobert       // the operator and keep the operands aligned.
1556a9ac8606Spatrick       if (Style.AlignOperands == FormatStyle::OAS_AlignAfterOperator)
1557ec727ea7Spatrick         NewParenState.UnindentOperator = true;
1558a9ac8606Spatrick       // Mark indentation as alignment if the expression is aligned.
1559a9ac8606Spatrick       if (Style.AlignOperands != FormatStyle::OAS_DontAlign)
1560a9ac8606Spatrick         NewParenState.IsAligned = true;
1561a9ac8606Spatrick     }
1562e5dd7070Spatrick 
1563e5dd7070Spatrick     // Do not indent relative to the fake parentheses inserted for "." or "->".
1564e5dd7070Spatrick     // This is a special case to make the following to statements consistent:
1565e5dd7070Spatrick     //   OuterFunction(InnerFunctionCall( // break
1566e5dd7070Spatrick     //       ParameterToInnerFunction));
1567e5dd7070Spatrick     //   OuterFunction(SomeObject.InnerFunctionCall( // break
1568e5dd7070Spatrick     //       ParameterToInnerFunction));
1569*12c85518Srobert     if (PrecedenceLevel > prec::Unknown)
1570e5dd7070Spatrick       NewParenState.LastSpace = std::max(NewParenState.LastSpace, State.Column);
1571*12c85518Srobert     if (PrecedenceLevel != prec::Conditional && !Current.is(TT_UnaryOperator) &&
1572*12c85518Srobert         Style.AlignAfterOpenBracket != FormatStyle::BAS_DontAlign) {
1573e5dd7070Spatrick       NewParenState.StartOfFunctionCall = State.Column;
1574*12c85518Srobert     }
1575e5dd7070Spatrick 
1576ec727ea7Spatrick     // Indent conditional expressions, unless they are chained "else-if"
1577ec727ea7Spatrick     // conditionals. Never indent expression where the 'operator' is ',', ';' or
1578ec727ea7Spatrick     // an assignment (i.e. *I <= prec::Assignment) as those have different
1579ec727ea7Spatrick     // indentation rules. Indent other expression, unless the indentation needs
1580ec727ea7Spatrick     // to be skipped.
1581*12c85518Srobert     if (PrecedenceLevel == prec::Conditional && Previous &&
1582*12c85518Srobert         Previous->is(tok::colon) && Previous->is(TT_ConditionalExpr) &&
1583*12c85518Srobert         &PrecedenceLevel == &Current.FakeLParens.back() &&
1584*12c85518Srobert         !CurrentState.IsWrappedConditional) {
1585ec727ea7Spatrick       NewParenState.IsChainedConditional = true;
1586ec727ea7Spatrick       NewParenState.UnindentOperator = State.Stack.back().UnindentOperator;
1587*12c85518Srobert     } else if (PrecedenceLevel == prec::Conditional ||
1588*12c85518Srobert                (!SkipFirstExtraIndent && PrecedenceLevel > prec::Assignment &&
1589ec727ea7Spatrick                 !Current.isTrailingComment())) {
1590e5dd7070Spatrick       NewParenState.Indent += Style.ContinuationIndentWidth;
1591ec727ea7Spatrick     }
1592*12c85518Srobert     if ((Previous && !Previous->opensScope()) || PrecedenceLevel != prec::Comma)
1593e5dd7070Spatrick       NewParenState.BreakBeforeParameter = false;
1594e5dd7070Spatrick     State.Stack.push_back(NewParenState);
1595e5dd7070Spatrick     SkipFirstExtraIndent = false;
1596e5dd7070Spatrick   }
1597e5dd7070Spatrick }
1598e5dd7070Spatrick 
moveStatePastFakeRParens(LineState & State)1599e5dd7070Spatrick void ContinuationIndenter::moveStatePastFakeRParens(LineState &State) {
1600e5dd7070Spatrick   for (unsigned i = 0, e = State.NextToken->FakeRParens; i != e; ++i) {
1601e5dd7070Spatrick     unsigned VariablePos = State.Stack.back().VariablePos;
1602e5dd7070Spatrick     if (State.Stack.size() == 1) {
1603e5dd7070Spatrick       // Do not pop the last element.
1604e5dd7070Spatrick       break;
1605e5dd7070Spatrick     }
1606e5dd7070Spatrick     State.Stack.pop_back();
1607e5dd7070Spatrick     State.Stack.back().VariablePos = VariablePos;
1608e5dd7070Spatrick   }
1609*12c85518Srobert 
1610*12c85518Srobert   if (State.NextToken->ClosesRequiresClause && Style.IndentRequiresClause) {
1611*12c85518Srobert     // Remove the indentation of the requires clauses (which is not in Indent,
1612*12c85518Srobert     // but in LastSpace).
1613*12c85518Srobert     State.Stack.back().LastSpace -= Style.IndentWidth;
1614*12c85518Srobert   }
1615e5dd7070Spatrick }
1616e5dd7070Spatrick 
moveStatePastScopeOpener(LineState & State,bool Newline)1617e5dd7070Spatrick void ContinuationIndenter::moveStatePastScopeOpener(LineState &State,
1618e5dd7070Spatrick                                                     bool Newline) {
1619e5dd7070Spatrick   const FormatToken &Current = *State.NextToken;
1620e5dd7070Spatrick   if (!Current.opensScope())
1621e5dd7070Spatrick     return;
1622e5dd7070Spatrick 
1623*12c85518Srobert   const auto &CurrentState = State.Stack.back();
1624*12c85518Srobert 
1625ec727ea7Spatrick   // Don't allow '<' or '(' in C# generic type constraints to start new scopes.
1626ec727ea7Spatrick   if (Current.isOneOf(tok::less, tok::l_paren) &&
1627*12c85518Srobert       CurrentState.IsCSharpGenericTypeConstraint) {
1628ec727ea7Spatrick     return;
1629*12c85518Srobert   }
1630ec727ea7Spatrick 
1631a9ac8606Spatrick   if (Current.MatchingParen && Current.is(BK_Block)) {
1632e5dd7070Spatrick     moveStateToNewBlock(State);
1633e5dd7070Spatrick     return;
1634e5dd7070Spatrick   }
1635e5dd7070Spatrick 
1636e5dd7070Spatrick   unsigned NewIndent;
1637*12c85518Srobert   unsigned LastSpace = CurrentState.LastSpace;
1638e5dd7070Spatrick   bool AvoidBinPacking;
1639e5dd7070Spatrick   bool BreakBeforeParameter = false;
1640*12c85518Srobert   unsigned NestedBlockIndent = std::max(CurrentState.StartOfFunctionCall,
1641*12c85518Srobert                                         CurrentState.NestedBlockIndent);
1642e5dd7070Spatrick   if (Current.isOneOf(tok::l_brace, TT_ArrayInitializerLSquare) ||
1643e5dd7070Spatrick       opensProtoMessageField(Current, Style)) {
1644e5dd7070Spatrick     if (Current.opensBlockOrBlockTypeList(Style)) {
1645e5dd7070Spatrick       NewIndent = Style.IndentWidth +
1646*12c85518Srobert                   std::min(State.Column, CurrentState.NestedBlockIndent);
1647e5dd7070Spatrick     } else {
1648*12c85518Srobert       NewIndent = CurrentState.LastSpace + Style.ContinuationIndentWidth;
1649e5dd7070Spatrick     }
1650e5dd7070Spatrick     const FormatToken *NextNoComment = Current.getNextNonComment();
1651e5dd7070Spatrick     bool EndsInComma = Current.MatchingParen &&
1652e5dd7070Spatrick                        Current.MatchingParen->Previous &&
1653e5dd7070Spatrick                        Current.MatchingParen->Previous->is(tok::comma);
1654e5dd7070Spatrick     AvoidBinPacking = EndsInComma || Current.is(TT_DictLiteral) ||
1655e5dd7070Spatrick                       Style.Language == FormatStyle::LK_Proto ||
1656e5dd7070Spatrick                       Style.Language == FormatStyle::LK_TextProto ||
1657e5dd7070Spatrick                       !Style.BinPackArguments ||
1658e5dd7070Spatrick                       (NextNoComment &&
1659e5dd7070Spatrick                        NextNoComment->isOneOf(TT_DesignatedInitializerPeriod,
1660e5dd7070Spatrick                                               TT_DesignatedInitializerLSquare));
1661e5dd7070Spatrick     BreakBeforeParameter = EndsInComma;
1662e5dd7070Spatrick     if (Current.ParameterCount > 1)
1663e5dd7070Spatrick       NestedBlockIndent = std::max(NestedBlockIndent, State.Column + 1);
1664e5dd7070Spatrick   } else {
1665*12c85518Srobert     NewIndent =
1666*12c85518Srobert         Style.ContinuationIndentWidth +
1667*12c85518Srobert         std::max(CurrentState.LastSpace, CurrentState.StartOfFunctionCall);
1668e5dd7070Spatrick 
1669e5dd7070Spatrick     // Ensure that different different brackets force relative alignment, e.g.:
1670e5dd7070Spatrick     // void SomeFunction(vector<  // break
1671e5dd7070Spatrick     //                       int> v);
1672e5dd7070Spatrick     // FIXME: We likely want to do this for more combinations of brackets.
1673e5dd7070Spatrick     if (Current.is(tok::less) && Current.ParentBracket == tok::l_paren) {
1674*12c85518Srobert       NewIndent = std::max(NewIndent, CurrentState.Indent);
1675*12c85518Srobert       LastSpace = std::max(LastSpace, CurrentState.Indent);
1676e5dd7070Spatrick     }
1677e5dd7070Spatrick 
1678e5dd7070Spatrick     bool EndsInComma =
1679e5dd7070Spatrick         Current.MatchingParen &&
1680e5dd7070Spatrick         Current.MatchingParen->getPreviousNonComment() &&
1681e5dd7070Spatrick         Current.MatchingParen->getPreviousNonComment()->is(tok::comma);
1682e5dd7070Spatrick 
1683e5dd7070Spatrick     // If ObjCBinPackProtocolList is unspecified, fall back to BinPackParameters
1684e5dd7070Spatrick     // for backwards compatibility.
1685e5dd7070Spatrick     bool ObjCBinPackProtocolList =
1686e5dd7070Spatrick         (Style.ObjCBinPackProtocolList == FormatStyle::BPS_Auto &&
1687e5dd7070Spatrick          Style.BinPackParameters) ||
1688e5dd7070Spatrick         Style.ObjCBinPackProtocolList == FormatStyle::BPS_Always;
1689e5dd7070Spatrick 
1690e5dd7070Spatrick     bool BinPackDeclaration =
1691e5dd7070Spatrick         (State.Line->Type != LT_ObjCDecl && Style.BinPackParameters) ||
1692e5dd7070Spatrick         (State.Line->Type == LT_ObjCDecl && ObjCBinPackProtocolList);
1693e5dd7070Spatrick 
1694*12c85518Srobert     bool GenericSelection =
1695*12c85518Srobert         Current.getPreviousNonComment() &&
1696*12c85518Srobert         Current.getPreviousNonComment()->is(tok::kw__Generic);
1697*12c85518Srobert 
1698e5dd7070Spatrick     AvoidBinPacking =
1699*12c85518Srobert         (CurrentState.IsCSharpGenericTypeConstraint) || GenericSelection ||
1700*12c85518Srobert         (Style.isJavaScript() && EndsInComma) ||
1701e5dd7070Spatrick         (State.Line->MustBeDeclaration && !BinPackDeclaration) ||
1702e5dd7070Spatrick         (!State.Line->MustBeDeclaration && !Style.BinPackArguments) ||
1703e5dd7070Spatrick         (Style.ExperimentalAutoDetectBinPacking &&
1704a9ac8606Spatrick          (Current.is(PPK_OnePerLine) ||
1705a9ac8606Spatrick           (!BinPackInconclusiveFunctions && Current.is(PPK_Inconclusive))));
1706e5dd7070Spatrick 
1707ec727ea7Spatrick     if (Current.is(TT_ObjCMethodExpr) && Current.MatchingParen &&
1708ec727ea7Spatrick         Style.ObjCBreakBeforeNestedBlockParam) {
1709e5dd7070Spatrick       if (Style.ColumnLimit) {
1710e5dd7070Spatrick         // If this '[' opens an ObjC call, determine whether all parameters fit
1711e5dd7070Spatrick         // into one line and put one per line if they don't.
1712e5dd7070Spatrick         if (getLengthToMatchingParen(Current, State.Stack) + State.Column >
1713*12c85518Srobert             getColumnLimit(State)) {
1714e5dd7070Spatrick           BreakBeforeParameter = true;
1715*12c85518Srobert         }
1716e5dd7070Spatrick       } else {
1717e5dd7070Spatrick         // For ColumnLimit = 0, we have to figure out whether there is or has to
1718e5dd7070Spatrick         // be a line break within this call.
1719e5dd7070Spatrick         for (const FormatToken *Tok = &Current;
1720e5dd7070Spatrick              Tok && Tok != Current.MatchingParen; Tok = Tok->Next) {
1721e5dd7070Spatrick           if (Tok->MustBreakBefore ||
1722e5dd7070Spatrick               (Tok->CanBreakBefore && Tok->NewlinesBefore > 0)) {
1723e5dd7070Spatrick             BreakBeforeParameter = true;
1724e5dd7070Spatrick             break;
1725e5dd7070Spatrick           }
1726e5dd7070Spatrick         }
1727e5dd7070Spatrick       }
1728e5dd7070Spatrick     }
1729e5dd7070Spatrick 
1730*12c85518Srobert     if (Style.isJavaScript() && EndsInComma)
1731e5dd7070Spatrick       BreakBeforeParameter = true;
1732e5dd7070Spatrick   }
1733e5dd7070Spatrick   // Generally inherit NoLineBreak from the current scope to nested scope.
1734e5dd7070Spatrick   // However, don't do this for non-empty nested blocks, dict literals and
1735e5dd7070Spatrick   // array literals as these follow different indentation rules.
1736e5dd7070Spatrick   bool NoLineBreak =
1737e5dd7070Spatrick       Current.Children.empty() &&
1738e5dd7070Spatrick       !Current.isOneOf(TT_DictLiteral, TT_ArrayInitializerLSquare) &&
1739*12c85518Srobert       (CurrentState.NoLineBreak || CurrentState.NoLineBreakInOperand ||
1740e5dd7070Spatrick        (Current.is(TT_TemplateOpener) &&
1741*12c85518Srobert         CurrentState.ContainsUnwrappedBuilder));
1742e5dd7070Spatrick   State.Stack.push_back(
1743e5dd7070Spatrick       ParenState(&Current, NewIndent, LastSpace, AvoidBinPacking, NoLineBreak));
1744*12c85518Srobert   auto &NewState = State.Stack.back();
1745*12c85518Srobert   NewState.NestedBlockIndent = NestedBlockIndent;
1746*12c85518Srobert   NewState.BreakBeforeParameter = BreakBeforeParameter;
1747*12c85518Srobert   NewState.HasMultipleNestedBlocks = (Current.BlockParameterCount > 1);
1748ec727ea7Spatrick 
1749ec727ea7Spatrick   if (Style.BraceWrapping.BeforeLambdaBody && Current.Next != nullptr &&
1750*12c85518Srobert       Current.is(tok::l_paren)) {
1751*12c85518Srobert     // Search for any parameter that is a lambda.
1752ec727ea7Spatrick     FormatToken const *next = Current.Next;
1753ec727ea7Spatrick     while (next != nullptr) {
1754ec727ea7Spatrick       if (next->is(TT_LambdaLSquare)) {
1755*12c85518Srobert         NewState.HasMultipleNestedBlocks = true;
1756ec727ea7Spatrick         break;
1757ec727ea7Spatrick       }
1758ec727ea7Spatrick       next = next->Next;
1759ec727ea7Spatrick     }
1760ec727ea7Spatrick   }
1761ec727ea7Spatrick 
1762*12c85518Srobert   NewState.IsInsideObjCArrayLiteral = Current.is(TT_ArrayInitializerLSquare) &&
1763*12c85518Srobert                                       Current.Previous &&
1764e5dd7070Spatrick                                       Current.Previous->is(tok::at);
1765e5dd7070Spatrick }
1766e5dd7070Spatrick 
moveStatePastScopeCloser(LineState & State)1767e5dd7070Spatrick void ContinuationIndenter::moveStatePastScopeCloser(LineState &State) {
1768e5dd7070Spatrick   const FormatToken &Current = *State.NextToken;
1769e5dd7070Spatrick   if (!Current.closesScope())
1770e5dd7070Spatrick     return;
1771e5dd7070Spatrick 
1772e5dd7070Spatrick   // If we encounter a closing ), ], } or >, we can remove a level from our
1773e5dd7070Spatrick   // stacks.
1774e5dd7070Spatrick   if (State.Stack.size() > 1 &&
1775e5dd7070Spatrick       (Current.isOneOf(tok::r_paren, tok::r_square, TT_TemplateString) ||
1776e5dd7070Spatrick        (Current.is(tok::r_brace) && State.NextToken != State.Line->First) ||
1777e5dd7070Spatrick        State.NextToken->is(TT_TemplateCloser) ||
1778*12c85518Srobert        (Current.is(tok::greater) && Current.is(TT_DictLiteral)))) {
1779e5dd7070Spatrick     State.Stack.pop_back();
1780*12c85518Srobert   }
1781*12c85518Srobert 
1782*12c85518Srobert   auto &CurrentState = State.Stack.back();
1783e5dd7070Spatrick 
1784e5dd7070Spatrick   // Reevaluate whether ObjC message arguments fit into one line.
1785e5dd7070Spatrick   // If a receiver spans multiple lines, e.g.:
1786e5dd7070Spatrick   //   [[object block:^{
1787e5dd7070Spatrick   //     return 42;
1788e5dd7070Spatrick   //   }] a:42 b:42];
1789e5dd7070Spatrick   // BreakBeforeParameter is calculated based on an incorrect assumption
1790e5dd7070Spatrick   // (it is checked whether the whole expression fits into one line without
1791e5dd7070Spatrick   // considering a line break inside a message receiver).
1792*12c85518Srobert   // We check whether arguments fit after receiver scope closer (into the same
1793e5dd7070Spatrick   // line).
1794*12c85518Srobert   if (CurrentState.BreakBeforeParameter && Current.MatchingParen &&
1795e5dd7070Spatrick       Current.MatchingParen->Previous) {
1796e5dd7070Spatrick     const FormatToken &CurrentScopeOpener = *Current.MatchingParen->Previous;
1797e5dd7070Spatrick     if (CurrentScopeOpener.is(TT_ObjCMethodExpr) &&
1798e5dd7070Spatrick         CurrentScopeOpener.MatchingParen) {
1799e5dd7070Spatrick       int NecessarySpaceInLine =
1800e5dd7070Spatrick           getLengthToMatchingParen(CurrentScopeOpener, State.Stack) +
1801e5dd7070Spatrick           CurrentScopeOpener.TotalLength - Current.TotalLength - 1;
1802e5dd7070Spatrick       if (State.Column + Current.ColumnWidth + NecessarySpaceInLine <=
1803*12c85518Srobert           Style.ColumnLimit) {
1804*12c85518Srobert         CurrentState.BreakBeforeParameter = false;
1805*12c85518Srobert       }
1806e5dd7070Spatrick     }
1807e5dd7070Spatrick   }
1808e5dd7070Spatrick 
1809e5dd7070Spatrick   if (Current.is(tok::r_square)) {
1810e5dd7070Spatrick     // If this ends the array subscript expr, reset the corresponding value.
1811e5dd7070Spatrick     const FormatToken *NextNonComment = Current.getNextNonComment();
1812e5dd7070Spatrick     if (NextNonComment && NextNonComment->isNot(tok::l_square))
1813*12c85518Srobert       CurrentState.StartOfArraySubscripts = 0;
1814e5dd7070Spatrick   }
1815e5dd7070Spatrick }
1816e5dd7070Spatrick 
moveStateToNewBlock(LineState & State)1817e5dd7070Spatrick void ContinuationIndenter::moveStateToNewBlock(LineState &State) {
1818e5dd7070Spatrick   unsigned NestedBlockIndent = State.Stack.back().NestedBlockIndent;
1819e5dd7070Spatrick   // ObjC block sometimes follow special indentation rules.
1820e5dd7070Spatrick   unsigned NewIndent =
1821e5dd7070Spatrick       NestedBlockIndent + (State.NextToken->is(TT_ObjCBlockLBrace)
1822e5dd7070Spatrick                                ? Style.ObjCBlockIndentWidth
1823e5dd7070Spatrick                                : Style.IndentWidth);
1824e5dd7070Spatrick   State.Stack.push_back(ParenState(State.NextToken, NewIndent,
1825e5dd7070Spatrick                                    State.Stack.back().LastSpace,
1826e5dd7070Spatrick                                    /*AvoidBinPacking=*/true,
1827e5dd7070Spatrick                                    /*NoLineBreak=*/false));
1828e5dd7070Spatrick   State.Stack.back().NestedBlockIndent = NestedBlockIndent;
1829e5dd7070Spatrick   State.Stack.back().BreakBeforeParameter = true;
1830e5dd7070Spatrick }
1831e5dd7070Spatrick 
getLastLineEndColumn(StringRef Text,unsigned StartColumn,unsigned TabWidth,encoding::Encoding Encoding)1832e5dd7070Spatrick static unsigned getLastLineEndColumn(StringRef Text, unsigned StartColumn,
1833e5dd7070Spatrick                                      unsigned TabWidth,
1834e5dd7070Spatrick                                      encoding::Encoding Encoding) {
1835e5dd7070Spatrick   size_t LastNewlinePos = Text.find_last_of("\n");
1836e5dd7070Spatrick   if (LastNewlinePos == StringRef::npos) {
1837e5dd7070Spatrick     return StartColumn +
1838e5dd7070Spatrick            encoding::columnWidthWithTabs(Text, StartColumn, TabWidth, Encoding);
1839e5dd7070Spatrick   } else {
1840e5dd7070Spatrick     return encoding::columnWidthWithTabs(Text.substr(LastNewlinePos),
1841e5dd7070Spatrick                                          /*StartColumn=*/0, TabWidth, Encoding);
1842e5dd7070Spatrick   }
1843e5dd7070Spatrick }
1844e5dd7070Spatrick 
reformatRawStringLiteral(const FormatToken & Current,LineState & State,const FormatStyle & RawStringStyle,bool DryRun,bool Newline)1845e5dd7070Spatrick unsigned ContinuationIndenter::reformatRawStringLiteral(
1846e5dd7070Spatrick     const FormatToken &Current, LineState &State,
1847e5dd7070Spatrick     const FormatStyle &RawStringStyle, bool DryRun, bool Newline) {
1848e5dd7070Spatrick   unsigned StartColumn = State.Column - Current.ColumnWidth;
1849e5dd7070Spatrick   StringRef OldDelimiter = *getRawStringDelimiter(Current.TokenText);
1850e5dd7070Spatrick   StringRef NewDelimiter =
1851e5dd7070Spatrick       getCanonicalRawStringDelimiter(Style, RawStringStyle.Language);
1852a9ac8606Spatrick   if (NewDelimiter.empty())
1853e5dd7070Spatrick     NewDelimiter = OldDelimiter;
1854e5dd7070Spatrick   // The text of a raw string is between the leading 'R"delimiter(' and the
1855e5dd7070Spatrick   // trailing 'delimiter)"'.
1856e5dd7070Spatrick   unsigned OldPrefixSize = 3 + OldDelimiter.size();
1857e5dd7070Spatrick   unsigned OldSuffixSize = 2 + OldDelimiter.size();
1858e5dd7070Spatrick   // We create a virtual text environment which expects a null-terminated
1859e5dd7070Spatrick   // string, so we cannot use StringRef.
1860ec727ea7Spatrick   std::string RawText = std::string(
1861ec727ea7Spatrick       Current.TokenText.substr(OldPrefixSize).drop_back(OldSuffixSize));
1862e5dd7070Spatrick   if (NewDelimiter != OldDelimiter) {
1863e5dd7070Spatrick     // Don't update to the canonical delimiter 'deli' if ')deli"' occurs in the
1864e5dd7070Spatrick     // raw string.
1865e5dd7070Spatrick     std::string CanonicalDelimiterSuffix = (")" + NewDelimiter + "\"").str();
1866e5dd7070Spatrick     if (StringRef(RawText).contains(CanonicalDelimiterSuffix))
1867e5dd7070Spatrick       NewDelimiter = OldDelimiter;
1868e5dd7070Spatrick   }
1869e5dd7070Spatrick 
1870e5dd7070Spatrick   unsigned NewPrefixSize = 3 + NewDelimiter.size();
1871e5dd7070Spatrick   unsigned NewSuffixSize = 2 + NewDelimiter.size();
1872e5dd7070Spatrick 
1873e5dd7070Spatrick   // The first start column is the column the raw text starts after formatting.
1874e5dd7070Spatrick   unsigned FirstStartColumn = StartColumn + NewPrefixSize;
1875e5dd7070Spatrick 
1876e5dd7070Spatrick   // The next start column is the intended indentation a line break inside
1877e5dd7070Spatrick   // the raw string at level 0. It is determined by the following rules:
1878e5dd7070Spatrick   //   - if the content starts on newline, it is one level more than the current
1879e5dd7070Spatrick   //     indent, and
1880e5dd7070Spatrick   //   - if the content does not start on a newline, it is the first start
1881e5dd7070Spatrick   //     column.
1882e5dd7070Spatrick   // These rules have the advantage that the formatted content both does not
1883e5dd7070Spatrick   // violate the rectangle rule and visually flows within the surrounding
1884e5dd7070Spatrick   // source.
1885e5dd7070Spatrick   bool ContentStartsOnNewline = Current.TokenText[OldPrefixSize] == '\n';
1886e5dd7070Spatrick   // If this token is the last parameter (checked by looking if it's followed by
1887e5dd7070Spatrick   // `)` and is not on a newline, the base the indent off the line's nested
1888e5dd7070Spatrick   // block indent. Otherwise, base the indent off the arguments indent, so we
1889e5dd7070Spatrick   // can achieve:
1890e5dd7070Spatrick   //
1891e5dd7070Spatrick   // fffffffffff(1, 2, 3, R"pb(
1892e5dd7070Spatrick   //     key1: 1  #
1893e5dd7070Spatrick   //     key2: 2)pb");
1894e5dd7070Spatrick   //
1895e5dd7070Spatrick   // fffffffffff(1, 2, 3,
1896e5dd7070Spatrick   //             R"pb(
1897e5dd7070Spatrick   //               key1: 1  #
1898e5dd7070Spatrick   //               key2: 2
1899e5dd7070Spatrick   //             )pb");
1900e5dd7070Spatrick   //
1901e5dd7070Spatrick   // fffffffffff(1, 2, 3,
1902e5dd7070Spatrick   //             R"pb(
1903e5dd7070Spatrick   //               key1: 1  #
1904e5dd7070Spatrick   //               key2: 2
1905e5dd7070Spatrick   //             )pb",
1906e5dd7070Spatrick   //             5);
1907e5dd7070Spatrick   unsigned CurrentIndent =
1908e5dd7070Spatrick       (!Newline && Current.Next && Current.Next->is(tok::r_paren))
1909e5dd7070Spatrick           ? State.Stack.back().NestedBlockIndent
1910e5dd7070Spatrick           : State.Stack.back().Indent;
1911e5dd7070Spatrick   unsigned NextStartColumn = ContentStartsOnNewline
1912e5dd7070Spatrick                                  ? CurrentIndent + Style.IndentWidth
1913e5dd7070Spatrick                                  : FirstStartColumn;
1914e5dd7070Spatrick 
1915e5dd7070Spatrick   // The last start column is the column the raw string suffix starts if it is
1916e5dd7070Spatrick   // put on a newline.
1917e5dd7070Spatrick   // The last start column is the intended indentation of the raw string postfix
1918e5dd7070Spatrick   // if it is put on a newline. It is determined by the following rules:
1919e5dd7070Spatrick   //   - if the raw string prefix starts on a newline, it is the column where
1920e5dd7070Spatrick   //     that raw string prefix starts, and
1921e5dd7070Spatrick   //   - if the raw string prefix does not start on a newline, it is the current
1922e5dd7070Spatrick   //     indent.
1923e5dd7070Spatrick   unsigned LastStartColumn =
1924e5dd7070Spatrick       Current.NewlinesBefore ? FirstStartColumn - NewPrefixSize : CurrentIndent;
1925e5dd7070Spatrick 
1926e5dd7070Spatrick   std::pair<tooling::Replacements, unsigned> Fixes = internal::reformat(
1927e5dd7070Spatrick       RawStringStyle, RawText, {tooling::Range(0, RawText.size())},
1928e5dd7070Spatrick       FirstStartColumn, NextStartColumn, LastStartColumn, "<stdin>",
1929e5dd7070Spatrick       /*Status=*/nullptr);
1930e5dd7070Spatrick 
1931e5dd7070Spatrick   auto NewCode = applyAllReplacements(RawText, Fixes.first);
1932e5dd7070Spatrick   tooling::Replacements NoFixes;
1933*12c85518Srobert   if (!NewCode)
1934e5dd7070Spatrick     return addMultilineToken(Current, State);
1935e5dd7070Spatrick   if (!DryRun) {
1936e5dd7070Spatrick     if (NewDelimiter != OldDelimiter) {
1937e5dd7070Spatrick       // In 'R"delimiter(...', the delimiter starts 2 characters after the start
1938e5dd7070Spatrick       // of the token.
1939e5dd7070Spatrick       SourceLocation PrefixDelimiterStart =
1940e5dd7070Spatrick           Current.Tok.getLocation().getLocWithOffset(2);
1941e5dd7070Spatrick       auto PrefixErr = Whitespaces.addReplacement(tooling::Replacement(
1942e5dd7070Spatrick           SourceMgr, PrefixDelimiterStart, OldDelimiter.size(), NewDelimiter));
1943e5dd7070Spatrick       if (PrefixErr) {
1944e5dd7070Spatrick         llvm::errs()
1945e5dd7070Spatrick             << "Failed to update the prefix delimiter of a raw string: "
1946e5dd7070Spatrick             << llvm::toString(std::move(PrefixErr)) << "\n";
1947e5dd7070Spatrick       }
1948e5dd7070Spatrick       // In 'R"delimiter(...)delimiter"', the suffix delimiter starts at
1949e5dd7070Spatrick       // position length - 1 - |delimiter|.
1950e5dd7070Spatrick       SourceLocation SuffixDelimiterStart =
1951e5dd7070Spatrick           Current.Tok.getLocation().getLocWithOffset(Current.TokenText.size() -
1952e5dd7070Spatrick                                                      1 - OldDelimiter.size());
1953e5dd7070Spatrick       auto SuffixErr = Whitespaces.addReplacement(tooling::Replacement(
1954e5dd7070Spatrick           SourceMgr, SuffixDelimiterStart, OldDelimiter.size(), NewDelimiter));
1955e5dd7070Spatrick       if (SuffixErr) {
1956e5dd7070Spatrick         llvm::errs()
1957e5dd7070Spatrick             << "Failed to update the suffix delimiter of a raw string: "
1958e5dd7070Spatrick             << llvm::toString(std::move(SuffixErr)) << "\n";
1959e5dd7070Spatrick       }
1960e5dd7070Spatrick     }
1961e5dd7070Spatrick     SourceLocation OriginLoc =
1962e5dd7070Spatrick         Current.Tok.getLocation().getLocWithOffset(OldPrefixSize);
1963e5dd7070Spatrick     for (const tooling::Replacement &Fix : Fixes.first) {
1964e5dd7070Spatrick       auto Err = Whitespaces.addReplacement(tooling::Replacement(
1965e5dd7070Spatrick           SourceMgr, OriginLoc.getLocWithOffset(Fix.getOffset()),
1966e5dd7070Spatrick           Fix.getLength(), Fix.getReplacementText()));
1967e5dd7070Spatrick       if (Err) {
1968e5dd7070Spatrick         llvm::errs() << "Failed to reformat raw string: "
1969e5dd7070Spatrick                      << llvm::toString(std::move(Err)) << "\n";
1970e5dd7070Spatrick       }
1971e5dd7070Spatrick     }
1972e5dd7070Spatrick   }
1973e5dd7070Spatrick   unsigned RawLastLineEndColumn = getLastLineEndColumn(
1974e5dd7070Spatrick       *NewCode, FirstStartColumn, Style.TabWidth, Encoding);
1975e5dd7070Spatrick   State.Column = RawLastLineEndColumn + NewSuffixSize;
1976e5dd7070Spatrick   // Since we're updating the column to after the raw string literal here, we
1977e5dd7070Spatrick   // have to manually add the penalty for the prefix R"delim( over the column
1978e5dd7070Spatrick   // limit.
1979e5dd7070Spatrick   unsigned PrefixExcessCharacters =
1980e5dd7070Spatrick       StartColumn + NewPrefixSize > Style.ColumnLimit
1981e5dd7070Spatrick           ? StartColumn + NewPrefixSize - Style.ColumnLimit
1982e5dd7070Spatrick           : 0;
1983e5dd7070Spatrick   bool IsMultiline =
1984e5dd7070Spatrick       ContentStartsOnNewline || (NewCode->find('\n') != std::string::npos);
1985e5dd7070Spatrick   if (IsMultiline) {
1986e5dd7070Spatrick     // Break before further function parameters on all levels.
1987*12c85518Srobert     for (ParenState &Paren : State.Stack)
1988*12c85518Srobert       Paren.BreakBeforeParameter = true;
1989e5dd7070Spatrick   }
1990e5dd7070Spatrick   return Fixes.second + PrefixExcessCharacters * Style.PenaltyExcessCharacter;
1991e5dd7070Spatrick }
1992e5dd7070Spatrick 
addMultilineToken(const FormatToken & Current,LineState & State)1993e5dd7070Spatrick unsigned ContinuationIndenter::addMultilineToken(const FormatToken &Current,
1994e5dd7070Spatrick                                                  LineState &State) {
1995e5dd7070Spatrick   // Break before further function parameters on all levels.
1996*12c85518Srobert   for (ParenState &Paren : State.Stack)
1997*12c85518Srobert     Paren.BreakBeforeParameter = true;
1998e5dd7070Spatrick 
1999e5dd7070Spatrick   unsigned ColumnsUsed = State.Column;
2000e5dd7070Spatrick   // We can only affect layout of the first and the last line, so the penalty
2001e5dd7070Spatrick   // for all other lines is constant, and we ignore it.
2002e5dd7070Spatrick   State.Column = Current.LastLineColumnWidth;
2003e5dd7070Spatrick 
2004e5dd7070Spatrick   if (ColumnsUsed > getColumnLimit(State))
2005e5dd7070Spatrick     return Style.PenaltyExcessCharacter * (ColumnsUsed - getColumnLimit(State));
2006e5dd7070Spatrick   return 0;
2007e5dd7070Spatrick }
2008e5dd7070Spatrick 
handleEndOfLine(const FormatToken & Current,LineState & State,bool DryRun,bool AllowBreak,bool Newline)2009e5dd7070Spatrick unsigned ContinuationIndenter::handleEndOfLine(const FormatToken &Current,
2010e5dd7070Spatrick                                                LineState &State, bool DryRun,
2011e5dd7070Spatrick                                                bool AllowBreak, bool Newline) {
2012e5dd7070Spatrick   unsigned Penalty = 0;
2013e5dd7070Spatrick   // Compute the raw string style to use in case this is a raw string literal
2014e5dd7070Spatrick   // that can be reformatted.
2015e5dd7070Spatrick   auto RawStringStyle = getRawStringStyle(Current, State);
2016e5dd7070Spatrick   if (RawStringStyle && !Current.Finalized) {
2017e5dd7070Spatrick     Penalty = reformatRawStringLiteral(Current, State, *RawStringStyle, DryRun,
2018e5dd7070Spatrick                                        Newline);
2019e5dd7070Spatrick   } else if (Current.IsMultiline && Current.isNot(TT_BlockComment)) {
2020e5dd7070Spatrick     // Don't break multi-line tokens other than block comments and raw string
2021e5dd7070Spatrick     // literals. Instead, just update the state.
2022e5dd7070Spatrick     Penalty = addMultilineToken(Current, State);
2023e5dd7070Spatrick   } else if (State.Line->Type != LT_ImportStatement) {
2024e5dd7070Spatrick     // We generally don't break import statements.
2025e5dd7070Spatrick     LineState OriginalState = State;
2026e5dd7070Spatrick 
2027e5dd7070Spatrick     // Whether we force the reflowing algorithm to stay strictly within the
2028e5dd7070Spatrick     // column limit.
2029e5dd7070Spatrick     bool Strict = false;
2030e5dd7070Spatrick     // Whether the first non-strict attempt at reflowing did intentionally
2031e5dd7070Spatrick     // exceed the column limit.
2032e5dd7070Spatrick     bool Exceeded = false;
2033e5dd7070Spatrick     std::tie(Penalty, Exceeded) = breakProtrudingToken(
2034e5dd7070Spatrick         Current, State, AllowBreak, /*DryRun=*/true, Strict);
2035e5dd7070Spatrick     if (Exceeded) {
2036e5dd7070Spatrick       // If non-strict reflowing exceeds the column limit, try whether strict
2037e5dd7070Spatrick       // reflowing leads to an overall lower penalty.
2038e5dd7070Spatrick       LineState StrictState = OriginalState;
2039e5dd7070Spatrick       unsigned StrictPenalty =
2040e5dd7070Spatrick           breakProtrudingToken(Current, StrictState, AllowBreak,
2041e5dd7070Spatrick                                /*DryRun=*/true, /*Strict=*/true)
2042e5dd7070Spatrick               .first;
2043e5dd7070Spatrick       Strict = StrictPenalty <= Penalty;
2044e5dd7070Spatrick       if (Strict) {
2045e5dd7070Spatrick         Penalty = StrictPenalty;
2046e5dd7070Spatrick         State = StrictState;
2047e5dd7070Spatrick       }
2048e5dd7070Spatrick     }
2049e5dd7070Spatrick     if (!DryRun) {
2050e5dd7070Spatrick       // If we're not in dry-run mode, apply the changes with the decision on
2051e5dd7070Spatrick       // strictness made above.
2052e5dd7070Spatrick       breakProtrudingToken(Current, OriginalState, AllowBreak, /*DryRun=*/false,
2053e5dd7070Spatrick                            Strict);
2054e5dd7070Spatrick     }
2055e5dd7070Spatrick   }
2056e5dd7070Spatrick   if (State.Column > getColumnLimit(State)) {
2057e5dd7070Spatrick     unsigned ExcessCharacters = State.Column - getColumnLimit(State);
2058e5dd7070Spatrick     Penalty += Style.PenaltyExcessCharacter * ExcessCharacters;
2059e5dd7070Spatrick   }
2060e5dd7070Spatrick   return Penalty;
2061e5dd7070Spatrick }
2062e5dd7070Spatrick 
2063e5dd7070Spatrick // Returns the enclosing function name of a token, or the empty string if not
2064e5dd7070Spatrick // found.
getEnclosingFunctionName(const FormatToken & Current)2065e5dd7070Spatrick static StringRef getEnclosingFunctionName(const FormatToken &Current) {
2066e5dd7070Spatrick   // Look for: 'function(' or 'function<templates>(' before Current.
2067e5dd7070Spatrick   auto Tok = Current.getPreviousNonComment();
2068e5dd7070Spatrick   if (!Tok || !Tok->is(tok::l_paren))
2069e5dd7070Spatrick     return "";
2070e5dd7070Spatrick   Tok = Tok->getPreviousNonComment();
2071e5dd7070Spatrick   if (!Tok)
2072e5dd7070Spatrick     return "";
2073e5dd7070Spatrick   if (Tok->is(TT_TemplateCloser)) {
2074e5dd7070Spatrick     Tok = Tok->MatchingParen;
2075e5dd7070Spatrick     if (Tok)
2076e5dd7070Spatrick       Tok = Tok->getPreviousNonComment();
2077e5dd7070Spatrick   }
2078e5dd7070Spatrick   if (!Tok || !Tok->is(tok::identifier))
2079e5dd7070Spatrick     return "";
2080e5dd7070Spatrick   return Tok->TokenText;
2081e5dd7070Spatrick }
2082e5dd7070Spatrick 
2083*12c85518Srobert std::optional<FormatStyle>
getRawStringStyle(const FormatToken & Current,const LineState & State)2084e5dd7070Spatrick ContinuationIndenter::getRawStringStyle(const FormatToken &Current,
2085e5dd7070Spatrick                                         const LineState &State) {
2086e5dd7070Spatrick   if (!Current.isStringLiteral())
2087*12c85518Srobert     return std::nullopt;
2088e5dd7070Spatrick   auto Delimiter = getRawStringDelimiter(Current.TokenText);
2089e5dd7070Spatrick   if (!Delimiter)
2090*12c85518Srobert     return std::nullopt;
2091e5dd7070Spatrick   auto RawStringStyle = RawStringFormats.getDelimiterStyle(*Delimiter);
2092*12c85518Srobert   if (!RawStringStyle && Delimiter->empty()) {
2093e5dd7070Spatrick     RawStringStyle = RawStringFormats.getEnclosingFunctionStyle(
2094e5dd7070Spatrick         getEnclosingFunctionName(Current));
2095*12c85518Srobert   }
2096e5dd7070Spatrick   if (!RawStringStyle)
2097*12c85518Srobert     return std::nullopt;
2098e5dd7070Spatrick   RawStringStyle->ColumnLimit = getColumnLimit(State);
2099e5dd7070Spatrick   return RawStringStyle;
2100e5dd7070Spatrick }
2101e5dd7070Spatrick 
2102e5dd7070Spatrick std::unique_ptr<BreakableToken>
createBreakableToken(const FormatToken & Current,LineState & State,bool AllowBreak)2103e5dd7070Spatrick ContinuationIndenter::createBreakableToken(const FormatToken &Current,
2104e5dd7070Spatrick                                            LineState &State, bool AllowBreak) {
2105e5dd7070Spatrick   unsigned StartColumn = State.Column - Current.ColumnWidth;
2106e5dd7070Spatrick   if (Current.isStringLiteral()) {
2107a9ac8606Spatrick     // FIXME: String literal breaking is currently disabled for C#, Java, Json
2108a9ac8606Spatrick     // and JavaScript, as it requires strings to be merged using "+" which we
2109e5dd7070Spatrick     // don't support.
2110*12c85518Srobert     if (Style.Language == FormatStyle::LK_Java || Style.isJavaScript() ||
2111*12c85518Srobert         Style.isCSharp() || Style.isJson() || !Style.BreakStringLiterals ||
2112*12c85518Srobert         !AllowBreak) {
2113e5dd7070Spatrick       return nullptr;
2114*12c85518Srobert     }
2115e5dd7070Spatrick 
2116e5dd7070Spatrick     // Don't break string literals inside preprocessor directives (except for
2117e5dd7070Spatrick     // #define directives, as their contents are stored in separate lines and
2118e5dd7070Spatrick     // are not affected by this check).
2119e5dd7070Spatrick     // This way we avoid breaking code with line directives and unknown
2120e5dd7070Spatrick     // preprocessor directives that contain long string literals.
2121e5dd7070Spatrick     if (State.Line->Type == LT_PreprocessorDirective)
2122e5dd7070Spatrick       return nullptr;
2123e5dd7070Spatrick     // Exempts unterminated string literals from line breaking. The user will
2124e5dd7070Spatrick     // likely want to terminate the string before any line breaking is done.
2125e5dd7070Spatrick     if (Current.IsUnterminatedLiteral)
2126e5dd7070Spatrick       return nullptr;
2127e5dd7070Spatrick     // Don't break string literals inside Objective-C array literals (doing so
2128e5dd7070Spatrick     // raises the warning -Wobjc-string-concatenation).
2129*12c85518Srobert     if (State.Stack.back().IsInsideObjCArrayLiteral)
2130e5dd7070Spatrick       return nullptr;
2131e5dd7070Spatrick 
2132e5dd7070Spatrick     StringRef Text = Current.TokenText;
2133e5dd7070Spatrick     StringRef Prefix;
2134e5dd7070Spatrick     StringRef Postfix;
2135e5dd7070Spatrick     // FIXME: Handle whitespace between '_T', '(', '"..."', and ')'.
2136e5dd7070Spatrick     // FIXME: Store Prefix and Suffix (or PrefixLength and SuffixLength to
2137e5dd7070Spatrick     // reduce the overhead) for each FormatToken, which is a string, so that we
2138e5dd7070Spatrick     // don't run multiple checks here on the hot path.
2139e5dd7070Spatrick     if ((Text.endswith(Postfix = "\"") &&
2140e5dd7070Spatrick          (Text.startswith(Prefix = "@\"") || Text.startswith(Prefix = "\"") ||
2141e5dd7070Spatrick           Text.startswith(Prefix = "u\"") || Text.startswith(Prefix = "U\"") ||
2142e5dd7070Spatrick           Text.startswith(Prefix = "u8\"") ||
2143e5dd7070Spatrick           Text.startswith(Prefix = "L\""))) ||
2144e5dd7070Spatrick         (Text.startswith(Prefix = "_T(\"") && Text.endswith(Postfix = "\")"))) {
2145e5dd7070Spatrick       // We need this to address the case where there is an unbreakable tail
2146e5dd7070Spatrick       // only if certain other formatting decisions have been taken. The
2147e5dd7070Spatrick       // UnbreakableTailLength of Current is an overapproximation is that case
2148e5dd7070Spatrick       // and we need to be correct here.
2149e5dd7070Spatrick       unsigned UnbreakableTailLength = (State.NextToken && canBreak(State))
2150e5dd7070Spatrick                                            ? 0
2151e5dd7070Spatrick                                            : Current.UnbreakableTailLength;
2152e5dd7070Spatrick       return std::make_unique<BreakableStringLiteral>(
2153e5dd7070Spatrick           Current, StartColumn, Prefix, Postfix, UnbreakableTailLength,
2154e5dd7070Spatrick           State.Line->InPPDirective, Encoding, Style);
2155e5dd7070Spatrick     }
2156e5dd7070Spatrick   } else if (Current.is(TT_BlockComment)) {
2157e5dd7070Spatrick     if (!Style.ReflowComments ||
2158e5dd7070Spatrick         // If a comment token switches formatting, like
2159e5dd7070Spatrick         // /* clang-format on */, we don't want to break it further,
2160e5dd7070Spatrick         // but we may still want to adjust its indentation.
2161e5dd7070Spatrick         switchesFormatting(Current)) {
2162e5dd7070Spatrick       return nullptr;
2163e5dd7070Spatrick     }
2164e5dd7070Spatrick     return std::make_unique<BreakableBlockComment>(
2165e5dd7070Spatrick         Current, StartColumn, Current.OriginalColumn, !Current.Previous,
2166e5dd7070Spatrick         State.Line->InPPDirective, Encoding, Style, Whitespaces.useCRLF());
2167e5dd7070Spatrick   } else if (Current.is(TT_LineComment) &&
2168e5dd7070Spatrick              (Current.Previous == nullptr ||
2169e5dd7070Spatrick               Current.Previous->isNot(TT_ImplicitStringLiteral))) {
2170*12c85518Srobert     bool RegularComments = [&]() {
2171*12c85518Srobert       for (const FormatToken *T = &Current; T && T->is(TT_LineComment);
2172*12c85518Srobert            T = T->Next) {
2173*12c85518Srobert         if (!(T->TokenText.startswith("//") || T->TokenText.startswith("#")))
2174*12c85518Srobert           return false;
2175*12c85518Srobert       }
2176*12c85518Srobert       return true;
2177*12c85518Srobert     }();
2178e5dd7070Spatrick     if (!Style.ReflowComments ||
2179e5dd7070Spatrick         CommentPragmasRegex.match(Current.TokenText.substr(2)) ||
2180*12c85518Srobert         switchesFormatting(Current) || !RegularComments) {
2181e5dd7070Spatrick       return nullptr;
2182*12c85518Srobert     }
2183e5dd7070Spatrick     return std::make_unique<BreakableLineCommentSection>(
2184a9ac8606Spatrick         Current, StartColumn, /*InPPDirective=*/false, Encoding, Style);
2185e5dd7070Spatrick   }
2186e5dd7070Spatrick   return nullptr;
2187e5dd7070Spatrick }
2188e5dd7070Spatrick 
2189e5dd7070Spatrick std::pair<unsigned, bool>
breakProtrudingToken(const FormatToken & Current,LineState & State,bool AllowBreak,bool DryRun,bool Strict)2190e5dd7070Spatrick ContinuationIndenter::breakProtrudingToken(const FormatToken &Current,
2191e5dd7070Spatrick                                            LineState &State, bool AllowBreak,
2192e5dd7070Spatrick                                            bool DryRun, bool Strict) {
2193e5dd7070Spatrick   std::unique_ptr<const BreakableToken> Token =
2194e5dd7070Spatrick       createBreakableToken(Current, State, AllowBreak);
2195e5dd7070Spatrick   if (!Token)
2196e5dd7070Spatrick     return {0, false};
2197e5dd7070Spatrick   assert(Token->getLineCount() > 0);
2198e5dd7070Spatrick   unsigned ColumnLimit = getColumnLimit(State);
2199e5dd7070Spatrick   if (Current.is(TT_LineComment)) {
2200e5dd7070Spatrick     // We don't insert backslashes when breaking line comments.
2201e5dd7070Spatrick     ColumnLimit = Style.ColumnLimit;
2202e5dd7070Spatrick   }
2203a9ac8606Spatrick   if (ColumnLimit == 0) {
2204a9ac8606Spatrick     // To make the rest of the function easier set the column limit to the
2205a9ac8606Spatrick     // maximum, if there should be no limit.
2206a9ac8606Spatrick     ColumnLimit = std::numeric_limits<decltype(ColumnLimit)>::max();
2207a9ac8606Spatrick   }
2208e5dd7070Spatrick   if (Current.UnbreakableTailLength >= ColumnLimit)
2209e5dd7070Spatrick     return {0, false};
2210e5dd7070Spatrick   // ColumnWidth was already accounted into State.Column before calling
2211e5dd7070Spatrick   // breakProtrudingToken.
2212e5dd7070Spatrick   unsigned StartColumn = State.Column - Current.ColumnWidth;
2213e5dd7070Spatrick   unsigned NewBreakPenalty = Current.isStringLiteral()
2214e5dd7070Spatrick                                  ? Style.PenaltyBreakString
2215e5dd7070Spatrick                                  : Style.PenaltyBreakComment;
2216e5dd7070Spatrick   // Stores whether we intentionally decide to let a line exceed the column
2217e5dd7070Spatrick   // limit.
2218e5dd7070Spatrick   bool Exceeded = false;
2219e5dd7070Spatrick   // Stores whether we introduce a break anywhere in the token.
2220e5dd7070Spatrick   bool BreakInserted = Token->introducesBreakBeforeToken();
2221e5dd7070Spatrick   // Store whether we inserted a new line break at the end of the previous
2222e5dd7070Spatrick   // logical line.
2223e5dd7070Spatrick   bool NewBreakBefore = false;
2224e5dd7070Spatrick   // We use a conservative reflowing strategy. Reflow starts after a line is
2225e5dd7070Spatrick   // broken or the corresponding whitespace compressed. Reflow ends as soon as a
2226e5dd7070Spatrick   // line that doesn't get reflown with the previous line is reached.
2227e5dd7070Spatrick   bool Reflow = false;
2228e5dd7070Spatrick   // Keep track of where we are in the token:
2229e5dd7070Spatrick   // Where we are in the content of the current logical line.
2230e5dd7070Spatrick   unsigned TailOffset = 0;
2231e5dd7070Spatrick   // The column number we're currently at.
2232e5dd7070Spatrick   unsigned ContentStartColumn =
2233e5dd7070Spatrick       Token->getContentStartColumn(0, /*Break=*/false);
2234e5dd7070Spatrick   // The number of columns left in the current logical line after TailOffset.
2235e5dd7070Spatrick   unsigned RemainingTokenColumns =
2236e5dd7070Spatrick       Token->getRemainingLength(0, TailOffset, ContentStartColumn);
2237e5dd7070Spatrick   // Adapt the start of the token, for example indent.
2238e5dd7070Spatrick   if (!DryRun)
2239e5dd7070Spatrick     Token->adaptStartOfLine(0, Whitespaces);
2240e5dd7070Spatrick 
2241e5dd7070Spatrick   unsigned ContentIndent = 0;
2242e5dd7070Spatrick   unsigned Penalty = 0;
2243e5dd7070Spatrick   LLVM_DEBUG(llvm::dbgs() << "Breaking protruding token at column "
2244e5dd7070Spatrick                           << StartColumn << ".\n");
2245e5dd7070Spatrick   for (unsigned LineIndex = 0, EndIndex = Token->getLineCount();
2246e5dd7070Spatrick        LineIndex != EndIndex; ++LineIndex) {
2247e5dd7070Spatrick     LLVM_DEBUG(llvm::dbgs()
2248e5dd7070Spatrick                << "  Line: " << LineIndex << " (Reflow: " << Reflow << ")\n");
2249e5dd7070Spatrick     NewBreakBefore = false;
2250e5dd7070Spatrick     // If we did reflow the previous line, we'll try reflowing again. Otherwise
2251e5dd7070Spatrick     // we'll start reflowing if the current line is broken or whitespace is
2252e5dd7070Spatrick     // compressed.
2253e5dd7070Spatrick     bool TryReflow = Reflow;
2254e5dd7070Spatrick     // Break the current token until we can fit the rest of the line.
2255e5dd7070Spatrick     while (ContentStartColumn + RemainingTokenColumns > ColumnLimit) {
2256e5dd7070Spatrick       LLVM_DEBUG(llvm::dbgs() << "    Over limit, need: "
2257e5dd7070Spatrick                               << (ContentStartColumn + RemainingTokenColumns)
2258e5dd7070Spatrick                               << ", space: " << ColumnLimit
2259e5dd7070Spatrick                               << ", reflown prefix: " << ContentStartColumn
2260e5dd7070Spatrick                               << ", offset in line: " << TailOffset << "\n");
2261e5dd7070Spatrick       // If the current token doesn't fit, find the latest possible split in the
2262e5dd7070Spatrick       // current line so that breaking at it will be under the column limit.
2263e5dd7070Spatrick       // FIXME: Use the earliest possible split while reflowing to correctly
2264e5dd7070Spatrick       // compress whitespace within a line.
2265e5dd7070Spatrick       BreakableToken::Split Split =
2266e5dd7070Spatrick           Token->getSplit(LineIndex, TailOffset, ColumnLimit,
2267e5dd7070Spatrick                           ContentStartColumn, CommentPragmasRegex);
2268e5dd7070Spatrick       if (Split.first == StringRef::npos) {
2269e5dd7070Spatrick         // No break opportunity - update the penalty and continue with the next
2270e5dd7070Spatrick         // logical line.
2271*12c85518Srobert         if (LineIndex < EndIndex - 1) {
2272e5dd7070Spatrick           // The last line's penalty is handled in addNextStateToQueue() or when
2273e5dd7070Spatrick           // calling replaceWhitespaceAfterLastLine below.
2274e5dd7070Spatrick           Penalty += Style.PenaltyExcessCharacter *
2275e5dd7070Spatrick                      (ContentStartColumn + RemainingTokenColumns - ColumnLimit);
2276*12c85518Srobert         }
2277e5dd7070Spatrick         LLVM_DEBUG(llvm::dbgs() << "    No break opportunity.\n");
2278e5dd7070Spatrick         break;
2279e5dd7070Spatrick       }
2280e5dd7070Spatrick       assert(Split.first != 0);
2281e5dd7070Spatrick 
2282e5dd7070Spatrick       if (Token->supportsReflow()) {
2283e5dd7070Spatrick         // Check whether the next natural split point after the current one can
2284e5dd7070Spatrick         // still fit the line, either because we can compress away whitespace,
2285e5dd7070Spatrick         // or because the penalty the excess characters introduce is lower than
2286e5dd7070Spatrick         // the break penalty.
2287e5dd7070Spatrick         // We only do this for tokens that support reflowing, and thus allow us
2288e5dd7070Spatrick         // to change the whitespace arbitrarily (e.g. comments).
2289e5dd7070Spatrick         // Other tokens, like string literals, can be broken on arbitrary
2290e5dd7070Spatrick         // positions.
2291e5dd7070Spatrick 
2292e5dd7070Spatrick         // First, compute the columns from TailOffset to the next possible split
2293e5dd7070Spatrick         // position.
2294e5dd7070Spatrick         // For example:
2295e5dd7070Spatrick         // ColumnLimit:     |
2296e5dd7070Spatrick         // // Some text   that    breaks
2297e5dd7070Spatrick         //    ^ tail offset
2298e5dd7070Spatrick         //             ^-- split
2299e5dd7070Spatrick         //    ^-------- to split columns
2300e5dd7070Spatrick         //                    ^--- next split
2301e5dd7070Spatrick         //    ^--------------- to next split columns
2302e5dd7070Spatrick         unsigned ToSplitColumns = Token->getRangeLength(
2303e5dd7070Spatrick             LineIndex, TailOffset, Split.first, ContentStartColumn);
2304e5dd7070Spatrick         LLVM_DEBUG(llvm::dbgs() << "    ToSplit: " << ToSplitColumns << "\n");
2305e5dd7070Spatrick 
2306e5dd7070Spatrick         BreakableToken::Split NextSplit = Token->getSplit(
2307e5dd7070Spatrick             LineIndex, TailOffset + Split.first + Split.second, ColumnLimit,
2308e5dd7070Spatrick             ContentStartColumn + ToSplitColumns + 1, CommentPragmasRegex);
2309e5dd7070Spatrick         // Compute the columns necessary to fit the next non-breakable sequence
2310e5dd7070Spatrick         // into the current line.
2311e5dd7070Spatrick         unsigned ToNextSplitColumns = 0;
2312e5dd7070Spatrick         if (NextSplit.first == StringRef::npos) {
2313e5dd7070Spatrick           ToNextSplitColumns = Token->getRemainingLength(LineIndex, TailOffset,
2314e5dd7070Spatrick                                                          ContentStartColumn);
2315e5dd7070Spatrick         } else {
2316e5dd7070Spatrick           ToNextSplitColumns = Token->getRangeLength(
2317e5dd7070Spatrick               LineIndex, TailOffset,
2318e5dd7070Spatrick               Split.first + Split.second + NextSplit.first, ContentStartColumn);
2319e5dd7070Spatrick         }
2320e5dd7070Spatrick         // Compress the whitespace between the break and the start of the next
2321e5dd7070Spatrick         // unbreakable sequence.
2322e5dd7070Spatrick         ToNextSplitColumns =
2323e5dd7070Spatrick             Token->getLengthAfterCompression(ToNextSplitColumns, Split);
2324e5dd7070Spatrick         LLVM_DEBUG(llvm::dbgs()
2325e5dd7070Spatrick                    << "    ContentStartColumn: " << ContentStartColumn << "\n");
2326e5dd7070Spatrick         LLVM_DEBUG(llvm::dbgs()
2327e5dd7070Spatrick                    << "    ToNextSplit: " << ToNextSplitColumns << "\n");
2328e5dd7070Spatrick         // If the whitespace compression makes us fit, continue on the current
2329e5dd7070Spatrick         // line.
2330e5dd7070Spatrick         bool ContinueOnLine =
2331e5dd7070Spatrick             ContentStartColumn + ToNextSplitColumns <= ColumnLimit;
2332e5dd7070Spatrick         unsigned ExcessCharactersPenalty = 0;
2333e5dd7070Spatrick         if (!ContinueOnLine && !Strict) {
2334e5dd7070Spatrick           // Similarly, if the excess characters' penalty is lower than the
2335e5dd7070Spatrick           // penalty of introducing a new break, continue on the current line.
2336e5dd7070Spatrick           ExcessCharactersPenalty =
2337e5dd7070Spatrick               (ContentStartColumn + ToNextSplitColumns - ColumnLimit) *
2338e5dd7070Spatrick               Style.PenaltyExcessCharacter;
2339e5dd7070Spatrick           LLVM_DEBUG(llvm::dbgs()
2340e5dd7070Spatrick                      << "    Penalty excess: " << ExcessCharactersPenalty
2341e5dd7070Spatrick                      << "\n            break : " << NewBreakPenalty << "\n");
2342e5dd7070Spatrick           if (ExcessCharactersPenalty < NewBreakPenalty) {
2343e5dd7070Spatrick             Exceeded = true;
2344e5dd7070Spatrick             ContinueOnLine = true;
2345e5dd7070Spatrick           }
2346e5dd7070Spatrick         }
2347e5dd7070Spatrick         if (ContinueOnLine) {
2348e5dd7070Spatrick           LLVM_DEBUG(llvm::dbgs() << "    Continuing on line...\n");
2349e5dd7070Spatrick           // The current line fits after compressing the whitespace - reflow
2350e5dd7070Spatrick           // the next line into it if possible.
2351e5dd7070Spatrick           TryReflow = true;
2352*12c85518Srobert           if (!DryRun) {
2353e5dd7070Spatrick             Token->compressWhitespace(LineIndex, TailOffset, Split,
2354e5dd7070Spatrick                                       Whitespaces);
2355*12c85518Srobert           }
2356e5dd7070Spatrick           // When we continue on the same line, leave one space between content.
2357e5dd7070Spatrick           ContentStartColumn += ToSplitColumns + 1;
2358e5dd7070Spatrick           Penalty += ExcessCharactersPenalty;
2359e5dd7070Spatrick           TailOffset += Split.first + Split.second;
2360e5dd7070Spatrick           RemainingTokenColumns = Token->getRemainingLength(
2361e5dd7070Spatrick               LineIndex, TailOffset, ContentStartColumn);
2362e5dd7070Spatrick           continue;
2363e5dd7070Spatrick         }
2364e5dd7070Spatrick       }
2365e5dd7070Spatrick       LLVM_DEBUG(llvm::dbgs() << "    Breaking...\n");
2366e5dd7070Spatrick       // Update the ContentIndent only if the current line was not reflown with
2367e5dd7070Spatrick       // the previous line, since in that case the previous line should still
2368e5dd7070Spatrick       // determine the ContentIndent. Also never intent the last line.
2369e5dd7070Spatrick       if (!Reflow)
2370e5dd7070Spatrick         ContentIndent = Token->getContentIndent(LineIndex);
2371e5dd7070Spatrick       LLVM_DEBUG(llvm::dbgs()
2372e5dd7070Spatrick                  << "    ContentIndent: " << ContentIndent << "\n");
2373e5dd7070Spatrick       ContentStartColumn = ContentIndent + Token->getContentStartColumn(
2374e5dd7070Spatrick                                                LineIndex, /*Break=*/true);
2375e5dd7070Spatrick 
2376e5dd7070Spatrick       unsigned NewRemainingTokenColumns = Token->getRemainingLength(
2377e5dd7070Spatrick           LineIndex, TailOffset + Split.first + Split.second,
2378e5dd7070Spatrick           ContentStartColumn);
2379e5dd7070Spatrick       if (NewRemainingTokenColumns == 0) {
2380e5dd7070Spatrick         // No content to indent.
2381e5dd7070Spatrick         ContentIndent = 0;
2382e5dd7070Spatrick         ContentStartColumn =
2383e5dd7070Spatrick             Token->getContentStartColumn(LineIndex, /*Break=*/true);
2384e5dd7070Spatrick         NewRemainingTokenColumns = Token->getRemainingLength(
2385e5dd7070Spatrick             LineIndex, TailOffset + Split.first + Split.second,
2386e5dd7070Spatrick             ContentStartColumn);
2387e5dd7070Spatrick       }
2388e5dd7070Spatrick 
2389e5dd7070Spatrick       // When breaking before a tab character, it may be moved by a few columns,
2390e5dd7070Spatrick       // but will still be expanded to the next tab stop, so we don't save any
2391e5dd7070Spatrick       // columns.
2392*12c85518Srobert       if (NewRemainingTokenColumns >= RemainingTokenColumns) {
2393e5dd7070Spatrick         // FIXME: Do we need to adjust the penalty?
2394e5dd7070Spatrick         break;
2395e5dd7070Spatrick       }
2396e5dd7070Spatrick 
2397e5dd7070Spatrick       LLVM_DEBUG(llvm::dbgs() << "    Breaking at: " << TailOffset + Split.first
2398e5dd7070Spatrick                               << ", " << Split.second << "\n");
2399*12c85518Srobert       if (!DryRun) {
2400e5dd7070Spatrick         Token->insertBreak(LineIndex, TailOffset, Split, ContentIndent,
2401e5dd7070Spatrick                            Whitespaces);
2402*12c85518Srobert       }
2403e5dd7070Spatrick 
2404e5dd7070Spatrick       Penalty += NewBreakPenalty;
2405e5dd7070Spatrick       TailOffset += Split.first + Split.second;
2406e5dd7070Spatrick       RemainingTokenColumns = NewRemainingTokenColumns;
2407e5dd7070Spatrick       BreakInserted = true;
2408e5dd7070Spatrick       NewBreakBefore = true;
2409e5dd7070Spatrick     }
2410e5dd7070Spatrick     // In case there's another line, prepare the state for the start of the next
2411e5dd7070Spatrick     // line.
2412e5dd7070Spatrick     if (LineIndex + 1 != EndIndex) {
2413e5dd7070Spatrick       unsigned NextLineIndex = LineIndex + 1;
2414*12c85518Srobert       if (NewBreakBefore) {
2415e5dd7070Spatrick         // After breaking a line, try to reflow the next line into the current
2416e5dd7070Spatrick         // one once RemainingTokenColumns fits.
2417e5dd7070Spatrick         TryReflow = true;
2418*12c85518Srobert       }
2419e5dd7070Spatrick       if (TryReflow) {
2420e5dd7070Spatrick         // We decided that we want to try reflowing the next line into the
2421e5dd7070Spatrick         // current one.
2422e5dd7070Spatrick         // We will now adjust the state as if the reflow is successful (in
2423e5dd7070Spatrick         // preparation for the next line), and see whether that works. If we
2424e5dd7070Spatrick         // decide that we cannot reflow, we will later reset the state to the
2425e5dd7070Spatrick         // start of the next line.
2426e5dd7070Spatrick         Reflow = false;
2427e5dd7070Spatrick         // As we did not continue breaking the line, RemainingTokenColumns is
2428e5dd7070Spatrick         // known to fit after ContentStartColumn. Adapt ContentStartColumn to
2429e5dd7070Spatrick         // the position at which we want to format the next line if we do
2430e5dd7070Spatrick         // actually reflow.
2431e5dd7070Spatrick         // When we reflow, we need to add a space between the end of the current
2432e5dd7070Spatrick         // line and the next line's start column.
2433e5dd7070Spatrick         ContentStartColumn += RemainingTokenColumns + 1;
2434e5dd7070Spatrick         // Get the split that we need to reflow next logical line into the end
2435e5dd7070Spatrick         // of the current one; the split will include any leading whitespace of
2436e5dd7070Spatrick         // the next logical line.
2437e5dd7070Spatrick         BreakableToken::Split SplitBeforeNext =
2438e5dd7070Spatrick             Token->getReflowSplit(NextLineIndex, CommentPragmasRegex);
2439e5dd7070Spatrick         LLVM_DEBUG(llvm::dbgs()
2440e5dd7070Spatrick                    << "    Size of reflown text: " << ContentStartColumn
2441e5dd7070Spatrick                    << "\n    Potential reflow split: ");
2442e5dd7070Spatrick         if (SplitBeforeNext.first != StringRef::npos) {
2443e5dd7070Spatrick           LLVM_DEBUG(llvm::dbgs() << SplitBeforeNext.first << ", "
2444e5dd7070Spatrick                                   << SplitBeforeNext.second << "\n");
2445e5dd7070Spatrick           TailOffset = SplitBeforeNext.first + SplitBeforeNext.second;
2446e5dd7070Spatrick           // If the rest of the next line fits into the current line below the
2447e5dd7070Spatrick           // column limit, we can safely reflow.
2448e5dd7070Spatrick           RemainingTokenColumns = Token->getRemainingLength(
2449e5dd7070Spatrick               NextLineIndex, TailOffset, ContentStartColumn);
2450e5dd7070Spatrick           Reflow = true;
2451e5dd7070Spatrick           if (ContentStartColumn + RemainingTokenColumns > ColumnLimit) {
2452e5dd7070Spatrick             LLVM_DEBUG(llvm::dbgs()
2453e5dd7070Spatrick                        << "    Over limit after reflow, need: "
2454e5dd7070Spatrick                        << (ContentStartColumn + RemainingTokenColumns)
2455e5dd7070Spatrick                        << ", space: " << ColumnLimit
2456e5dd7070Spatrick                        << ", reflown prefix: " << ContentStartColumn
2457e5dd7070Spatrick                        << ", offset in line: " << TailOffset << "\n");
2458e5dd7070Spatrick             // If the whole next line does not fit, try to find a point in
2459e5dd7070Spatrick             // the next line at which we can break so that attaching the part
2460e5dd7070Spatrick             // of the next line to that break point onto the current line is
2461e5dd7070Spatrick             // below the column limit.
2462e5dd7070Spatrick             BreakableToken::Split Split =
2463e5dd7070Spatrick                 Token->getSplit(NextLineIndex, TailOffset, ColumnLimit,
2464e5dd7070Spatrick                                 ContentStartColumn, CommentPragmasRegex);
2465e5dd7070Spatrick             if (Split.first == StringRef::npos) {
2466e5dd7070Spatrick               LLVM_DEBUG(llvm::dbgs() << "    Did not find later break\n");
2467e5dd7070Spatrick               Reflow = false;
2468e5dd7070Spatrick             } else {
2469e5dd7070Spatrick               // Check whether the first split point gets us below the column
2470e5dd7070Spatrick               // limit. Note that we will execute this split below as part of
2471e5dd7070Spatrick               // the normal token breaking and reflow logic within the line.
2472e5dd7070Spatrick               unsigned ToSplitColumns = Token->getRangeLength(
2473e5dd7070Spatrick                   NextLineIndex, TailOffset, Split.first, ContentStartColumn);
2474e5dd7070Spatrick               if (ContentStartColumn + ToSplitColumns > ColumnLimit) {
2475e5dd7070Spatrick                 LLVM_DEBUG(llvm::dbgs() << "    Next split protrudes, need: "
2476e5dd7070Spatrick                                         << (ContentStartColumn + ToSplitColumns)
2477e5dd7070Spatrick                                         << ", space: " << ColumnLimit);
2478e5dd7070Spatrick                 unsigned ExcessCharactersPenalty =
2479e5dd7070Spatrick                     (ContentStartColumn + ToSplitColumns - ColumnLimit) *
2480e5dd7070Spatrick                     Style.PenaltyExcessCharacter;
2481*12c85518Srobert                 if (NewBreakPenalty < ExcessCharactersPenalty)
2482e5dd7070Spatrick                   Reflow = false;
2483e5dd7070Spatrick               }
2484e5dd7070Spatrick             }
2485e5dd7070Spatrick           }
2486e5dd7070Spatrick         } else {
2487e5dd7070Spatrick           LLVM_DEBUG(llvm::dbgs() << "not found.\n");
2488e5dd7070Spatrick         }
2489e5dd7070Spatrick       }
2490e5dd7070Spatrick       if (!Reflow) {
2491e5dd7070Spatrick         // If we didn't reflow into the next line, the only space to consider is
2492e5dd7070Spatrick         // the next logical line. Reset our state to match the start of the next
2493e5dd7070Spatrick         // line.
2494e5dd7070Spatrick         TailOffset = 0;
2495e5dd7070Spatrick         ContentStartColumn =
2496e5dd7070Spatrick             Token->getContentStartColumn(NextLineIndex, /*Break=*/false);
2497e5dd7070Spatrick         RemainingTokenColumns = Token->getRemainingLength(
2498e5dd7070Spatrick             NextLineIndex, TailOffset, ContentStartColumn);
2499e5dd7070Spatrick         // Adapt the start of the token, for example indent.
2500e5dd7070Spatrick         if (!DryRun)
2501e5dd7070Spatrick           Token->adaptStartOfLine(NextLineIndex, Whitespaces);
2502e5dd7070Spatrick       } else {
2503e5dd7070Spatrick         // If we found a reflow split and have added a new break before the next
2504e5dd7070Spatrick         // line, we are going to remove the line break at the start of the next
2505e5dd7070Spatrick         // logical line. For example, here we'll add a new line break after
2506e5dd7070Spatrick         // 'text', and subsequently delete the line break between 'that' and
2507e5dd7070Spatrick         // 'reflows'.
2508e5dd7070Spatrick         //   // some text that
2509e5dd7070Spatrick         //   // reflows
2510e5dd7070Spatrick         // ->
2511e5dd7070Spatrick         //   // some text
2512e5dd7070Spatrick         //   // that reflows
2513e5dd7070Spatrick         // When adding the line break, we also added the penalty for it, so we
2514e5dd7070Spatrick         // need to subtract that penalty again when we remove the line break due
2515e5dd7070Spatrick         // to reflowing.
2516e5dd7070Spatrick         if (NewBreakBefore) {
2517e5dd7070Spatrick           assert(Penalty >= NewBreakPenalty);
2518e5dd7070Spatrick           Penalty -= NewBreakPenalty;
2519e5dd7070Spatrick         }
2520e5dd7070Spatrick         if (!DryRun)
2521e5dd7070Spatrick           Token->reflow(NextLineIndex, Whitespaces);
2522e5dd7070Spatrick       }
2523e5dd7070Spatrick     }
2524e5dd7070Spatrick   }
2525e5dd7070Spatrick 
2526e5dd7070Spatrick   BreakableToken::Split SplitAfterLastLine =
2527e5dd7070Spatrick       Token->getSplitAfterLastLine(TailOffset);
2528e5dd7070Spatrick   if (SplitAfterLastLine.first != StringRef::npos) {
2529e5dd7070Spatrick     LLVM_DEBUG(llvm::dbgs() << "Replacing whitespace after last line.\n");
2530e5dd7070Spatrick 
2531e5dd7070Spatrick     // We add the last line's penalty here, since that line is going to be split
2532e5dd7070Spatrick     // now.
2533e5dd7070Spatrick     Penalty += Style.PenaltyExcessCharacter *
2534e5dd7070Spatrick                (ContentStartColumn + RemainingTokenColumns - ColumnLimit);
2535e5dd7070Spatrick 
2536*12c85518Srobert     if (!DryRun) {
2537e5dd7070Spatrick       Token->replaceWhitespaceAfterLastLine(TailOffset, SplitAfterLastLine,
2538e5dd7070Spatrick                                             Whitespaces);
2539*12c85518Srobert     }
2540e5dd7070Spatrick     ContentStartColumn =
2541e5dd7070Spatrick         Token->getContentStartColumn(Token->getLineCount() - 1, /*Break=*/true);
2542e5dd7070Spatrick     RemainingTokenColumns = Token->getRemainingLength(
2543e5dd7070Spatrick         Token->getLineCount() - 1,
2544e5dd7070Spatrick         TailOffset + SplitAfterLastLine.first + SplitAfterLastLine.second,
2545e5dd7070Spatrick         ContentStartColumn);
2546e5dd7070Spatrick   }
2547e5dd7070Spatrick 
2548e5dd7070Spatrick   State.Column = ContentStartColumn + RemainingTokenColumns -
2549e5dd7070Spatrick                  Current.UnbreakableTailLength;
2550e5dd7070Spatrick 
2551e5dd7070Spatrick   if (BreakInserted) {
2552e5dd7070Spatrick     // If we break the token inside a parameter list, we need to break before
2553e5dd7070Spatrick     // the next parameter on all levels, so that the next parameter is clearly
2554e5dd7070Spatrick     // visible. Line comments already introduce a break.
2555*12c85518Srobert     if (Current.isNot(TT_LineComment))
2556*12c85518Srobert       for (ParenState &Paren : State.Stack)
2557*12c85518Srobert         Paren.BreakBeforeParameter = true;
2558e5dd7070Spatrick 
2559e5dd7070Spatrick     if (Current.is(TT_BlockComment))
2560e5dd7070Spatrick       State.NoContinuation = true;
2561e5dd7070Spatrick 
2562e5dd7070Spatrick     State.Stack.back().LastSpace = StartColumn;
2563e5dd7070Spatrick   }
2564e5dd7070Spatrick 
2565e5dd7070Spatrick   Token->updateNextToken(State);
2566e5dd7070Spatrick 
2567e5dd7070Spatrick   return {Penalty, Exceeded};
2568e5dd7070Spatrick }
2569e5dd7070Spatrick 
getColumnLimit(const LineState & State) const2570e5dd7070Spatrick unsigned ContinuationIndenter::getColumnLimit(const LineState &State) const {
2571*12c85518Srobert   // In preprocessor directives reserve two chars for trailing " \".
2572e5dd7070Spatrick   return Style.ColumnLimit - (State.Line->InPPDirective ? 2 : 0);
2573e5dd7070Spatrick }
2574e5dd7070Spatrick 
nextIsMultilineString(const LineState & State)2575e5dd7070Spatrick bool ContinuationIndenter::nextIsMultilineString(const LineState &State) {
2576e5dd7070Spatrick   const FormatToken &Current = *State.NextToken;
2577e5dd7070Spatrick   if (!Current.isStringLiteral() || Current.is(TT_ImplicitStringLiteral))
2578e5dd7070Spatrick     return false;
2579e5dd7070Spatrick   // We never consider raw string literals "multiline" for the purpose of
2580e5dd7070Spatrick   // AlwaysBreakBeforeMultilineStrings implementation as they are special-cased
2581e5dd7070Spatrick   // (see TokenAnnotator::mustBreakBefore().
2582e5dd7070Spatrick   if (Current.TokenText.startswith("R\""))
2583e5dd7070Spatrick     return false;
2584e5dd7070Spatrick   if (Current.IsMultiline)
2585e5dd7070Spatrick     return true;
2586e5dd7070Spatrick   if (Current.getNextNonComment() &&
2587*12c85518Srobert       Current.getNextNonComment()->isStringLiteral()) {
2588e5dd7070Spatrick     return true; // Implicit concatenation.
2589*12c85518Srobert   }
2590e5dd7070Spatrick   if (Style.ColumnLimit != 0 && Style.BreakStringLiterals &&
2591e5dd7070Spatrick       State.Column + Current.ColumnWidth + Current.UnbreakableTailLength >
2592*12c85518Srobert           Style.ColumnLimit) {
2593e5dd7070Spatrick     return true; // String will be split.
2594*12c85518Srobert   }
2595e5dd7070Spatrick   return false;
2596e5dd7070Spatrick }
2597e5dd7070Spatrick 
2598e5dd7070Spatrick } // namespace format
2599e5dd7070Spatrick } // namespace clang
2600