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