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