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