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