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