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