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