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