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