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