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