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