[AMDGPU][AsmParser][NFC] Get rid of custom default operand handlers.
[llvm-project.git] / clang / lib / Format / ContinuationIndenter.cpp
blobf6f6bf61f1c3722384ceb15d1e762f84e6ec8ad3
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) ||
752 Previous.isOneOf(BK_BracedInit, TT_VerilogMultiLineListLParen))) {
753 CurrentState.Indent = State.Column + Spaces;
754 CurrentState.IsAligned = true;
756 if (CurrentState.AvoidBinPacking && startsNextParameter(Current, Style))
757 CurrentState.NoLineBreak = true;
758 if (startsSegmentOfBuilderTypeCall(Current) &&
759 State.Column > getNewLineColumn(State)) {
760 CurrentState.ContainsUnwrappedBuilder = true;
763 if (Current.is(TT_LambdaArrow) && Style.Language == FormatStyle::LK_Java)
764 CurrentState.NoLineBreak = true;
765 if (Current.isMemberAccess() && Previous.is(tok::r_paren) &&
766 (Previous.MatchingParen &&
767 (Previous.TotalLength - Previous.MatchingParen->TotalLength > 10))) {
768 // If there is a function call with long parameters, break before trailing
769 // calls. This prevents things like:
770 // EXPECT_CALL(SomeLongParameter).Times(
771 // 2);
772 // We don't want to do this for short parameters as they can just be
773 // indexes.
774 CurrentState.NoLineBreak = true;
777 // Don't allow the RHS of an operator to be split over multiple lines unless
778 // there is a line-break right after the operator.
779 // Exclude relational operators, as there, it is always more desirable to
780 // have the LHS 'left' of the RHS.
781 const FormatToken *P = Current.getPreviousNonComment();
782 if (!Current.is(tok::comment) && P &&
783 (P->isOneOf(TT_BinaryOperator, tok::comma) ||
784 (P->is(TT_ConditionalExpr) && P->is(tok::colon))) &&
785 !P->isOneOf(TT_OverloadedOperator, TT_CtorInitializerComma) &&
786 P->getPrecedence() != prec::Assignment &&
787 P->getPrecedence() != prec::Relational &&
788 P->getPrecedence() != prec::Spaceship) {
789 bool BreakBeforeOperator =
790 P->MustBreakBefore || P->is(tok::lessless) ||
791 (P->is(TT_BinaryOperator) &&
792 Style.BreakBeforeBinaryOperators != FormatStyle::BOS_None) ||
793 (P->is(TT_ConditionalExpr) && Style.BreakBeforeTernaryOperators);
794 // Don't do this if there are only two operands. In these cases, there is
795 // always a nice vertical separation between them and the extra line break
796 // does not help.
797 bool HasTwoOperands =
798 P->OperatorIndex == 0 && !P->NextOperator && !P->is(TT_ConditionalExpr);
799 if ((!BreakBeforeOperator &&
800 !(HasTwoOperands &&
801 Style.AlignOperands != FormatStyle::OAS_DontAlign)) ||
802 (!CurrentState.LastOperatorWrapped && BreakBeforeOperator)) {
803 CurrentState.NoLineBreakInOperand = true;
807 State.Column += Spaces;
808 if (Current.isNot(tok::comment) && Previous.is(tok::l_paren) &&
809 Previous.Previous &&
810 (Previous.Previous->is(tok::kw_for) || Previous.Previous->isIf())) {
811 // Treat the condition inside an if as if it was a second function
812 // parameter, i.e. let nested calls have a continuation indent.
813 CurrentState.LastSpace = State.Column;
814 CurrentState.NestedBlockIndent = State.Column;
815 } else if (!Current.isOneOf(tok::comment, tok::caret) &&
816 ((Previous.is(tok::comma) &&
817 !Previous.is(TT_OverloadedOperator)) ||
818 (Previous.is(tok::colon) && Previous.is(TT_ObjCMethodExpr)))) {
819 CurrentState.LastSpace = State.Column;
820 } else if (Previous.is(TT_CtorInitializerColon) &&
821 (!Current.isTrailingComment() || Current.NewlinesBefore > 0) &&
822 Style.BreakConstructorInitializers ==
823 FormatStyle::BCIS_AfterColon) {
824 CurrentState.Indent = State.Column;
825 CurrentState.LastSpace = State.Column;
826 } else if ((Previous.isOneOf(TT_BinaryOperator, TT_ConditionalExpr,
827 TT_CtorInitializerColon)) &&
828 ((Previous.getPrecedence() != prec::Assignment &&
829 (Previous.isNot(tok::lessless) || Previous.OperatorIndex != 0 ||
830 Previous.NextOperator)) ||
831 Current.StartsBinaryExpression)) {
832 // Indent relative to the RHS of the expression unless this is a simple
833 // assignment without binary expression on the RHS. Also indent relative to
834 // unary operators and the colons of constructor initializers.
835 if (Style.BreakBeforeBinaryOperators == FormatStyle::BOS_None)
836 CurrentState.LastSpace = State.Column;
837 } else if (Previous.is(TT_InheritanceColon)) {
838 CurrentState.Indent = State.Column;
839 CurrentState.LastSpace = State.Column;
840 } else if (Current.is(TT_CSharpGenericTypeConstraintColon)) {
841 CurrentState.ColonPos = State.Column;
842 } else if (Previous.opensScope()) {
843 // If a function has a trailing call, indent all parameters from the
844 // opening parenthesis. This avoids confusing indents like:
845 // OuterFunction(InnerFunctionCall( // break
846 // ParameterToInnerFunction)) // break
847 // .SecondInnerFunctionCall();
848 if (Previous.MatchingParen) {
849 const FormatToken *Next = Previous.MatchingParen->getNextNonComment();
850 if (Next && Next->isMemberAccess() && State.Stack.size() > 1 &&
851 State.Stack[State.Stack.size() - 2].CallContinuation == 0) {
852 CurrentState.LastSpace = State.Column;
858 unsigned ContinuationIndenter::addTokenOnNewLine(LineState &State,
859 bool DryRun) {
860 FormatToken &Current = *State.NextToken;
861 assert(State.NextToken->Previous);
862 const FormatToken &Previous = *State.NextToken->Previous;
863 auto &CurrentState = State.Stack.back();
865 // Extra penalty that needs to be added because of the way certain line
866 // breaks are chosen.
867 unsigned Penalty = 0;
869 const FormatToken *PreviousNonComment = Current.getPreviousNonComment();
870 const FormatToken *NextNonComment = Previous.getNextNonComment();
871 if (!NextNonComment)
872 NextNonComment = &Current;
873 // The first line break on any NestingLevel causes an extra penalty in order
874 // prefer similar line breaks.
875 if (!CurrentState.ContainsLineBreak)
876 Penalty += 15;
877 CurrentState.ContainsLineBreak = true;
879 Penalty += State.NextToken->SplitPenalty;
881 // Breaking before the first "<<" is generally not desirable if the LHS is
882 // short. Also always add the penalty if the LHS is split over multiple lines
883 // to avoid unnecessary line breaks that just work around this penalty.
884 if (NextNonComment->is(tok::lessless) && CurrentState.FirstLessLess == 0 &&
885 (State.Column <= Style.ColumnLimit / 3 ||
886 CurrentState.BreakBeforeParameter)) {
887 Penalty += Style.PenaltyBreakFirstLessLess;
890 State.Column = getNewLineColumn(State);
892 // Add Penalty proportional to amount of whitespace away from FirstColumn
893 // This tends to penalize several lines that are far-right indented,
894 // and prefers a line-break prior to such a block, e.g:
896 // Constructor() :
897 // member(value), looooooooooooooooong_member(
898 // looooooooooong_call(param_1, param_2, param_3))
899 // would then become
900 // Constructor() :
901 // member(value),
902 // looooooooooooooooong_member(
903 // looooooooooong_call(param_1, param_2, param_3))
904 if (State.Column > State.FirstIndent) {
905 Penalty +=
906 Style.PenaltyIndentedWhitespace * (State.Column - State.FirstIndent);
909 // Indent nested blocks relative to this column, unless in a very specific
910 // JavaScript special case where:
912 // var loooooong_name =
913 // function() {
914 // // code
915 // }
917 // is common and should be formatted like a free-standing function. The same
918 // goes for wrapping before the lambda return type arrow.
919 if (!Current.is(TT_LambdaArrow) &&
920 (!Style.isJavaScript() || Current.NestingLevel != 0 ||
921 !PreviousNonComment || !PreviousNonComment->is(tok::equal) ||
922 !Current.isOneOf(Keywords.kw_async, Keywords.kw_function))) {
923 CurrentState.NestedBlockIndent = State.Column;
926 if (NextNonComment->isMemberAccess()) {
927 if (CurrentState.CallContinuation == 0)
928 CurrentState.CallContinuation = State.Column;
929 } else if (NextNonComment->is(TT_SelectorName)) {
930 if (!CurrentState.ObjCSelectorNameFound) {
931 if (NextNonComment->LongestObjCSelectorName == 0) {
932 CurrentState.AlignColons = false;
933 } else {
934 CurrentState.ColonPos =
935 (shouldIndentWrappedSelectorName(Style, State.Line->Type)
936 ? std::max(CurrentState.Indent,
937 State.FirstIndent + Style.ContinuationIndentWidth)
938 : CurrentState.Indent) +
939 std::max(NextNonComment->LongestObjCSelectorName,
940 NextNonComment->ColumnWidth);
942 } else if (CurrentState.AlignColons &&
943 CurrentState.ColonPos <= NextNonComment->ColumnWidth) {
944 CurrentState.ColonPos = State.Column + NextNonComment->ColumnWidth;
946 } else if (PreviousNonComment && PreviousNonComment->is(tok::colon) &&
947 PreviousNonComment->isOneOf(TT_ObjCMethodExpr, TT_DictLiteral)) {
948 // FIXME: This is hacky, find a better way. The problem is that in an ObjC
949 // method expression, the block should be aligned to the line starting it,
950 // e.g.:
951 // [aaaaaaaaaaaaaaa aaaaaaaaa: \\ break for some reason
952 // ^(int *i) {
953 // // ...
954 // }];
955 // Thus, we set LastSpace of the next higher NestingLevel, to which we move
956 // when we consume all of the "}"'s FakeRParens at the "{".
957 if (State.Stack.size() > 1) {
958 State.Stack[State.Stack.size() - 2].LastSpace =
959 std::max(CurrentState.LastSpace, CurrentState.Indent) +
960 Style.ContinuationIndentWidth;
964 if ((PreviousNonComment &&
965 PreviousNonComment->isOneOf(tok::comma, tok::semi) &&
966 !CurrentState.AvoidBinPacking) ||
967 Previous.is(TT_BinaryOperator)) {
968 CurrentState.BreakBeforeParameter = false;
970 if (PreviousNonComment &&
971 (PreviousNonComment->isOneOf(TT_TemplateCloser, TT_JavaAnnotation) ||
972 PreviousNonComment->ClosesRequiresClause) &&
973 Current.NestingLevel == 0) {
974 CurrentState.BreakBeforeParameter = false;
976 if (NextNonComment->is(tok::question) ||
977 (PreviousNonComment && PreviousNonComment->is(tok::question))) {
978 CurrentState.BreakBeforeParameter = true;
980 if (Current.is(TT_BinaryOperator) && Current.CanBreakBefore)
981 CurrentState.BreakBeforeParameter = false;
983 if (!DryRun) {
984 unsigned MaxEmptyLinesToKeep = Style.MaxEmptyLinesToKeep + 1;
985 if (Current.is(tok::r_brace) && Current.MatchingParen &&
986 // Only strip trailing empty lines for l_braces that have children, i.e.
987 // for function expressions (lambdas, arrows, etc).
988 !Current.MatchingParen->Children.empty()) {
989 // lambdas and arrow functions are expressions, thus their r_brace is not
990 // on its own line, and thus not covered by UnwrappedLineFormatter's logic
991 // about removing empty lines on closing blocks. Special case them here.
992 MaxEmptyLinesToKeep = 1;
994 unsigned Newlines =
995 std::max(1u, std::min(Current.NewlinesBefore, MaxEmptyLinesToKeep));
996 bool ContinuePPDirective =
997 State.Line->InPPDirective && State.Line->Type != LT_ImportStatement;
998 Whitespaces.replaceWhitespace(Current, Newlines, State.Column, State.Column,
999 CurrentState.IsAligned, ContinuePPDirective);
1002 if (!Current.isTrailingComment())
1003 CurrentState.LastSpace = State.Column;
1004 if (Current.is(tok::lessless)) {
1005 // If we are breaking before a "<<", we always want to indent relative to
1006 // RHS. This is necessary only for "<<", as we special-case it and don't
1007 // always indent relative to the RHS.
1008 CurrentState.LastSpace += 3; // 3 -> width of "<< ".
1011 State.StartOfLineLevel = Current.NestingLevel;
1012 State.LowestLevelOnLine = Current.NestingLevel;
1014 // Any break on this level means that the parent level has been broken
1015 // and we need to avoid bin packing there.
1016 bool NestedBlockSpecialCase =
1017 (!Style.isCpp() && Current.is(tok::r_brace) && State.Stack.size() > 1 &&
1018 State.Stack[State.Stack.size() - 2].NestedBlockInlined) ||
1019 (Style.Language == FormatStyle::LK_ObjC && Current.is(tok::r_brace) &&
1020 State.Stack.size() > 1 && !Style.ObjCBreakBeforeNestedBlockParam);
1021 // Do not force parameter break for statements with requires expressions.
1022 NestedBlockSpecialCase =
1023 NestedBlockSpecialCase ||
1024 (Current.MatchingParen &&
1025 Current.MatchingParen->is(TT_RequiresExpressionLBrace));
1026 if (!NestedBlockSpecialCase)
1027 for (ParenState &PState : llvm::drop_end(State.Stack))
1028 PState.BreakBeforeParameter = true;
1030 if (PreviousNonComment &&
1031 !PreviousNonComment->isOneOf(tok::comma, tok::colon, tok::semi) &&
1032 ((PreviousNonComment->isNot(TT_TemplateCloser) &&
1033 !PreviousNonComment->ClosesRequiresClause) ||
1034 Current.NestingLevel != 0) &&
1035 !PreviousNonComment->isOneOf(
1036 TT_BinaryOperator, TT_FunctionAnnotationRParen, TT_JavaAnnotation,
1037 TT_LeadingJavaAnnotation) &&
1038 Current.isNot(TT_BinaryOperator) && !PreviousNonComment->opensScope()) {
1039 CurrentState.BreakBeforeParameter = true;
1042 // If we break after { or the [ of an array initializer, we should also break
1043 // before the corresponding } or ].
1044 if (PreviousNonComment &&
1045 (PreviousNonComment->isOneOf(tok::l_brace, TT_ArrayInitializerLSquare) ||
1046 opensProtoMessageField(*PreviousNonComment, Style))) {
1047 CurrentState.BreakBeforeClosingBrace = true;
1050 if (PreviousNonComment && PreviousNonComment->is(tok::l_paren)) {
1051 CurrentState.BreakBeforeClosingParen =
1052 Style.AlignAfterOpenBracket == FormatStyle::BAS_BlockIndent;
1055 if (CurrentState.AvoidBinPacking) {
1056 // If we are breaking after '(', '{', '<', or this is the break after a ':'
1057 // to start a member initializater list in a constructor, this should not
1058 // be considered bin packing unless the relevant AllowAll option is false or
1059 // this is a dict/object literal.
1060 bool PreviousIsBreakingCtorInitializerColon =
1061 PreviousNonComment && PreviousNonComment->is(TT_CtorInitializerColon) &&
1062 Style.BreakConstructorInitializers == FormatStyle::BCIS_AfterColon;
1063 bool AllowAllConstructorInitializersOnNextLine =
1064 Style.PackConstructorInitializers == FormatStyle::PCIS_NextLine ||
1065 Style.PackConstructorInitializers == FormatStyle::PCIS_NextLineOnly;
1066 if (!(Previous.isOneOf(tok::l_paren, tok::l_brace, TT_BinaryOperator) ||
1067 PreviousIsBreakingCtorInitializerColon) ||
1068 (!Style.AllowAllParametersOfDeclarationOnNextLine &&
1069 State.Line->MustBeDeclaration) ||
1070 (!Style.AllowAllArgumentsOnNextLine &&
1071 !State.Line->MustBeDeclaration) ||
1072 (!AllowAllConstructorInitializersOnNextLine &&
1073 PreviousIsBreakingCtorInitializerColon) ||
1074 Previous.is(TT_DictLiteral)) {
1075 CurrentState.BreakBeforeParameter = true;
1078 // If we are breaking after a ':' to start a member initializer list,
1079 // and we allow all arguments on the next line, we should not break
1080 // before the next parameter.
1081 if (PreviousIsBreakingCtorInitializerColon &&
1082 AllowAllConstructorInitializersOnNextLine) {
1083 CurrentState.BreakBeforeParameter = false;
1087 return Penalty;
1090 unsigned ContinuationIndenter::getNewLineColumn(const LineState &State) {
1091 if (!State.NextToken || !State.NextToken->Previous)
1092 return 0;
1094 FormatToken &Current = *State.NextToken;
1095 const auto &CurrentState = State.Stack.back();
1097 if (CurrentState.IsCSharpGenericTypeConstraint &&
1098 Current.isNot(TT_CSharpGenericTypeConstraint)) {
1099 return CurrentState.ColonPos + 2;
1102 const FormatToken &Previous = *Current.Previous;
1103 // If we are continuing an expression, we want to use the continuation indent.
1104 unsigned ContinuationIndent =
1105 std::max(CurrentState.LastSpace, CurrentState.Indent) +
1106 Style.ContinuationIndentWidth;
1107 const FormatToken *PreviousNonComment = Current.getPreviousNonComment();
1108 const FormatToken *NextNonComment = Previous.getNextNonComment();
1109 if (!NextNonComment)
1110 NextNonComment = &Current;
1112 // Java specific bits.
1113 if (Style.Language == FormatStyle::LK_Java &&
1114 Current.isOneOf(Keywords.kw_implements, Keywords.kw_extends)) {
1115 return std::max(CurrentState.LastSpace,
1116 CurrentState.Indent + Style.ContinuationIndentWidth);
1119 // After a goto label. Usually labels are on separate lines. However
1120 // for Verilog the labels may be only recognized by the annotator and
1121 // thus are on the same line as the current token.
1122 if ((Style.isVerilog() && Keywords.isVerilogEndOfLabel(Previous)) ||
1123 (Style.BreakBeforeBraces == FormatStyle::BS_Whitesmiths &&
1124 State.Line->First->is(tok::kw_enum))) {
1125 return (Style.IndentWidth * State.Line->First->IndentLevel) +
1126 Style.IndentWidth;
1129 if ((NextNonComment->is(tok::l_brace) && NextNonComment->is(BK_Block)) ||
1130 (Style.isVerilog() && Keywords.isVerilogBegin(*NextNonComment))) {
1131 if (Current.NestingLevel == 0 ||
1132 (Style.LambdaBodyIndentation == FormatStyle::LBI_OuterScope &&
1133 State.NextToken->is(TT_LambdaLBrace))) {
1134 return State.FirstIndent;
1136 return CurrentState.Indent;
1138 if ((Current.isOneOf(tok::r_brace, tok::r_square) ||
1139 (Current.is(tok::greater) &&
1140 (Style.Language == FormatStyle::LK_Proto ||
1141 Style.Language == FormatStyle::LK_TextProto))) &&
1142 State.Stack.size() > 1) {
1143 if (Current.closesBlockOrBlockTypeList(Style))
1144 return State.Stack[State.Stack.size() - 2].NestedBlockIndent;
1145 if (Current.MatchingParen && Current.MatchingParen->is(BK_BracedInit))
1146 return State.Stack[State.Stack.size() - 2].LastSpace;
1147 return State.FirstIndent;
1149 // Indent a closing parenthesis at the previous level if followed by a semi,
1150 // const, or opening brace. This allows indentations such as:
1151 // foo(
1152 // a,
1153 // );
1154 // int Foo::getter(
1155 // //
1156 // ) const {
1157 // return foo;
1158 // }
1159 // function foo(
1160 // a,
1161 // ) {
1162 // code(); //
1163 // }
1164 if (Current.is(tok::r_paren) && State.Stack.size() > 1 &&
1165 (!Current.Next ||
1166 Current.Next->isOneOf(tok::semi, tok::kw_const, tok::l_brace))) {
1167 return State.Stack[State.Stack.size() - 2].LastSpace;
1169 if (Style.AlignAfterOpenBracket == FormatStyle::BAS_BlockIndent &&
1170 Current.is(tok::r_paren) && State.Stack.size() > 1) {
1171 return State.Stack[State.Stack.size() - 2].LastSpace;
1173 if (NextNonComment->is(TT_TemplateString) && NextNonComment->closesScope())
1174 return State.Stack[State.Stack.size() - 2].LastSpace;
1175 if (Current.is(tok::identifier) && Current.Next &&
1176 (Current.Next->is(TT_DictLiteral) ||
1177 ((Style.Language == FormatStyle::LK_Proto ||
1178 Style.Language == FormatStyle::LK_TextProto) &&
1179 Current.Next->isOneOf(tok::less, tok::l_brace)))) {
1180 return CurrentState.Indent;
1182 if (NextNonComment->is(TT_ObjCStringLiteral) &&
1183 State.StartOfStringLiteral != 0) {
1184 return State.StartOfStringLiteral - 1;
1186 if (NextNonComment->isStringLiteral() && State.StartOfStringLiteral != 0)
1187 return State.StartOfStringLiteral;
1188 if (NextNonComment->is(tok::lessless) && CurrentState.FirstLessLess != 0)
1189 return CurrentState.FirstLessLess;
1190 if (NextNonComment->isMemberAccess()) {
1191 if (CurrentState.CallContinuation == 0)
1192 return ContinuationIndent;
1193 return CurrentState.CallContinuation;
1195 if (CurrentState.QuestionColumn != 0 &&
1196 ((NextNonComment->is(tok::colon) &&
1197 NextNonComment->is(TT_ConditionalExpr)) ||
1198 Previous.is(TT_ConditionalExpr))) {
1199 if (((NextNonComment->is(tok::colon) && NextNonComment->Next &&
1200 !NextNonComment->Next->FakeLParens.empty() &&
1201 NextNonComment->Next->FakeLParens.back() == prec::Conditional) ||
1202 (Previous.is(tok::colon) && !Current.FakeLParens.empty() &&
1203 Current.FakeLParens.back() == prec::Conditional)) &&
1204 !CurrentState.IsWrappedConditional) {
1205 // NOTE: we may tweak this slightly:
1206 // * not remove the 'lead' ContinuationIndentWidth
1207 // * always un-indent by the operator when
1208 // BreakBeforeTernaryOperators=true
1209 unsigned Indent = CurrentState.Indent;
1210 if (Style.AlignOperands != FormatStyle::OAS_DontAlign)
1211 Indent -= Style.ContinuationIndentWidth;
1212 if (Style.BreakBeforeTernaryOperators && CurrentState.UnindentOperator)
1213 Indent -= 2;
1214 return Indent;
1216 return CurrentState.QuestionColumn;
1218 if (Previous.is(tok::comma) && CurrentState.VariablePos != 0)
1219 return CurrentState.VariablePos;
1220 if (Current.is(TT_RequiresClause)) {
1221 if (Style.IndentRequiresClause)
1222 return CurrentState.Indent + Style.IndentWidth;
1223 switch (Style.RequiresClausePosition) {
1224 case FormatStyle::RCPS_OwnLine:
1225 case FormatStyle::RCPS_WithFollowing:
1226 return CurrentState.Indent;
1227 default:
1228 break;
1231 if (NextNonComment->isOneOf(TT_CtorInitializerColon, TT_InheritanceColon,
1232 TT_InheritanceComma)) {
1233 return State.FirstIndent + Style.ConstructorInitializerIndentWidth;
1235 if ((PreviousNonComment &&
1236 (PreviousNonComment->ClosesTemplateDeclaration ||
1237 PreviousNonComment->ClosesRequiresClause ||
1238 PreviousNonComment->isOneOf(
1239 TT_AttributeParen, TT_AttributeSquare, TT_FunctionAnnotationRParen,
1240 TT_JavaAnnotation, TT_LeadingJavaAnnotation))) ||
1241 (!Style.IndentWrappedFunctionNames &&
1242 NextNonComment->isOneOf(tok::kw_operator, TT_FunctionDeclarationName))) {
1243 return std::max(CurrentState.LastSpace, CurrentState.Indent);
1245 if (NextNonComment->is(TT_SelectorName)) {
1246 if (!CurrentState.ObjCSelectorNameFound) {
1247 unsigned MinIndent = CurrentState.Indent;
1248 if (shouldIndentWrappedSelectorName(Style, State.Line->Type)) {
1249 MinIndent = std::max(MinIndent,
1250 State.FirstIndent + Style.ContinuationIndentWidth);
1252 // If LongestObjCSelectorName is 0, we are indenting the first
1253 // part of an ObjC selector (or a selector component which is
1254 // not colon-aligned due to block formatting).
1256 // Otherwise, we are indenting a subsequent part of an ObjC
1257 // selector which should be colon-aligned to the longest
1258 // component of the ObjC selector.
1260 // In either case, we want to respect Style.IndentWrappedFunctionNames.
1261 return MinIndent +
1262 std::max(NextNonComment->LongestObjCSelectorName,
1263 NextNonComment->ColumnWidth) -
1264 NextNonComment->ColumnWidth;
1266 if (!CurrentState.AlignColons)
1267 return CurrentState.Indent;
1268 if (CurrentState.ColonPos > NextNonComment->ColumnWidth)
1269 return CurrentState.ColonPos - NextNonComment->ColumnWidth;
1270 return CurrentState.Indent;
1272 if (NextNonComment->is(tok::colon) && NextNonComment->is(TT_ObjCMethodExpr))
1273 return CurrentState.ColonPos;
1274 if (NextNonComment->is(TT_ArraySubscriptLSquare)) {
1275 if (CurrentState.StartOfArraySubscripts != 0) {
1276 return CurrentState.StartOfArraySubscripts;
1277 } else if (Style.isCSharp()) { // C# allows `["key"] = value` inside object
1278 // initializers.
1279 return CurrentState.Indent;
1281 return ContinuationIndent;
1284 // OpenMP clauses want to get additional indentation when they are pushed onto
1285 // the next line.
1286 if (State.Line->InPragmaDirective) {
1287 FormatToken *PragmaType = State.Line->First->Next->Next;
1288 if (PragmaType && PragmaType->TokenText.equals("omp"))
1289 return CurrentState.Indent + Style.ContinuationIndentWidth;
1292 // This ensure that we correctly format ObjC methods calls without inputs,
1293 // i.e. where the last element isn't selector like: [callee method];
1294 if (NextNonComment->is(tok::identifier) && NextNonComment->FakeRParens == 0 &&
1295 NextNonComment->Next && NextNonComment->Next->is(TT_ObjCMethodExpr)) {
1296 return CurrentState.Indent;
1299 if (NextNonComment->isOneOf(TT_StartOfName, TT_PointerOrReference) ||
1300 Previous.isOneOf(tok::coloncolon, tok::equal, TT_JsTypeColon)) {
1301 return ContinuationIndent;
1303 if (PreviousNonComment && PreviousNonComment->is(tok::colon) &&
1304 PreviousNonComment->isOneOf(TT_ObjCMethodExpr, TT_DictLiteral)) {
1305 return ContinuationIndent;
1307 if (NextNonComment->is(TT_CtorInitializerComma))
1308 return CurrentState.Indent;
1309 if (PreviousNonComment && PreviousNonComment->is(TT_CtorInitializerColon) &&
1310 Style.BreakConstructorInitializers == FormatStyle::BCIS_AfterColon) {
1311 return CurrentState.Indent;
1313 if (PreviousNonComment && PreviousNonComment->is(TT_InheritanceColon) &&
1314 Style.BreakInheritanceList == FormatStyle::BILS_AfterColon) {
1315 return CurrentState.Indent;
1317 if (Previous.is(tok::r_paren) && !Current.isBinaryOperator() &&
1318 !Current.isOneOf(tok::colon, tok::comment)) {
1319 return ContinuationIndent;
1321 if (Current.is(TT_ProtoExtensionLSquare))
1322 return CurrentState.Indent;
1323 if (Current.isBinaryOperator() && CurrentState.UnindentOperator) {
1324 return CurrentState.Indent - Current.Tok.getLength() -
1325 Current.SpacesRequiredBefore;
1327 if (Current.isOneOf(tok::comment, TT_BlockComment, TT_LineComment) &&
1328 NextNonComment->isBinaryOperator() && CurrentState.UnindentOperator) {
1329 return CurrentState.Indent - NextNonComment->Tok.getLength() -
1330 NextNonComment->SpacesRequiredBefore;
1332 if (CurrentState.Indent == State.FirstIndent && PreviousNonComment &&
1333 !PreviousNonComment->isOneOf(tok::r_brace, TT_CtorInitializerComma)) {
1334 // Ensure that we fall back to the continuation indent width instead of
1335 // just flushing continuations left.
1336 return CurrentState.Indent + Style.ContinuationIndentWidth;
1338 return CurrentState.Indent;
1341 static bool hasNestedBlockInlined(const FormatToken *Previous,
1342 const FormatToken &Current,
1343 const FormatStyle &Style) {
1344 if (Previous->isNot(tok::l_paren))
1345 return true;
1346 if (Previous->ParameterCount > 1)
1347 return true;
1349 // Also a nested block if contains a lambda inside function with 1 parameter.
1350 return Style.BraceWrapping.BeforeLambdaBody && Current.is(TT_LambdaLSquare);
1353 unsigned ContinuationIndenter::moveStateToNextToken(LineState &State,
1354 bool DryRun, bool Newline) {
1355 assert(State.Stack.size());
1356 const FormatToken &Current = *State.NextToken;
1357 auto &CurrentState = State.Stack.back();
1359 if (Current.is(TT_CSharpGenericTypeConstraint))
1360 CurrentState.IsCSharpGenericTypeConstraint = true;
1361 if (Current.isOneOf(tok::comma, TT_BinaryOperator))
1362 CurrentState.NoLineBreakInOperand = false;
1363 if (Current.isOneOf(TT_InheritanceColon, TT_CSharpGenericTypeConstraintColon))
1364 CurrentState.AvoidBinPacking = true;
1365 if (Current.is(tok::lessless) && Current.isNot(TT_OverloadedOperator)) {
1366 if (CurrentState.FirstLessLess == 0)
1367 CurrentState.FirstLessLess = State.Column;
1368 else
1369 CurrentState.LastOperatorWrapped = Newline;
1371 if (Current.is(TT_BinaryOperator) && Current.isNot(tok::lessless))
1372 CurrentState.LastOperatorWrapped = Newline;
1373 if (Current.is(TT_ConditionalExpr) && Current.Previous &&
1374 !Current.Previous->is(TT_ConditionalExpr)) {
1375 CurrentState.LastOperatorWrapped = Newline;
1377 if (Current.is(TT_ArraySubscriptLSquare) &&
1378 CurrentState.StartOfArraySubscripts == 0) {
1379 CurrentState.StartOfArraySubscripts = State.Column;
1382 auto IsWrappedConditional = [](const FormatToken &Tok) {
1383 if (!(Tok.is(TT_ConditionalExpr) && Tok.is(tok::question)))
1384 return false;
1385 if (Tok.MustBreakBefore)
1386 return true;
1388 const FormatToken *Next = Tok.getNextNonComment();
1389 return Next && Next->MustBreakBefore;
1391 if (IsWrappedConditional(Current))
1392 CurrentState.IsWrappedConditional = true;
1393 if (Style.BreakBeforeTernaryOperators && Current.is(tok::question))
1394 CurrentState.QuestionColumn = State.Column;
1395 if (!Style.BreakBeforeTernaryOperators && Current.isNot(tok::colon)) {
1396 const FormatToken *Previous = Current.Previous;
1397 while (Previous && Previous->isTrailingComment())
1398 Previous = Previous->Previous;
1399 if (Previous && Previous->is(tok::question))
1400 CurrentState.QuestionColumn = State.Column;
1402 if (!Current.opensScope() && !Current.closesScope() &&
1403 !Current.is(TT_PointerOrReference)) {
1404 State.LowestLevelOnLine =
1405 std::min(State.LowestLevelOnLine, Current.NestingLevel);
1407 if (Current.isMemberAccess())
1408 CurrentState.StartOfFunctionCall = !Current.NextOperator ? 0 : State.Column;
1409 if (Current.is(TT_SelectorName))
1410 CurrentState.ObjCSelectorNameFound = true;
1411 if (Current.is(TT_CtorInitializerColon) &&
1412 Style.BreakConstructorInitializers != FormatStyle::BCIS_AfterColon) {
1413 // Indent 2 from the column, so:
1414 // SomeClass::SomeClass()
1415 // : First(...), ...
1416 // Next(...)
1417 // ^ line up here.
1418 CurrentState.Indent = State.Column + (Style.BreakConstructorInitializers ==
1419 FormatStyle::BCIS_BeforeComma
1421 : 2);
1422 CurrentState.NestedBlockIndent = CurrentState.Indent;
1423 if (Style.PackConstructorInitializers > FormatStyle::PCIS_BinPack) {
1424 CurrentState.AvoidBinPacking = true;
1425 CurrentState.BreakBeforeParameter =
1426 Style.PackConstructorInitializers != FormatStyle::PCIS_NextLine &&
1427 Style.PackConstructorInitializers != FormatStyle::PCIS_NextLineOnly;
1428 } else {
1429 CurrentState.BreakBeforeParameter = false;
1432 if (Current.is(TT_CtorInitializerColon) &&
1433 Style.BreakConstructorInitializers == FormatStyle::BCIS_AfterColon) {
1434 CurrentState.Indent =
1435 State.FirstIndent + Style.ConstructorInitializerIndentWidth;
1436 CurrentState.NestedBlockIndent = CurrentState.Indent;
1437 if (Style.PackConstructorInitializers > FormatStyle::PCIS_BinPack)
1438 CurrentState.AvoidBinPacking = true;
1440 if (Current.is(TT_InheritanceColon)) {
1441 CurrentState.Indent =
1442 State.FirstIndent + Style.ConstructorInitializerIndentWidth;
1444 if (Current.isOneOf(TT_BinaryOperator, TT_ConditionalExpr) && Newline)
1445 CurrentState.NestedBlockIndent = State.Column + Current.ColumnWidth + 1;
1446 if (Current.isOneOf(TT_LambdaLSquare, TT_LambdaArrow))
1447 CurrentState.LastSpace = State.Column;
1448 if (Current.is(TT_RequiresExpression) &&
1449 Style.RequiresExpressionIndentation == FormatStyle::REI_Keyword) {
1450 CurrentState.NestedBlockIndent = State.Column;
1453 // Insert scopes created by fake parenthesis.
1454 const FormatToken *Previous = Current.getPreviousNonComment();
1456 // Add special behavior to support a format commonly used for JavaScript
1457 // closures:
1458 // SomeFunction(function() {
1459 // foo();
1460 // bar();
1461 // }, a, b, c);
1462 if (Current.isNot(tok::comment) && !Current.ClosesRequiresClause &&
1463 Previous && Previous->isOneOf(tok::l_brace, TT_ArrayInitializerLSquare) &&
1464 !Previous->is(TT_DictLiteral) && State.Stack.size() > 1 &&
1465 !CurrentState.HasMultipleNestedBlocks) {
1466 if (State.Stack[State.Stack.size() - 2].NestedBlockInlined && Newline)
1467 for (ParenState &PState : llvm::drop_end(State.Stack))
1468 PState.NoLineBreak = true;
1469 State.Stack[State.Stack.size() - 2].NestedBlockInlined = false;
1471 if (Previous && (Previous->isOneOf(TT_BinaryOperator, TT_ConditionalExpr) ||
1472 (Previous->isOneOf(tok::l_paren, tok::comma, tok::colon) &&
1473 !Previous->isOneOf(TT_DictLiteral, TT_ObjCMethodExpr)))) {
1474 CurrentState.NestedBlockInlined =
1475 !Newline && hasNestedBlockInlined(Previous, Current, Style);
1478 moveStatePastFakeLParens(State, Newline);
1479 moveStatePastScopeCloser(State);
1480 // Do not use CurrentState here, since the two functions before may change the
1481 // Stack.
1482 bool AllowBreak = !State.Stack.back().NoLineBreak &&
1483 !State.Stack.back().NoLineBreakInOperand;
1484 moveStatePastScopeOpener(State, Newline);
1485 moveStatePastFakeRParens(State);
1487 if (Current.is(TT_ObjCStringLiteral) && State.StartOfStringLiteral == 0)
1488 State.StartOfStringLiteral = State.Column + 1;
1489 if (Current.is(TT_CSharpStringLiteral) && State.StartOfStringLiteral == 0) {
1490 State.StartOfStringLiteral = State.Column + 1;
1491 } else if (Current.isStringLiteral() && State.StartOfStringLiteral == 0) {
1492 State.StartOfStringLiteral = State.Column;
1493 } else if (!Current.isOneOf(tok::comment, tok::identifier, tok::hash) &&
1494 !Current.isStringLiteral()) {
1495 State.StartOfStringLiteral = 0;
1498 State.Column += Current.ColumnWidth;
1499 State.NextToken = State.NextToken->Next;
1501 unsigned Penalty =
1502 handleEndOfLine(Current, State, DryRun, AllowBreak, Newline);
1504 if (Current.Role)
1505 Current.Role->formatFromToken(State, this, DryRun);
1506 // If the previous has a special role, let it consume tokens as appropriate.
1507 // It is necessary to start at the previous token for the only implemented
1508 // role (comma separated list). That way, the decision whether or not to break
1509 // after the "{" is already done and both options are tried and evaluated.
1510 // FIXME: This is ugly, find a better way.
1511 if (Previous && Previous->Role)
1512 Penalty += Previous->Role->formatAfterToken(State, this, DryRun);
1514 return Penalty;
1517 void ContinuationIndenter::moveStatePastFakeLParens(LineState &State,
1518 bool Newline) {
1519 const FormatToken &Current = *State.NextToken;
1520 if (Current.FakeLParens.empty())
1521 return;
1523 const FormatToken *Previous = Current.getPreviousNonComment();
1525 // Don't add extra indentation for the first fake parenthesis after
1526 // 'return', assignments, opening <({[, or requires clauses. The indentation
1527 // for these cases is special cased.
1528 bool SkipFirstExtraIndent =
1529 Previous &&
1530 (Previous->opensScope() ||
1531 Previous->isOneOf(tok::semi, tok::kw_return, TT_RequiresClause) ||
1532 (Previous->getPrecedence() == prec::Assignment &&
1533 Style.AlignOperands != FormatStyle::OAS_DontAlign) ||
1534 Previous->is(TT_ObjCMethodExpr));
1535 for (const auto &PrecedenceLevel : llvm::reverse(Current.FakeLParens)) {
1536 const auto &CurrentState = State.Stack.back();
1537 ParenState NewParenState = CurrentState;
1538 NewParenState.Tok = nullptr;
1539 NewParenState.ContainsLineBreak = false;
1540 NewParenState.LastOperatorWrapped = true;
1541 NewParenState.IsChainedConditional = false;
1542 NewParenState.IsWrappedConditional = false;
1543 NewParenState.UnindentOperator = false;
1544 NewParenState.NoLineBreak =
1545 NewParenState.NoLineBreak || CurrentState.NoLineBreakInOperand;
1547 // Don't propagate AvoidBinPacking into subexpressions of arg/param lists.
1548 if (PrecedenceLevel > prec::Comma)
1549 NewParenState.AvoidBinPacking = false;
1551 // Indent from 'LastSpace' unless these are fake parentheses encapsulating
1552 // a builder type call after 'return' or, if the alignment after opening
1553 // brackets is disabled.
1554 if (!Current.isTrailingComment() &&
1555 (Style.AlignOperands != FormatStyle::OAS_DontAlign ||
1556 PrecedenceLevel < prec::Assignment) &&
1557 (!Previous || Previous->isNot(tok::kw_return) ||
1558 (Style.Language != FormatStyle::LK_Java && PrecedenceLevel > 0)) &&
1559 (Style.AlignAfterOpenBracket != FormatStyle::BAS_DontAlign ||
1560 PrecedenceLevel != prec::Comma || Current.NestingLevel == 0)) {
1561 NewParenState.Indent = std::max(
1562 std::max(State.Column, NewParenState.Indent), CurrentState.LastSpace);
1565 // Special case for generic selection expressions, its comma-separated
1566 // expressions are not aligned to the opening paren like regular calls, but
1567 // rather continuation-indented relative to the _Generic keyword.
1568 if (Previous && Previous->endsSequence(tok::l_paren, tok::kw__Generic))
1569 NewParenState.Indent = CurrentState.LastSpace;
1571 if (Previous &&
1572 (Previous->getPrecedence() == prec::Assignment ||
1573 Previous->isOneOf(tok::kw_return, TT_RequiresClause) ||
1574 (PrecedenceLevel == prec::Conditional && Previous->is(tok::question) &&
1575 Previous->is(TT_ConditionalExpr))) &&
1576 !Newline) {
1577 // If BreakBeforeBinaryOperators is set, un-indent a bit to account for
1578 // the operator and keep the operands aligned.
1579 if (Style.AlignOperands == FormatStyle::OAS_AlignAfterOperator)
1580 NewParenState.UnindentOperator = true;
1581 // Mark indentation as alignment if the expression is aligned.
1582 if (Style.AlignOperands != FormatStyle::OAS_DontAlign)
1583 NewParenState.IsAligned = true;
1586 // Do not indent relative to the fake parentheses inserted for "." or "->".
1587 // This is a special case to make the following to statements consistent:
1588 // OuterFunction(InnerFunctionCall( // break
1589 // ParameterToInnerFunction));
1590 // OuterFunction(SomeObject.InnerFunctionCall( // break
1591 // ParameterToInnerFunction));
1592 if (PrecedenceLevel > prec::Unknown)
1593 NewParenState.LastSpace = std::max(NewParenState.LastSpace, State.Column);
1594 if (PrecedenceLevel != prec::Conditional && !Current.is(TT_UnaryOperator) &&
1595 Style.AlignAfterOpenBracket != FormatStyle::BAS_DontAlign) {
1596 NewParenState.StartOfFunctionCall = State.Column;
1599 // Indent conditional expressions, unless they are chained "else-if"
1600 // conditionals. Never indent expression where the 'operator' is ',', ';' or
1601 // an assignment (i.e. *I <= prec::Assignment) as those have different
1602 // indentation rules. Indent other expression, unless the indentation needs
1603 // to be skipped.
1604 if (PrecedenceLevel == prec::Conditional && Previous &&
1605 Previous->is(tok::colon) && Previous->is(TT_ConditionalExpr) &&
1606 &PrecedenceLevel == &Current.FakeLParens.back() &&
1607 !CurrentState.IsWrappedConditional) {
1608 NewParenState.IsChainedConditional = true;
1609 NewParenState.UnindentOperator = State.Stack.back().UnindentOperator;
1610 } else if (PrecedenceLevel == prec::Conditional ||
1611 (!SkipFirstExtraIndent && PrecedenceLevel > prec::Assignment &&
1612 !Current.isTrailingComment())) {
1613 NewParenState.Indent += Style.ContinuationIndentWidth;
1615 if ((Previous && !Previous->opensScope()) || PrecedenceLevel != prec::Comma)
1616 NewParenState.BreakBeforeParameter = false;
1617 State.Stack.push_back(NewParenState);
1618 SkipFirstExtraIndent = false;
1622 void ContinuationIndenter::moveStatePastFakeRParens(LineState &State) {
1623 for (unsigned i = 0, e = State.NextToken->FakeRParens; i != e; ++i) {
1624 unsigned VariablePos = State.Stack.back().VariablePos;
1625 if (State.Stack.size() == 1) {
1626 // Do not pop the last element.
1627 break;
1629 State.Stack.pop_back();
1630 State.Stack.back().VariablePos = VariablePos;
1633 if (State.NextToken->ClosesRequiresClause && Style.IndentRequiresClause) {
1634 // Remove the indentation of the requires clauses (which is not in Indent,
1635 // but in LastSpace).
1636 State.Stack.back().LastSpace -= Style.IndentWidth;
1640 void ContinuationIndenter::moveStatePastScopeOpener(LineState &State,
1641 bool Newline) {
1642 const FormatToken &Current = *State.NextToken;
1643 if (!Current.opensScope())
1644 return;
1646 const auto &CurrentState = State.Stack.back();
1648 // Don't allow '<' or '(' in C# generic type constraints to start new scopes.
1649 if (Current.isOneOf(tok::less, tok::l_paren) &&
1650 CurrentState.IsCSharpGenericTypeConstraint) {
1651 return;
1654 if (Current.MatchingParen && Current.is(BK_Block)) {
1655 moveStateToNewBlock(State);
1656 return;
1659 unsigned NewIndent;
1660 unsigned LastSpace = CurrentState.LastSpace;
1661 bool AvoidBinPacking;
1662 bool BreakBeforeParameter = false;
1663 unsigned NestedBlockIndent = std::max(CurrentState.StartOfFunctionCall,
1664 CurrentState.NestedBlockIndent);
1665 if (Current.isOneOf(tok::l_brace, TT_ArrayInitializerLSquare) ||
1666 opensProtoMessageField(Current, Style)) {
1667 if (Current.opensBlockOrBlockTypeList(Style)) {
1668 NewIndent = Style.IndentWidth +
1669 std::min(State.Column, CurrentState.NestedBlockIndent);
1670 } else if (Current.is(tok::l_brace)) {
1671 NewIndent =
1672 CurrentState.LastSpace + Style.BracedInitializerIndentWidth.value_or(
1673 Style.ContinuationIndentWidth);
1674 } else {
1675 NewIndent = CurrentState.LastSpace + Style.ContinuationIndentWidth;
1677 const FormatToken *NextNonComment = Current.getNextNonComment();
1678 bool EndsInComma = Current.MatchingParen &&
1679 Current.MatchingParen->Previous &&
1680 Current.MatchingParen->Previous->is(tok::comma);
1681 AvoidBinPacking = EndsInComma || Current.is(TT_DictLiteral) ||
1682 Style.Language == FormatStyle::LK_Proto ||
1683 Style.Language == FormatStyle::LK_TextProto ||
1684 !Style.BinPackArguments ||
1685 (NextNonComment && NextNonComment->isOneOf(
1686 TT_DesignatedInitializerPeriod,
1687 TT_DesignatedInitializerLSquare));
1688 BreakBeforeParameter = EndsInComma;
1689 if (Current.ParameterCount > 1)
1690 NestedBlockIndent = std::max(NestedBlockIndent, State.Column + 1);
1691 } else {
1692 NewIndent =
1693 Style.ContinuationIndentWidth +
1694 std::max(CurrentState.LastSpace, CurrentState.StartOfFunctionCall);
1696 // Ensure that different different brackets force relative alignment, e.g.:
1697 // void SomeFunction(vector< // break
1698 // int> v);
1699 // FIXME: We likely want to do this for more combinations of brackets.
1700 if (Current.is(tok::less) && Current.ParentBracket == tok::l_paren) {
1701 NewIndent = std::max(NewIndent, CurrentState.Indent);
1702 LastSpace = std::max(LastSpace, CurrentState.Indent);
1705 bool EndsInComma =
1706 Current.MatchingParen &&
1707 Current.MatchingParen->getPreviousNonComment() &&
1708 Current.MatchingParen->getPreviousNonComment()->is(tok::comma);
1710 // If ObjCBinPackProtocolList is unspecified, fall back to BinPackParameters
1711 // for backwards compatibility.
1712 bool ObjCBinPackProtocolList =
1713 (Style.ObjCBinPackProtocolList == FormatStyle::BPS_Auto &&
1714 Style.BinPackParameters) ||
1715 Style.ObjCBinPackProtocolList == FormatStyle::BPS_Always;
1717 bool BinPackDeclaration =
1718 (State.Line->Type != LT_ObjCDecl && Style.BinPackParameters) ||
1719 (State.Line->Type == LT_ObjCDecl && ObjCBinPackProtocolList);
1721 bool GenericSelection =
1722 Current.getPreviousNonComment() &&
1723 Current.getPreviousNonComment()->is(tok::kw__Generic);
1725 AvoidBinPacking =
1726 (CurrentState.IsCSharpGenericTypeConstraint) || GenericSelection ||
1727 (Style.isJavaScript() && EndsInComma) ||
1728 (State.Line->MustBeDeclaration && !BinPackDeclaration) ||
1729 (!State.Line->MustBeDeclaration && !Style.BinPackArguments) ||
1730 (Style.ExperimentalAutoDetectBinPacking &&
1731 (Current.is(PPK_OnePerLine) ||
1732 (!BinPackInconclusiveFunctions && Current.is(PPK_Inconclusive))));
1734 if (Current.is(TT_ObjCMethodExpr) && Current.MatchingParen &&
1735 Style.ObjCBreakBeforeNestedBlockParam) {
1736 if (Style.ColumnLimit) {
1737 // If this '[' opens an ObjC call, determine whether all parameters fit
1738 // into one line and put one per line if they don't.
1739 if (getLengthToMatchingParen(Current, State.Stack) + State.Column >
1740 getColumnLimit(State)) {
1741 BreakBeforeParameter = true;
1743 } else {
1744 // For ColumnLimit = 0, we have to figure out whether there is or has to
1745 // be a line break within this call.
1746 for (const FormatToken *Tok = &Current;
1747 Tok && Tok != Current.MatchingParen; Tok = Tok->Next) {
1748 if (Tok->MustBreakBefore ||
1749 (Tok->CanBreakBefore && Tok->NewlinesBefore > 0)) {
1750 BreakBeforeParameter = true;
1751 break;
1757 if (Style.isJavaScript() && EndsInComma)
1758 BreakBeforeParameter = true;
1760 // Generally inherit NoLineBreak from the current scope to nested scope.
1761 // However, don't do this for non-empty nested blocks, dict literals and
1762 // array literals as these follow different indentation rules.
1763 bool NoLineBreak =
1764 Current.Children.empty() &&
1765 !Current.isOneOf(TT_DictLiteral, TT_ArrayInitializerLSquare) &&
1766 (CurrentState.NoLineBreak || CurrentState.NoLineBreakInOperand ||
1767 (Current.is(TT_TemplateOpener) &&
1768 CurrentState.ContainsUnwrappedBuilder));
1769 State.Stack.push_back(
1770 ParenState(&Current, NewIndent, LastSpace, AvoidBinPacking, NoLineBreak));
1771 auto &NewState = State.Stack.back();
1772 NewState.NestedBlockIndent = NestedBlockIndent;
1773 NewState.BreakBeforeParameter = BreakBeforeParameter;
1774 NewState.HasMultipleNestedBlocks = (Current.BlockParameterCount > 1);
1776 if (Style.BraceWrapping.BeforeLambdaBody && Current.Next &&
1777 Current.is(tok::l_paren)) {
1778 // Search for any parameter that is a lambda.
1779 FormatToken const *next = Current.Next;
1780 while (next) {
1781 if (next->is(TT_LambdaLSquare)) {
1782 NewState.HasMultipleNestedBlocks = true;
1783 break;
1785 next = next->Next;
1789 NewState.IsInsideObjCArrayLiteral = Current.is(TT_ArrayInitializerLSquare) &&
1790 Current.Previous &&
1791 Current.Previous->is(tok::at);
1794 void ContinuationIndenter::moveStatePastScopeCloser(LineState &State) {
1795 const FormatToken &Current = *State.NextToken;
1796 if (!Current.closesScope())
1797 return;
1799 // If we encounter a closing ), ], } or >, we can remove a level from our
1800 // stacks.
1801 if (State.Stack.size() > 1 &&
1802 (Current.isOneOf(tok::r_paren, tok::r_square, TT_TemplateString) ||
1803 (Current.is(tok::r_brace) && State.NextToken != State.Line->First) ||
1804 State.NextToken->is(TT_TemplateCloser) ||
1805 (Current.is(tok::greater) && Current.is(TT_DictLiteral)))) {
1806 State.Stack.pop_back();
1809 auto &CurrentState = State.Stack.back();
1811 // Reevaluate whether ObjC message arguments fit into one line.
1812 // If a receiver spans multiple lines, e.g.:
1813 // [[object block:^{
1814 // return 42;
1815 // }] a:42 b:42];
1816 // BreakBeforeParameter is calculated based on an incorrect assumption
1817 // (it is checked whether the whole expression fits into one line without
1818 // considering a line break inside a message receiver).
1819 // We check whether arguments fit after receiver scope closer (into the same
1820 // line).
1821 if (CurrentState.BreakBeforeParameter && Current.MatchingParen &&
1822 Current.MatchingParen->Previous) {
1823 const FormatToken &CurrentScopeOpener = *Current.MatchingParen->Previous;
1824 if (CurrentScopeOpener.is(TT_ObjCMethodExpr) &&
1825 CurrentScopeOpener.MatchingParen) {
1826 int NecessarySpaceInLine =
1827 getLengthToMatchingParen(CurrentScopeOpener, State.Stack) +
1828 CurrentScopeOpener.TotalLength - Current.TotalLength - 1;
1829 if (State.Column + Current.ColumnWidth + NecessarySpaceInLine <=
1830 Style.ColumnLimit) {
1831 CurrentState.BreakBeforeParameter = false;
1836 if (Current.is(tok::r_square)) {
1837 // If this ends the array subscript expr, reset the corresponding value.
1838 const FormatToken *NextNonComment = Current.getNextNonComment();
1839 if (NextNonComment && NextNonComment->isNot(tok::l_square))
1840 CurrentState.StartOfArraySubscripts = 0;
1844 void ContinuationIndenter::moveStateToNewBlock(LineState &State) {
1845 if (Style.LambdaBodyIndentation == FormatStyle::LBI_OuterScope &&
1846 State.NextToken->is(TT_LambdaLBrace)) {
1847 State.Stack.back().NestedBlockIndent = State.FirstIndent;
1849 unsigned NestedBlockIndent = State.Stack.back().NestedBlockIndent;
1850 // ObjC block sometimes follow special indentation rules.
1851 unsigned NewIndent =
1852 NestedBlockIndent + (State.NextToken->is(TT_ObjCBlockLBrace)
1853 ? Style.ObjCBlockIndentWidth
1854 : Style.IndentWidth);
1855 State.Stack.push_back(ParenState(State.NextToken, NewIndent,
1856 State.Stack.back().LastSpace,
1857 /*AvoidBinPacking=*/true,
1858 /*NoLineBreak=*/false));
1859 State.Stack.back().NestedBlockIndent = NestedBlockIndent;
1860 State.Stack.back().BreakBeforeParameter = true;
1863 static unsigned getLastLineEndColumn(StringRef Text, unsigned StartColumn,
1864 unsigned TabWidth,
1865 encoding::Encoding Encoding) {
1866 size_t LastNewlinePos = Text.find_last_of("\n");
1867 if (LastNewlinePos == StringRef::npos) {
1868 return StartColumn +
1869 encoding::columnWidthWithTabs(Text, StartColumn, TabWidth, Encoding);
1870 } else {
1871 return encoding::columnWidthWithTabs(Text.substr(LastNewlinePos),
1872 /*StartColumn=*/0, TabWidth, Encoding);
1876 unsigned ContinuationIndenter::reformatRawStringLiteral(
1877 const FormatToken &Current, LineState &State,
1878 const FormatStyle &RawStringStyle, bool DryRun, bool Newline) {
1879 unsigned StartColumn = State.Column - Current.ColumnWidth;
1880 StringRef OldDelimiter = *getRawStringDelimiter(Current.TokenText);
1881 StringRef NewDelimiter =
1882 getCanonicalRawStringDelimiter(Style, RawStringStyle.Language);
1883 if (NewDelimiter.empty())
1884 NewDelimiter = OldDelimiter;
1885 // The text of a raw string is between the leading 'R"delimiter(' and the
1886 // trailing 'delimiter)"'.
1887 unsigned OldPrefixSize = 3 + OldDelimiter.size();
1888 unsigned OldSuffixSize = 2 + OldDelimiter.size();
1889 // We create a virtual text environment which expects a null-terminated
1890 // string, so we cannot use StringRef.
1891 std::string RawText = std::string(
1892 Current.TokenText.substr(OldPrefixSize).drop_back(OldSuffixSize));
1893 if (NewDelimiter != OldDelimiter) {
1894 // Don't update to the canonical delimiter 'deli' if ')deli"' occurs in the
1895 // raw string.
1896 std::string CanonicalDelimiterSuffix = (")" + NewDelimiter + "\"").str();
1897 if (StringRef(RawText).contains(CanonicalDelimiterSuffix))
1898 NewDelimiter = OldDelimiter;
1901 unsigned NewPrefixSize = 3 + NewDelimiter.size();
1902 unsigned NewSuffixSize = 2 + NewDelimiter.size();
1904 // The first start column is the column the raw text starts after formatting.
1905 unsigned FirstStartColumn = StartColumn + NewPrefixSize;
1907 // The next start column is the intended indentation a line break inside
1908 // the raw string at level 0. It is determined by the following rules:
1909 // - if the content starts on newline, it is one level more than the current
1910 // indent, and
1911 // - if the content does not start on a newline, it is the first start
1912 // column.
1913 // These rules have the advantage that the formatted content both does not
1914 // violate the rectangle rule and visually flows within the surrounding
1915 // source.
1916 bool ContentStartsOnNewline = Current.TokenText[OldPrefixSize] == '\n';
1917 // If this token is the last parameter (checked by looking if it's followed by
1918 // `)` and is not on a newline, the base the indent off the line's nested
1919 // block indent. Otherwise, base the indent off the arguments indent, so we
1920 // can achieve:
1922 // fffffffffff(1, 2, 3, R"pb(
1923 // key1: 1 #
1924 // key2: 2)pb");
1926 // fffffffffff(1, 2, 3,
1927 // R"pb(
1928 // key1: 1 #
1929 // key2: 2
1930 // )pb");
1932 // fffffffffff(1, 2, 3,
1933 // R"pb(
1934 // key1: 1 #
1935 // key2: 2
1936 // )pb",
1937 // 5);
1938 unsigned CurrentIndent =
1939 (!Newline && Current.Next && Current.Next->is(tok::r_paren))
1940 ? State.Stack.back().NestedBlockIndent
1941 : State.Stack.back().Indent;
1942 unsigned NextStartColumn = ContentStartsOnNewline
1943 ? CurrentIndent + Style.IndentWidth
1944 : FirstStartColumn;
1946 // The last start column is the column the raw string suffix starts if it is
1947 // put on a newline.
1948 // The last start column is the intended indentation of the raw string postfix
1949 // if it is put on a newline. It is determined by the following rules:
1950 // - if the raw string prefix starts on a newline, it is the column where
1951 // that raw string prefix starts, and
1952 // - if the raw string prefix does not start on a newline, it is the current
1953 // indent.
1954 unsigned LastStartColumn =
1955 Current.NewlinesBefore ? FirstStartColumn - NewPrefixSize : CurrentIndent;
1957 std::pair<tooling::Replacements, unsigned> Fixes = internal::reformat(
1958 RawStringStyle, RawText, {tooling::Range(0, RawText.size())},
1959 FirstStartColumn, NextStartColumn, LastStartColumn, "<stdin>",
1960 /*Status=*/nullptr);
1962 auto NewCode = applyAllReplacements(RawText, Fixes.first);
1963 tooling::Replacements NoFixes;
1964 if (!NewCode)
1965 return addMultilineToken(Current, State);
1966 if (!DryRun) {
1967 if (NewDelimiter != OldDelimiter) {
1968 // In 'R"delimiter(...', the delimiter starts 2 characters after the start
1969 // of the token.
1970 SourceLocation PrefixDelimiterStart =
1971 Current.Tok.getLocation().getLocWithOffset(2);
1972 auto PrefixErr = Whitespaces.addReplacement(tooling::Replacement(
1973 SourceMgr, PrefixDelimiterStart, OldDelimiter.size(), NewDelimiter));
1974 if (PrefixErr) {
1975 llvm::errs()
1976 << "Failed to update the prefix delimiter of a raw string: "
1977 << llvm::toString(std::move(PrefixErr)) << "\n";
1979 // In 'R"delimiter(...)delimiter"', the suffix delimiter starts at
1980 // position length - 1 - |delimiter|.
1981 SourceLocation SuffixDelimiterStart =
1982 Current.Tok.getLocation().getLocWithOffset(Current.TokenText.size() -
1983 1 - OldDelimiter.size());
1984 auto SuffixErr = Whitespaces.addReplacement(tooling::Replacement(
1985 SourceMgr, SuffixDelimiterStart, OldDelimiter.size(), NewDelimiter));
1986 if (SuffixErr) {
1987 llvm::errs()
1988 << "Failed to update the suffix delimiter of a raw string: "
1989 << llvm::toString(std::move(SuffixErr)) << "\n";
1992 SourceLocation OriginLoc =
1993 Current.Tok.getLocation().getLocWithOffset(OldPrefixSize);
1994 for (const tooling::Replacement &Fix : Fixes.first) {
1995 auto Err = Whitespaces.addReplacement(tooling::Replacement(
1996 SourceMgr, OriginLoc.getLocWithOffset(Fix.getOffset()),
1997 Fix.getLength(), Fix.getReplacementText()));
1998 if (Err) {
1999 llvm::errs() << "Failed to reformat raw string: "
2000 << llvm::toString(std::move(Err)) << "\n";
2004 unsigned RawLastLineEndColumn = getLastLineEndColumn(
2005 *NewCode, FirstStartColumn, Style.TabWidth, Encoding);
2006 State.Column = RawLastLineEndColumn + NewSuffixSize;
2007 // Since we're updating the column to after the raw string literal here, we
2008 // have to manually add the penalty for the prefix R"delim( over the column
2009 // limit.
2010 unsigned PrefixExcessCharacters =
2011 StartColumn + NewPrefixSize > Style.ColumnLimit
2012 ? StartColumn + NewPrefixSize - Style.ColumnLimit
2013 : 0;
2014 bool IsMultiline =
2015 ContentStartsOnNewline || (NewCode->find('\n') != std::string::npos);
2016 if (IsMultiline) {
2017 // Break before further function parameters on all levels.
2018 for (ParenState &Paren : State.Stack)
2019 Paren.BreakBeforeParameter = true;
2021 return Fixes.second + PrefixExcessCharacters * Style.PenaltyExcessCharacter;
2024 unsigned ContinuationIndenter::addMultilineToken(const FormatToken &Current,
2025 LineState &State) {
2026 // Break before further function parameters on all levels.
2027 for (ParenState &Paren : State.Stack)
2028 Paren.BreakBeforeParameter = true;
2030 unsigned ColumnsUsed = State.Column;
2031 // We can only affect layout of the first and the last line, so the penalty
2032 // for all other lines is constant, and we ignore it.
2033 State.Column = Current.LastLineColumnWidth;
2035 if (ColumnsUsed > getColumnLimit(State))
2036 return Style.PenaltyExcessCharacter * (ColumnsUsed - getColumnLimit(State));
2037 return 0;
2040 unsigned ContinuationIndenter::handleEndOfLine(const FormatToken &Current,
2041 LineState &State, bool DryRun,
2042 bool AllowBreak, bool Newline) {
2043 unsigned Penalty = 0;
2044 // Compute the raw string style to use in case this is a raw string literal
2045 // that can be reformatted.
2046 auto RawStringStyle = getRawStringStyle(Current, State);
2047 if (RawStringStyle && !Current.Finalized) {
2048 Penalty = reformatRawStringLiteral(Current, State, *RawStringStyle, DryRun,
2049 Newline);
2050 } else if (Current.IsMultiline && Current.isNot(TT_BlockComment)) {
2051 // Don't break multi-line tokens other than block comments and raw string
2052 // literals. Instead, just update the state.
2053 Penalty = addMultilineToken(Current, State);
2054 } else if (State.Line->Type != LT_ImportStatement) {
2055 // We generally don't break import statements.
2056 LineState OriginalState = State;
2058 // Whether we force the reflowing algorithm to stay strictly within the
2059 // column limit.
2060 bool Strict = false;
2061 // Whether the first non-strict attempt at reflowing did intentionally
2062 // exceed the column limit.
2063 bool Exceeded = false;
2064 std::tie(Penalty, Exceeded) = breakProtrudingToken(
2065 Current, State, AllowBreak, /*DryRun=*/true, Strict);
2066 if (Exceeded) {
2067 // If non-strict reflowing exceeds the column limit, try whether strict
2068 // reflowing leads to an overall lower penalty.
2069 LineState StrictState = OriginalState;
2070 unsigned StrictPenalty =
2071 breakProtrudingToken(Current, StrictState, AllowBreak,
2072 /*DryRun=*/true, /*Strict=*/true)
2073 .first;
2074 Strict = StrictPenalty <= Penalty;
2075 if (Strict) {
2076 Penalty = StrictPenalty;
2077 State = StrictState;
2080 if (!DryRun) {
2081 // If we're not in dry-run mode, apply the changes with the decision on
2082 // strictness made above.
2083 breakProtrudingToken(Current, OriginalState, AllowBreak, /*DryRun=*/false,
2084 Strict);
2087 if (State.Column > getColumnLimit(State)) {
2088 unsigned ExcessCharacters = State.Column - getColumnLimit(State);
2089 Penalty += Style.PenaltyExcessCharacter * ExcessCharacters;
2091 return Penalty;
2094 // Returns the enclosing function name of a token, or the empty string if not
2095 // found.
2096 static StringRef getEnclosingFunctionName(const FormatToken &Current) {
2097 // Look for: 'function(' or 'function<templates>(' before Current.
2098 auto Tok = Current.getPreviousNonComment();
2099 if (!Tok || !Tok->is(tok::l_paren))
2100 return "";
2101 Tok = Tok->getPreviousNonComment();
2102 if (!Tok)
2103 return "";
2104 if (Tok->is(TT_TemplateCloser)) {
2105 Tok = Tok->MatchingParen;
2106 if (Tok)
2107 Tok = Tok->getPreviousNonComment();
2109 if (!Tok || !Tok->is(tok::identifier))
2110 return "";
2111 return Tok->TokenText;
2114 std::optional<FormatStyle>
2115 ContinuationIndenter::getRawStringStyle(const FormatToken &Current,
2116 const LineState &State) {
2117 if (!Current.isStringLiteral())
2118 return std::nullopt;
2119 auto Delimiter = getRawStringDelimiter(Current.TokenText);
2120 if (!Delimiter)
2121 return std::nullopt;
2122 auto RawStringStyle = RawStringFormats.getDelimiterStyle(*Delimiter);
2123 if (!RawStringStyle && Delimiter->empty()) {
2124 RawStringStyle = RawStringFormats.getEnclosingFunctionStyle(
2125 getEnclosingFunctionName(Current));
2127 if (!RawStringStyle)
2128 return std::nullopt;
2129 RawStringStyle->ColumnLimit = getColumnLimit(State);
2130 return RawStringStyle;
2133 std::unique_ptr<BreakableToken>
2134 ContinuationIndenter::createBreakableToken(const FormatToken &Current,
2135 LineState &State, bool AllowBreak) {
2136 unsigned StartColumn = State.Column - Current.ColumnWidth;
2137 if (Current.isStringLiteral()) {
2138 // FIXME: String literal breaking is currently disabled for C#, Java, Json
2139 // and JavaScript, as it requires strings to be merged using "+" which we
2140 // don't support.
2141 if (Style.Language == FormatStyle::LK_Java || Style.isJavaScript() ||
2142 Style.isCSharp() || Style.isJson() || !Style.BreakStringLiterals ||
2143 !AllowBreak) {
2144 return nullptr;
2147 // Don't break string literals inside preprocessor directives (except for
2148 // #define directives, as their contents are stored in separate lines and
2149 // are not affected by this check).
2150 // This way we avoid breaking code with line directives and unknown
2151 // preprocessor directives that contain long string literals.
2152 if (State.Line->Type == LT_PreprocessorDirective)
2153 return nullptr;
2154 // Exempts unterminated string literals from line breaking. The user will
2155 // likely want to terminate the string before any line breaking is done.
2156 if (Current.IsUnterminatedLiteral)
2157 return nullptr;
2158 // Don't break string literals inside Objective-C array literals (doing so
2159 // raises the warning -Wobjc-string-concatenation).
2160 if (State.Stack.back().IsInsideObjCArrayLiteral)
2161 return nullptr;
2163 StringRef Text = Current.TokenText;
2164 StringRef Prefix;
2165 StringRef Postfix;
2166 // FIXME: Handle whitespace between '_T', '(', '"..."', and ')'.
2167 // FIXME: Store Prefix and Suffix (or PrefixLength and SuffixLength to
2168 // reduce the overhead) for each FormatToken, which is a string, so that we
2169 // don't run multiple checks here on the hot path.
2170 if ((Text.endswith(Postfix = "\"") &&
2171 (Text.startswith(Prefix = "@\"") || Text.startswith(Prefix = "\"") ||
2172 Text.startswith(Prefix = "u\"") || Text.startswith(Prefix = "U\"") ||
2173 Text.startswith(Prefix = "u8\"") ||
2174 Text.startswith(Prefix = "L\""))) ||
2175 (Text.startswith(Prefix = "_T(\"") && Text.endswith(Postfix = "\")"))) {
2176 // We need this to address the case where there is an unbreakable tail
2177 // only if certain other formatting decisions have been taken. The
2178 // UnbreakableTailLength of Current is an overapproximation is that case
2179 // and we need to be correct here.
2180 unsigned UnbreakableTailLength = (State.NextToken && canBreak(State))
2182 : Current.UnbreakableTailLength;
2183 return std::make_unique<BreakableStringLiteral>(
2184 Current, StartColumn, Prefix, Postfix, UnbreakableTailLength,
2185 State.Line->InPPDirective, Encoding, Style);
2187 } else if (Current.is(TT_BlockComment)) {
2188 if (!Style.ReflowComments ||
2189 // If a comment token switches formatting, like
2190 // /* clang-format on */, we don't want to break it further,
2191 // but we may still want to adjust its indentation.
2192 switchesFormatting(Current)) {
2193 return nullptr;
2195 return std::make_unique<BreakableBlockComment>(
2196 Current, StartColumn, Current.OriginalColumn, !Current.Previous,
2197 State.Line->InPPDirective, Encoding, Style, Whitespaces.useCRLF());
2198 } else if (Current.is(TT_LineComment) &&
2199 (!Current.Previous ||
2200 Current.Previous->isNot(TT_ImplicitStringLiteral))) {
2201 bool RegularComments = [&]() {
2202 for (const FormatToken *T = &Current; T && T->is(TT_LineComment);
2203 T = T->Next) {
2204 if (!(T->TokenText.startswith("//") || T->TokenText.startswith("#")))
2205 return false;
2207 return true;
2208 }();
2209 if (!Style.ReflowComments ||
2210 CommentPragmasRegex.match(Current.TokenText.substr(2)) ||
2211 switchesFormatting(Current) || !RegularComments) {
2212 return nullptr;
2214 return std::make_unique<BreakableLineCommentSection>(
2215 Current, StartColumn, /*InPPDirective=*/false, Encoding, Style);
2217 return nullptr;
2220 std::pair<unsigned, bool>
2221 ContinuationIndenter::breakProtrudingToken(const FormatToken &Current,
2222 LineState &State, bool AllowBreak,
2223 bool DryRun, bool Strict) {
2224 std::unique_ptr<const BreakableToken> Token =
2225 createBreakableToken(Current, State, AllowBreak);
2226 if (!Token)
2227 return {0, false};
2228 assert(Token->getLineCount() > 0);
2229 unsigned ColumnLimit = getColumnLimit(State);
2230 if (Current.is(TT_LineComment)) {
2231 // We don't insert backslashes when breaking line comments.
2232 ColumnLimit = Style.ColumnLimit;
2234 if (ColumnLimit == 0) {
2235 // To make the rest of the function easier set the column limit to the
2236 // maximum, if there should be no limit.
2237 ColumnLimit = std::numeric_limits<decltype(ColumnLimit)>::max();
2239 if (Current.UnbreakableTailLength >= ColumnLimit)
2240 return {0, false};
2241 // ColumnWidth was already accounted into State.Column before calling
2242 // breakProtrudingToken.
2243 unsigned StartColumn = State.Column - Current.ColumnWidth;
2244 unsigned NewBreakPenalty = Current.isStringLiteral()
2245 ? Style.PenaltyBreakString
2246 : Style.PenaltyBreakComment;
2247 // Stores whether we intentionally decide to let a line exceed the column
2248 // limit.
2249 bool Exceeded = false;
2250 // Stores whether we introduce a break anywhere in the token.
2251 bool BreakInserted = Token->introducesBreakBeforeToken();
2252 // Store whether we inserted a new line break at the end of the previous
2253 // logical line.
2254 bool NewBreakBefore = false;
2255 // We use a conservative reflowing strategy. Reflow starts after a line is
2256 // broken or the corresponding whitespace compressed. Reflow ends as soon as a
2257 // line that doesn't get reflown with the previous line is reached.
2258 bool Reflow = false;
2259 // Keep track of where we are in the token:
2260 // Where we are in the content of the current logical line.
2261 unsigned TailOffset = 0;
2262 // The column number we're currently at.
2263 unsigned ContentStartColumn =
2264 Token->getContentStartColumn(0, /*Break=*/false);
2265 // The number of columns left in the current logical line after TailOffset.
2266 unsigned RemainingTokenColumns =
2267 Token->getRemainingLength(0, TailOffset, ContentStartColumn);
2268 // Adapt the start of the token, for example indent.
2269 if (!DryRun)
2270 Token->adaptStartOfLine(0, Whitespaces);
2272 unsigned ContentIndent = 0;
2273 unsigned Penalty = 0;
2274 LLVM_DEBUG(llvm::dbgs() << "Breaking protruding token at column "
2275 << StartColumn << ".\n");
2276 for (unsigned LineIndex = 0, EndIndex = Token->getLineCount();
2277 LineIndex != EndIndex; ++LineIndex) {
2278 LLVM_DEBUG(llvm::dbgs()
2279 << " Line: " << LineIndex << " (Reflow: " << Reflow << ")\n");
2280 NewBreakBefore = false;
2281 // If we did reflow the previous line, we'll try reflowing again. Otherwise
2282 // we'll start reflowing if the current line is broken or whitespace is
2283 // compressed.
2284 bool TryReflow = Reflow;
2285 // Break the current token until we can fit the rest of the line.
2286 while (ContentStartColumn + RemainingTokenColumns > ColumnLimit) {
2287 LLVM_DEBUG(llvm::dbgs() << " Over limit, need: "
2288 << (ContentStartColumn + RemainingTokenColumns)
2289 << ", space: " << ColumnLimit
2290 << ", reflown prefix: " << ContentStartColumn
2291 << ", offset in line: " << TailOffset << "\n");
2292 // If the current token doesn't fit, find the latest possible split in the
2293 // current line so that breaking at it will be under the column limit.
2294 // FIXME: Use the earliest possible split while reflowing to correctly
2295 // compress whitespace within a line.
2296 BreakableToken::Split Split =
2297 Token->getSplit(LineIndex, TailOffset, ColumnLimit,
2298 ContentStartColumn, CommentPragmasRegex);
2299 if (Split.first == StringRef::npos) {
2300 // No break opportunity - update the penalty and continue with the next
2301 // logical line.
2302 if (LineIndex < EndIndex - 1) {
2303 // The last line's penalty is handled in addNextStateToQueue() or when
2304 // calling replaceWhitespaceAfterLastLine below.
2305 Penalty += Style.PenaltyExcessCharacter *
2306 (ContentStartColumn + RemainingTokenColumns - ColumnLimit);
2308 LLVM_DEBUG(llvm::dbgs() << " No break opportunity.\n");
2309 break;
2311 assert(Split.first != 0);
2313 if (Token->supportsReflow()) {
2314 // Check whether the next natural split point after the current one can
2315 // still fit the line, either because we can compress away whitespace,
2316 // or because the penalty the excess characters introduce is lower than
2317 // the break penalty.
2318 // We only do this for tokens that support reflowing, and thus allow us
2319 // to change the whitespace arbitrarily (e.g. comments).
2320 // Other tokens, like string literals, can be broken on arbitrary
2321 // positions.
2323 // First, compute the columns from TailOffset to the next possible split
2324 // position.
2325 // For example:
2326 // ColumnLimit: |
2327 // // Some text that breaks
2328 // ^ tail offset
2329 // ^-- split
2330 // ^-------- to split columns
2331 // ^--- next split
2332 // ^--------------- to next split columns
2333 unsigned ToSplitColumns = Token->getRangeLength(
2334 LineIndex, TailOffset, Split.first, ContentStartColumn);
2335 LLVM_DEBUG(llvm::dbgs() << " ToSplit: " << ToSplitColumns << "\n");
2337 BreakableToken::Split NextSplit = Token->getSplit(
2338 LineIndex, TailOffset + Split.first + Split.second, ColumnLimit,
2339 ContentStartColumn + ToSplitColumns + 1, CommentPragmasRegex);
2340 // Compute the columns necessary to fit the next non-breakable sequence
2341 // into the current line.
2342 unsigned ToNextSplitColumns = 0;
2343 if (NextSplit.first == StringRef::npos) {
2344 ToNextSplitColumns = Token->getRemainingLength(LineIndex, TailOffset,
2345 ContentStartColumn);
2346 } else {
2347 ToNextSplitColumns = Token->getRangeLength(
2348 LineIndex, TailOffset,
2349 Split.first + Split.second + NextSplit.first, ContentStartColumn);
2351 // Compress the whitespace between the break and the start of the next
2352 // unbreakable sequence.
2353 ToNextSplitColumns =
2354 Token->getLengthAfterCompression(ToNextSplitColumns, Split);
2355 LLVM_DEBUG(llvm::dbgs()
2356 << " ContentStartColumn: " << ContentStartColumn << "\n");
2357 LLVM_DEBUG(llvm::dbgs()
2358 << " ToNextSplit: " << ToNextSplitColumns << "\n");
2359 // If the whitespace compression makes us fit, continue on the current
2360 // line.
2361 bool ContinueOnLine =
2362 ContentStartColumn + ToNextSplitColumns <= ColumnLimit;
2363 unsigned ExcessCharactersPenalty = 0;
2364 if (!ContinueOnLine && !Strict) {
2365 // Similarly, if the excess characters' penalty is lower than the
2366 // penalty of introducing a new break, continue on the current line.
2367 ExcessCharactersPenalty =
2368 (ContentStartColumn + ToNextSplitColumns - ColumnLimit) *
2369 Style.PenaltyExcessCharacter;
2370 LLVM_DEBUG(llvm::dbgs()
2371 << " Penalty excess: " << ExcessCharactersPenalty
2372 << "\n break : " << NewBreakPenalty << "\n");
2373 if (ExcessCharactersPenalty < NewBreakPenalty) {
2374 Exceeded = true;
2375 ContinueOnLine = true;
2378 if (ContinueOnLine) {
2379 LLVM_DEBUG(llvm::dbgs() << " Continuing on line...\n");
2380 // The current line fits after compressing the whitespace - reflow
2381 // the next line into it if possible.
2382 TryReflow = true;
2383 if (!DryRun) {
2384 Token->compressWhitespace(LineIndex, TailOffset, Split,
2385 Whitespaces);
2387 // When we continue on the same line, leave one space between content.
2388 ContentStartColumn += ToSplitColumns + 1;
2389 Penalty += ExcessCharactersPenalty;
2390 TailOffset += Split.first + Split.second;
2391 RemainingTokenColumns = Token->getRemainingLength(
2392 LineIndex, TailOffset, ContentStartColumn);
2393 continue;
2396 LLVM_DEBUG(llvm::dbgs() << " Breaking...\n");
2397 // Update the ContentIndent only if the current line was not reflown with
2398 // the previous line, since in that case the previous line should still
2399 // determine the ContentIndent. Also never intent the last line.
2400 if (!Reflow)
2401 ContentIndent = Token->getContentIndent(LineIndex);
2402 LLVM_DEBUG(llvm::dbgs()
2403 << " ContentIndent: " << ContentIndent << "\n");
2404 ContentStartColumn = ContentIndent + Token->getContentStartColumn(
2405 LineIndex, /*Break=*/true);
2407 unsigned NewRemainingTokenColumns = Token->getRemainingLength(
2408 LineIndex, TailOffset + Split.first + Split.second,
2409 ContentStartColumn);
2410 if (NewRemainingTokenColumns == 0) {
2411 // No content to indent.
2412 ContentIndent = 0;
2413 ContentStartColumn =
2414 Token->getContentStartColumn(LineIndex, /*Break=*/true);
2415 NewRemainingTokenColumns = Token->getRemainingLength(
2416 LineIndex, TailOffset + Split.first + Split.second,
2417 ContentStartColumn);
2420 // When breaking before a tab character, it may be moved by a few columns,
2421 // but will still be expanded to the next tab stop, so we don't save any
2422 // columns.
2423 if (NewRemainingTokenColumns >= RemainingTokenColumns) {
2424 // FIXME: Do we need to adjust the penalty?
2425 break;
2428 LLVM_DEBUG(llvm::dbgs() << " Breaking at: " << TailOffset + Split.first
2429 << ", " << Split.second << "\n");
2430 if (!DryRun) {
2431 Token->insertBreak(LineIndex, TailOffset, Split, ContentIndent,
2432 Whitespaces);
2435 Penalty += NewBreakPenalty;
2436 TailOffset += Split.first + Split.second;
2437 RemainingTokenColumns = NewRemainingTokenColumns;
2438 BreakInserted = true;
2439 NewBreakBefore = true;
2441 // In case there's another line, prepare the state for the start of the next
2442 // line.
2443 if (LineIndex + 1 != EndIndex) {
2444 unsigned NextLineIndex = LineIndex + 1;
2445 if (NewBreakBefore) {
2446 // After breaking a line, try to reflow the next line into the current
2447 // one once RemainingTokenColumns fits.
2448 TryReflow = true;
2450 if (TryReflow) {
2451 // We decided that we want to try reflowing the next line into the
2452 // current one.
2453 // We will now adjust the state as if the reflow is successful (in
2454 // preparation for the next line), and see whether that works. If we
2455 // decide that we cannot reflow, we will later reset the state to the
2456 // start of the next line.
2457 Reflow = false;
2458 // As we did not continue breaking the line, RemainingTokenColumns is
2459 // known to fit after ContentStartColumn. Adapt ContentStartColumn to
2460 // the position at which we want to format the next line if we do
2461 // actually reflow.
2462 // When we reflow, we need to add a space between the end of the current
2463 // line and the next line's start column.
2464 ContentStartColumn += RemainingTokenColumns + 1;
2465 // Get the split that we need to reflow next logical line into the end
2466 // of the current one; the split will include any leading whitespace of
2467 // the next logical line.
2468 BreakableToken::Split SplitBeforeNext =
2469 Token->getReflowSplit(NextLineIndex, CommentPragmasRegex);
2470 LLVM_DEBUG(llvm::dbgs()
2471 << " Size of reflown text: " << ContentStartColumn
2472 << "\n Potential reflow split: ");
2473 if (SplitBeforeNext.first != StringRef::npos) {
2474 LLVM_DEBUG(llvm::dbgs() << SplitBeforeNext.first << ", "
2475 << SplitBeforeNext.second << "\n");
2476 TailOffset = SplitBeforeNext.first + SplitBeforeNext.second;
2477 // If the rest of the next line fits into the current line below the
2478 // column limit, we can safely reflow.
2479 RemainingTokenColumns = Token->getRemainingLength(
2480 NextLineIndex, TailOffset, ContentStartColumn);
2481 Reflow = true;
2482 if (ContentStartColumn + RemainingTokenColumns > ColumnLimit) {
2483 LLVM_DEBUG(llvm::dbgs()
2484 << " Over limit after reflow, need: "
2485 << (ContentStartColumn + RemainingTokenColumns)
2486 << ", space: " << ColumnLimit
2487 << ", reflown prefix: " << ContentStartColumn
2488 << ", offset in line: " << TailOffset << "\n");
2489 // If the whole next line does not fit, try to find a point in
2490 // the next line at which we can break so that attaching the part
2491 // of the next line to that break point onto the current line is
2492 // below the column limit.
2493 BreakableToken::Split Split =
2494 Token->getSplit(NextLineIndex, TailOffset, ColumnLimit,
2495 ContentStartColumn, CommentPragmasRegex);
2496 if (Split.first == StringRef::npos) {
2497 LLVM_DEBUG(llvm::dbgs() << " Did not find later break\n");
2498 Reflow = false;
2499 } else {
2500 // Check whether the first split point gets us below the column
2501 // limit. Note that we will execute this split below as part of
2502 // the normal token breaking and reflow logic within the line.
2503 unsigned ToSplitColumns = Token->getRangeLength(
2504 NextLineIndex, TailOffset, Split.first, ContentStartColumn);
2505 if (ContentStartColumn + ToSplitColumns > ColumnLimit) {
2506 LLVM_DEBUG(llvm::dbgs() << " Next split protrudes, need: "
2507 << (ContentStartColumn + ToSplitColumns)
2508 << ", space: " << ColumnLimit);
2509 unsigned ExcessCharactersPenalty =
2510 (ContentStartColumn + ToSplitColumns - ColumnLimit) *
2511 Style.PenaltyExcessCharacter;
2512 if (NewBreakPenalty < ExcessCharactersPenalty)
2513 Reflow = false;
2517 } else {
2518 LLVM_DEBUG(llvm::dbgs() << "not found.\n");
2521 if (!Reflow) {
2522 // If we didn't reflow into the next line, the only space to consider is
2523 // the next logical line. Reset our state to match the start of the next
2524 // line.
2525 TailOffset = 0;
2526 ContentStartColumn =
2527 Token->getContentStartColumn(NextLineIndex, /*Break=*/false);
2528 RemainingTokenColumns = Token->getRemainingLength(
2529 NextLineIndex, TailOffset, ContentStartColumn);
2530 // Adapt the start of the token, for example indent.
2531 if (!DryRun)
2532 Token->adaptStartOfLine(NextLineIndex, Whitespaces);
2533 } else {
2534 // If we found a reflow split and have added a new break before the next
2535 // line, we are going to remove the line break at the start of the next
2536 // logical line. For example, here we'll add a new line break after
2537 // 'text', and subsequently delete the line break between 'that' and
2538 // 'reflows'.
2539 // // some text that
2540 // // reflows
2541 // ->
2542 // // some text
2543 // // that reflows
2544 // When adding the line break, we also added the penalty for it, so we
2545 // need to subtract that penalty again when we remove the line break due
2546 // to reflowing.
2547 if (NewBreakBefore) {
2548 assert(Penalty >= NewBreakPenalty);
2549 Penalty -= NewBreakPenalty;
2551 if (!DryRun)
2552 Token->reflow(NextLineIndex, Whitespaces);
2557 BreakableToken::Split SplitAfterLastLine =
2558 Token->getSplitAfterLastLine(TailOffset);
2559 if (SplitAfterLastLine.first != StringRef::npos) {
2560 LLVM_DEBUG(llvm::dbgs() << "Replacing whitespace after last line.\n");
2562 // We add the last line's penalty here, since that line is going to be split
2563 // now.
2564 Penalty += Style.PenaltyExcessCharacter *
2565 (ContentStartColumn + RemainingTokenColumns - ColumnLimit);
2567 if (!DryRun) {
2568 Token->replaceWhitespaceAfterLastLine(TailOffset, SplitAfterLastLine,
2569 Whitespaces);
2571 ContentStartColumn =
2572 Token->getContentStartColumn(Token->getLineCount() - 1, /*Break=*/true);
2573 RemainingTokenColumns = Token->getRemainingLength(
2574 Token->getLineCount() - 1,
2575 TailOffset + SplitAfterLastLine.first + SplitAfterLastLine.second,
2576 ContentStartColumn);
2579 State.Column = ContentStartColumn + RemainingTokenColumns -
2580 Current.UnbreakableTailLength;
2582 if (BreakInserted) {
2583 // If we break the token inside a parameter list, we need to break before
2584 // the next parameter on all levels, so that the next parameter is clearly
2585 // visible. Line comments already introduce a break.
2586 if (Current.isNot(TT_LineComment))
2587 for (ParenState &Paren : State.Stack)
2588 Paren.BreakBeforeParameter = true;
2590 if (Current.is(TT_BlockComment))
2591 State.NoContinuation = true;
2593 State.Stack.back().LastSpace = StartColumn;
2596 Token->updateNextToken(State);
2598 return {Penalty, Exceeded};
2601 unsigned ContinuationIndenter::getColumnLimit(const LineState &State) const {
2602 // In preprocessor directives reserve two chars for trailing " \".
2603 return Style.ColumnLimit - (State.Line->InPPDirective ? 2 : 0);
2606 bool ContinuationIndenter::nextIsMultilineString(const LineState &State) {
2607 const FormatToken &Current = *State.NextToken;
2608 if (!Current.isStringLiteral() || Current.is(TT_ImplicitStringLiteral))
2609 return false;
2610 // We never consider raw string literals "multiline" for the purpose of
2611 // AlwaysBreakBeforeMultilineStrings implementation as they are special-cased
2612 // (see TokenAnnotator::mustBreakBefore().
2613 if (Current.TokenText.startswith("R\""))
2614 return false;
2615 if (Current.IsMultiline)
2616 return true;
2617 if (Current.getNextNonComment() &&
2618 Current.getNextNonComment()->isStringLiteral()) {
2619 return true; // Implicit concatenation.
2621 if (Style.ColumnLimit != 0 && Style.BreakStringLiterals &&
2622 State.Column + Current.ColumnWidth + Current.UnbreakableTailLength >
2623 Style.ColumnLimit) {
2624 return true; // String will be split.
2626 return false;
2629 } // namespace format
2630 } // namespace clang