clang 20.0.0git
ContinuationIndenter.cpp
Go to the documentation of this file.
1//===--- ContinuationIndenter.cpp - Format C++ code -----------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8///
9/// \file
10/// This file implements the continuation indenter.
11///
12//===----------------------------------------------------------------------===//
13
15#include "BreakableToken.h"
16#include "FormatInternal.h"
17#include "FormatToken.h"
18#include "WhitespaceManager.h"
22#include "clang/Format/Format.h"
23#include "llvm/ADT/StringSet.h"
24#include "llvm/Support/Debug.h"
25#include <optional>
26
27#define DEBUG_TYPE "format-indenter"
28
29namespace clang {
30namespace format {
31
32// Returns true if a TT_SelectorName should be indented when wrapped,
33// false otherwise.
37}
38
39// Returns true if a binary operator following \p Tok should be unindented when
40// the style permits it.
41static bool shouldUnindentNextOperator(const FormatToken &Tok) {
43 return Previous && (Previous->getPrecedence() == prec::Assignment ||
44 Previous->isOneOf(tok::kw_return, TT_RequiresClause));
45}
46
47// Returns the length of everything up to the first possible line break after
48// the ), ], } or > matching \c Tok.
49static unsigned getLengthToMatchingParen(const FormatToken &Tok,
51 // Normally whether or not a break before T is possible is calculated and
52 // stored in T.CanBreakBefore. Braces, array initializers and text proto
53 // messages like `key: < ... >` are an exception: a break is possible
54 // before a closing brace R if a break was inserted after the corresponding
55 // opening brace. The information about whether or not a break is needed
56 // before a closing brace R is stored in the ParenState field
57 // S.BreakBeforeClosingBrace where S is the state that R closes.
58 //
59 // In order to decide whether there can be a break before encountered right
60 // braces, this implementation iterates over the sequence of tokens and over
61 // the paren stack in lockstep, keeping track of the stack level which visited
62 // right braces correspond to in MatchingStackIndex.
63 //
64 // For example, consider:
65 // L. <- line number
66 // 1. {
67 // 2. {1},
68 // 3. {2},
69 // 4. {{3}}}
70 // ^ where we call this method with this token.
71 // The paren stack at this point contains 3 brace levels:
72 // 0. { at line 1, BreakBeforeClosingBrace: true
73 // 1. first { at line 4, BreakBeforeClosingBrace: false
74 // 2. second { at line 4, BreakBeforeClosingBrace: false,
75 // where there might be fake parens levels in-between these levels.
76 // The algorithm will start at the first } on line 4, which is the matching
77 // brace of the initial left brace and at level 2 of the stack. Then,
78 // examining BreakBeforeClosingBrace: false at level 2, it will continue to
79 // the second } on line 4, and will traverse the stack downwards until it
80 // finds the matching { on level 1. Then, examining BreakBeforeClosingBrace:
81 // false at level 1, it will continue to the third } on line 4 and will
82 // traverse the stack downwards until it finds the matching { on level 0.
83 // Then, examining BreakBeforeClosingBrace: true at level 0, the algorithm
84 // will stop and will use the second } on line 4 to determine the length to
85 // return, as in this example the range will include the tokens: {3}}
86 //
87 // The algorithm will only traverse the stack if it encounters braces, array
88 // initializer squares or text proto angle brackets.
89 if (!Tok.MatchingParen)
90 return 0;
91 FormatToken *End = Tok.MatchingParen;
92 // Maintains a stack level corresponding to the current End token.
93 int MatchingStackIndex = Stack.size() - 1;
94 // Traverses the stack downwards, looking for the level to which LBrace
95 // corresponds. Returns either a pointer to the matching level or nullptr if
96 // LParen is not found in the initial portion of the stack up to
97 // MatchingStackIndex.
98 auto FindParenState = [&](const FormatToken *LBrace) -> const ParenState * {
99 while (MatchingStackIndex >= 0 && Stack[MatchingStackIndex].Tok != LBrace)
100 --MatchingStackIndex;
101 return MatchingStackIndex >= 0 ? &Stack[MatchingStackIndex] : nullptr;
102 };
103 for (; End->Next; End = End->Next) {
104 if (End->Next->CanBreakBefore)
105 break;
106 if (!End->Next->closesScope())
107 continue;
108 if (End->Next->MatchingParen &&
109 End->Next->MatchingParen->isOneOf(
110 tok::l_brace, TT_ArrayInitializerLSquare, tok::less)) {
111 const ParenState *State = FindParenState(End->Next->MatchingParen);
112 if (State && State->BreakBeforeClosingBrace)
113 break;
114 }
115 }
116 return End->TotalLength - Tok.TotalLength + 1;
117}
118
119static unsigned getLengthToNextOperator(const FormatToken &Tok) {
120 if (!Tok.NextOperator)
121 return 0;
122 return Tok.NextOperator->TotalLength - Tok.TotalLength;
123}
124
125// Returns \c true if \c Tok is the "." or "->" of a call and starts the next
126// segment of a builder type call.
128 return Tok.isMemberAccess() && Tok.Previous && Tok.Previous->closesScope();
129}
130
131// Returns \c true if \c Current starts a new parameter.
132static bool startsNextParameter(const FormatToken &Current,
133 const FormatStyle &Style) {
134 assert(Current.Previous);
135 const auto &Previous = *Current.Previous;
136 if (Current.is(TT_CtorInitializerComma) &&
138 return true;
139 }
140 if (Style.Language == FormatStyle::LK_Proto && Current.is(TT_SelectorName))
141 return true;
142 return Previous.is(tok::comma) && !Current.isTrailingComment() &&
143 ((Previous.isNot(TT_CtorInitializerComma) ||
146 (Previous.isNot(TT_InheritanceComma) ||
148}
149
150// Returns \c true if \c Token in an alignable binary operator
152 // No need to align binary operators that only have two operands.
153 bool HasTwoOperands = Token.OperatorIndex == 0 && !Token.NextOperator;
154 return Token.is(TT_BinaryOperator) && !HasTwoOperands &&
155 Token.getPrecedence() > prec::Conditional &&
156 Token.getPrecedence() < prec::PointerToMember;
157}
158
159// Returns \c true if \c Current starts the next operand in a binary operation.
160static bool startsNextOperand(const FormatToken &Current) {
161 assert(Current.Previous);
162 const auto &Previous = *Current.Previous;
164}
165
166// Returns \c true if \c Current is a binary operation that must break.
167static bool mustBreakBinaryOperation(const FormatToken &Current,
168 const FormatStyle &Style) {
172 : isAlignableBinaryOperator)(Current);
173}
174
175static bool opensProtoMessageField(const FormatToken &LessTok,
176 const FormatStyle &Style) {
177 if (LessTok.isNot(tok::less))
178 return false;
179 return Style.Language == FormatStyle::LK_TextProto ||
181 (LessTok.NestingLevel > 0 ||
182 (LessTok.Previous && LessTok.Previous->is(tok::equal))));
183}
184
185// Returns the delimiter of a raw string literal, or std::nullopt if TokenText
186// is not the text of a raw string literal. The delimiter could be the empty
187// string. For example, the delimiter of R"deli(cont)deli" is deli.
188static std::optional<StringRef> getRawStringDelimiter(StringRef TokenText) {
189 if (TokenText.size() < 5 // The smallest raw string possible is 'R"()"'.
190 || !TokenText.starts_with("R\"") || !TokenText.ends_with("\"")) {
191 return std::nullopt;
192 }
193
194 // A raw string starts with 'R"<delimiter>(' and delimiter is ascii and has
195 // size at most 16 by the standard, so the first '(' must be among the first
196 // 19 bytes.
197 size_t LParenPos = TokenText.substr(0, 19).find_first_of('(');
198 if (LParenPos == StringRef::npos)
199 return std::nullopt;
200 StringRef Delimiter = TokenText.substr(2, LParenPos - 2);
201
202 // Check that the string ends in ')Delimiter"'.
203 size_t RParenPos = TokenText.size() - Delimiter.size() - 2;
204 if (TokenText[RParenPos] != ')')
205 return std::nullopt;
206 if (!TokenText.substr(RParenPos + 1).starts_with(Delimiter))
207 return std::nullopt;
208 return Delimiter;
209}
210
211// Returns the canonical delimiter for \p Language, or the empty string if no
212// canonical delimiter is specified.
213static StringRef
216 for (const auto &Format : Style.RawStringFormats)
217 if (Format.Language == Language)
218 return StringRef(Format.CanonicalDelimiter);
219 return "";
220}
221
223 const FormatStyle &CodeStyle) {
224 for (const auto &RawStringFormat : CodeStyle.RawStringFormats) {
225 std::optional<FormatStyle> LanguageStyle =
226 CodeStyle.GetLanguageStyle(RawStringFormat.Language);
227 if (!LanguageStyle) {
228 FormatStyle PredefinedStyle;
229 if (!getPredefinedStyle(RawStringFormat.BasedOnStyle,
230 RawStringFormat.Language, &PredefinedStyle)) {
231 PredefinedStyle = getLLVMStyle();
232 PredefinedStyle.Language = RawStringFormat.Language;
233 }
234 LanguageStyle = PredefinedStyle;
235 }
236 LanguageStyle->ColumnLimit = CodeStyle.ColumnLimit;
237 for (StringRef Delimiter : RawStringFormat.Delimiters)
238 DelimiterStyle.insert({Delimiter, *LanguageStyle});
239 for (StringRef EnclosingFunction : RawStringFormat.EnclosingFunctions)
240 EnclosingFunctionStyle.insert({EnclosingFunction, *LanguageStyle});
241 }
242}
243
244std::optional<FormatStyle>
246 auto It = DelimiterStyle.find(Delimiter);
247 if (It == DelimiterStyle.end())
248 return std::nullopt;
249 return It->second;
250}
251
252std::optional<FormatStyle>
254 StringRef EnclosingFunction) const {
255 auto It = EnclosingFunctionStyle.find(EnclosingFunction);
256 if (It == EnclosingFunctionStyle.end())
257 return std::nullopt;
258 return It->second;
259}
260
262 const AdditionalKeywords &Keywords,
263 const SourceManager &SourceMgr,
264 WhitespaceManager &Whitespaces,
265 encoding::Encoding Encoding,
266 bool BinPackInconclusiveFunctions)
267 : Style(Style), Keywords(Keywords), SourceMgr(SourceMgr),
268 Whitespaces(Whitespaces), Encoding(Encoding),
269 BinPackInconclusiveFunctions(BinPackInconclusiveFunctions),
270 CommentPragmasRegex(Style.CommentPragmas), RawStringFormats(Style) {}
271
273 unsigned FirstStartColumn,
274 const AnnotatedLine *Line,
275 bool DryRun) {
276 LineState State;
277 State.FirstIndent = FirstIndent;
278 if (FirstStartColumn && Line->First->NewlinesBefore == 0)
279 State.Column = FirstStartColumn;
280 else
281 State.Column = FirstIndent;
282 // With preprocessor directive indentation, the line starts on column 0
283 // since it's indented after the hash, but FirstIndent is set to the
284 // preprocessor indent.
286 (Line->Type == LT_PreprocessorDirective ||
287 Line->Type == LT_ImportStatement)) {
288 State.Column = 0;
289 }
290 State.Line = Line;
291 State.NextToken = Line->First;
292 State.Stack.push_back(ParenState(/*Tok=*/nullptr, FirstIndent, FirstIndent,
293 /*AvoidBinPacking=*/false,
294 /*NoLineBreak=*/false));
295 State.NoContinuation = false;
296 State.StartOfStringLiteral = 0;
297 State.NoLineBreak = false;
298 State.StartOfLineLevel = 0;
299 State.LowestLevelOnLine = 0;
300 State.IgnoreStackForComparison = false;
301
302 if (Style.Language == FormatStyle::LK_TextProto) {
303 // We need this in order to deal with the bin packing of text fields at
304 // global scope.
305 auto &CurrentState = State.Stack.back();
306 CurrentState.AvoidBinPacking = true;
307 CurrentState.BreakBeforeParameter = true;
308 CurrentState.AlignColons = false;
309 }
310
311 // The first token has already been indented and thus consumed.
312 moveStateToNextToken(State, DryRun, /*Newline=*/false);
313 return State;
314}
315
317 const FormatToken &Current = *State.NextToken;
318 const FormatToken &Previous = *Current.Previous;
319 const auto &CurrentState = State.Stack.back();
320 assert(&Previous == Current.Previous);
321 if (!Current.CanBreakBefore && !(CurrentState.BreakBeforeClosingBrace &&
322 Current.closesBlockOrBlockTypeList(Style))) {
323 return false;
324 }
325 // The opening "{" of a braced list has to be on the same line as the first
326 // element if it is nested in another braced init list or function call.
327 if (!Current.MustBreakBefore && Previous.is(tok::l_brace) &&
328 Previous.isNot(TT_DictLiteral) && Previous.is(BK_BracedInit) &&
329 Previous.Previous &&
330 Previous.Previous->isOneOf(tok::l_brace, tok::l_paren, tok::comma)) {
331 return false;
332 }
333 // This prevents breaks like:
334 // ...
335 // SomeParameter, OtherParameter).DoSomething(
336 // ...
337 // As they hide "DoSomething" and are generally bad for readability.
338 if (Previous.opensScope() && Previous.isNot(tok::l_brace) &&
339 State.LowestLevelOnLine < State.StartOfLineLevel &&
340 State.LowestLevelOnLine < Current.NestingLevel) {
341 return false;
342 }
343 if (Current.isMemberAccess() && CurrentState.ContainsUnwrappedBuilder)
344 return false;
345
346 // Don't create a 'hanging' indent if there are multiple blocks in a single
347 // statement and we are aligning lambda blocks to their signatures.
348 if (Previous.is(tok::l_brace) && State.Stack.size() > 1 &&
349 State.Stack[State.Stack.size() - 2].NestedBlockInlined &&
350 State.Stack[State.Stack.size() - 2].HasMultipleNestedBlocks &&
352 return false;
353 }
354
355 // Don't break after very short return types (e.g. "void") as that is often
356 // unexpected.
357 if (Current.is(TT_FunctionDeclarationName)) {
359 State.Column < 6) {
360 return false;
361 }
362
364 assert(State.Column >= State.FirstIndent);
365 if (State.Column - State.FirstIndent < 6)
366 return false;
367 }
368 }
369
370 // If binary operators are moved to the next line (including commas for some
371 // styles of constructor initializers), that's always ok.
372 if (!Current.isOneOf(TT_BinaryOperator, tok::comma) &&
373 // Allow breaking opening brace of lambdas (when passed as function
374 // arguments) to a new line when BeforeLambdaBody brace wrapping is
375 // enabled.
377 Current.isNot(TT_LambdaLBrace)) &&
378 CurrentState.NoLineBreakInOperand) {
379 return false;
380 }
381
382 if (Previous.is(tok::l_square) && Previous.is(TT_ObjCMethodExpr))
383 return false;
384
385 if (Current.is(TT_ConditionalExpr) && Previous.is(tok::r_paren) &&
386 Previous.MatchingParen && Previous.MatchingParen->Previous &&
387 Previous.MatchingParen->Previous->MatchingParen &&
388 Previous.MatchingParen->Previous->MatchingParen->is(TT_LambdaLBrace)) {
389 // We have a lambda within a conditional expression, allow breaking here.
390 assert(Previous.MatchingParen->Previous->is(tok::r_brace));
391 return true;
392 }
393
394 return !State.NoLineBreak && !CurrentState.NoLineBreak;
395}
396
398 const FormatToken &Current = *State.NextToken;
399 const FormatToken &Previous = *Current.Previous;
400 const auto &CurrentState = State.Stack.back();
401 if (Style.BraceWrapping.BeforeLambdaBody && Current.CanBreakBefore &&
402 Current.is(TT_LambdaLBrace) && Previous.isNot(TT_LineComment)) {
403 auto LambdaBodyLength = getLengthToMatchingParen(Current, State.Stack);
404 return LambdaBodyLength > getColumnLimit(State);
405 }
406 if (Current.MustBreakBefore ||
407 (Current.is(TT_InlineASMColon) &&
410 Style.ColumnLimit > 0)))) {
411 return true;
412 }
413 if (CurrentState.BreakBeforeClosingBrace &&
414 (Current.closesBlockOrBlockTypeList(Style) ||
415 (Current.is(tok::r_brace) &&
416 Current.isBlockIndentedInitRBrace(Style)))) {
417 return true;
418 }
419 if (CurrentState.BreakBeforeClosingParen && Current.is(tok::r_paren))
420 return true;
421 if (Style.Language == FormatStyle::LK_ObjC &&
423 Current.ObjCSelectorNameParts > 1 &&
424 Current.startsSequence(TT_SelectorName, tok::colon, tok::caret)) {
425 return true;
426 }
427 // Avoid producing inconsistent states by requiring breaks where they are not
428 // permitted for C# generic type constraints.
429 if (CurrentState.IsCSharpGenericTypeConstraint &&
430 Previous.isNot(TT_CSharpGenericTypeConstraintComma)) {
431 return false;
432 }
433 if ((startsNextParameter(Current, Style) || Previous.is(tok::semi) ||
434 (Previous.is(TT_TemplateCloser) && Current.is(TT_StartOfName) &&
435 State.Line->First->isNot(TT_AttributeSquare) && Style.isCpp() &&
436 // FIXME: This is a temporary workaround for the case where clang-format
437 // sets BreakBeforeParameter to avoid bin packing and this creates a
438 // completely unnecessary line break after a template type that isn't
439 // line-wrapped.
440 (Previous.NestingLevel == 1 || Style.BinPackParameters)) ||
441 (Style.BreakBeforeTernaryOperators && Current.is(TT_ConditionalExpr) &&
442 Previous.isNot(tok::question)) ||
444 Previous.is(TT_ConditionalExpr))) &&
445 CurrentState.BreakBeforeParameter && !Current.isTrailingComment() &&
446 !Current.isOneOf(tok::r_paren, tok::r_brace)) {
447 return true;
448 }
449 if (CurrentState.IsChainedConditional &&
450 ((Style.BreakBeforeTernaryOperators && Current.is(TT_ConditionalExpr) &&
451 Current.is(tok::colon)) ||
452 (!Style.BreakBeforeTernaryOperators && Previous.is(TT_ConditionalExpr) &&
453 Previous.is(tok::colon)))) {
454 return true;
455 }
456 if (((Previous.is(TT_DictLiteral) && Previous.is(tok::l_brace)) ||
457 (Previous.is(TT_ArrayInitializerLSquare) &&
458 Previous.ParameterCount > 1) ||
460 Style.ColumnLimit > 0 &&
461 getLengthToMatchingParen(Previous, State.Stack) + State.Column - 1 >
462 getColumnLimit(State)) {
463 return true;
464 }
465
466 const FormatToken &BreakConstructorInitializersToken =
468 ? Previous
469 : Current;
470 if (BreakConstructorInitializersToken.is(TT_CtorInitializerColon) &&
471 (State.Column + State.Line->Last->TotalLength - Previous.TotalLength >
472 getColumnLimit(State) ||
473 CurrentState.BreakBeforeParameter) &&
474 (!Current.isTrailingComment() || Current.NewlinesBefore > 0) &&
477 Style.ColumnLimit != 0)) {
478 return true;
479 }
480
481 if (Current.is(TT_ObjCMethodExpr) && Previous.isNot(TT_SelectorName) &&
482 State.Line->startsWith(TT_ObjCMethodSpecifier)) {
483 return true;
484 }
485 if (Current.is(TT_SelectorName) && Previous.isNot(tok::at) &&
486 CurrentState.ObjCSelectorNameFound && CurrentState.BreakBeforeParameter &&
488 !Current.startsSequence(TT_SelectorName, tok::colon, tok::caret))) {
489 return true;
490 }
491
492 unsigned NewLineColumn = getNewLineColumn(State);
493 if (Current.isMemberAccess() && Style.ColumnLimit != 0 &&
494 State.Column + getLengthToNextOperator(Current) > Style.ColumnLimit &&
495 (State.Column > NewLineColumn ||
496 Current.NestingLevel < State.StartOfLineLevel)) {
497 return true;
498 }
499
500 if (startsSegmentOfBuilderTypeCall(Current) &&
501 (CurrentState.CallContinuation != 0 ||
502 CurrentState.BreakBeforeParameter) &&
503 // JavaScript is treated different here as there is a frequent pattern:
504 // SomeFunction(function() {
505 // ...
506 // }.bind(...));
507 // FIXME: We should find a more generic solution to this problem.
508 !(State.Column <= NewLineColumn && Style.isJavaScript()) &&
509 !(Previous.closesScopeAfterBlock() && State.Column <= NewLineColumn)) {
510 return true;
511 }
512
513 // If the template declaration spans multiple lines, force wrap before the
514 // function/class declaration.
515 if (Previous.ClosesTemplateDeclaration && CurrentState.BreakBeforeParameter &&
516 Current.CanBreakBefore) {
517 return true;
518 }
519
520 if (State.Line->First->isNot(tok::kw_enum) && State.Column <= NewLineColumn)
521 return false;
522
524 (NewLineColumn == State.FirstIndent + Style.ContinuationIndentWidth ||
525 Previous.is(tok::comma) || Current.NestingLevel < 2) &&
526 !Previous.isOneOf(tok::kw_return, tok::lessless, tok::at,
527 Keywords.kw_dollar) &&
528 !Previous.isOneOf(TT_InlineASMColon, TT_ConditionalExpr) &&
529 nextIsMultilineString(State)) {
530 return true;
531 }
532
533 // Using CanBreakBefore here and below takes care of the decision whether the
534 // current style uses wrapping before or after operators for the given
535 // operator.
536 if (Previous.is(TT_BinaryOperator) && Current.CanBreakBefore) {
537 const auto PreviousPrecedence = Previous.getPrecedence();
538 if (PreviousPrecedence != prec::Assignment &&
539 CurrentState.BreakBeforeParameter && !Current.isTrailingComment()) {
540 const bool LHSIsBinaryExpr =
541 Previous.Previous && Previous.Previous->EndsBinaryExpression;
542 if (LHSIsBinaryExpr)
543 return true;
544 // If we need to break somewhere inside the LHS of a binary expression, we
545 // should also break after the operator. Otherwise, the formatting would
546 // hide the operator precedence, e.g. in:
547 // if (aaaaaaaaaaaaaa ==
548 // bbbbbbbbbbbbbb && c) {..
549 // For comparisons, we only apply this rule, if the LHS is a binary
550 // expression itself as otherwise, the line breaks seem superfluous.
551 // We need special cases for ">>" which we have split into two ">" while
552 // lexing in order to make template parsing easier.
553 const bool IsComparison =
554 (PreviousPrecedence == prec::Relational ||
555 PreviousPrecedence == prec::Equality ||
556 PreviousPrecedence == prec::Spaceship) &&
557 Previous.Previous &&
558 Previous.Previous->isNot(TT_BinaryOperator); // For >>.
559 if (!IsComparison)
560 return true;
561 }
562 } else if (Current.is(TT_BinaryOperator) && Current.CanBreakBefore &&
563 CurrentState.BreakBeforeParameter) {
564 return true;
565 }
566
567 // Same as above, but for the first "<<" operator.
568 if (Current.is(tok::lessless) && Current.isNot(TT_OverloadedOperator) &&
569 CurrentState.BreakBeforeParameter && CurrentState.FirstLessLess == 0) {
570 return true;
571 }
572
573 if (Current.NestingLevel == 0 && !Current.isTrailingComment()) {
574 // Always break after "template <...>"(*) and leading annotations. This is
575 // only for cases where the entire line does not fit on a single line as a
576 // different LineFormatter would be used otherwise.
577 // *: Except when another option interferes with that, like concepts.
578 if (Previous.ClosesTemplateDeclaration) {
579 if (Current.is(tok::kw_concept)) {
580 switch (Style.BreakBeforeConceptDeclarations) {
582 break;
584 return true;
586 return false;
587 }
588 }
589 if (Current.is(TT_RequiresClause)) {
590 switch (Style.RequiresClausePosition) {
593 return false;
594 default:
595 return true;
596 }
597 }
600 Current.NewlinesBefore > 0);
601 }
602 if (Previous.is(TT_FunctionAnnotationRParen) &&
603 State.Line->Type != LT_PreprocessorDirective) {
604 return true;
605 }
606 if (Previous.is(TT_LeadingJavaAnnotation) && Current.isNot(tok::l_paren) &&
607 Current.isNot(TT_LeadingJavaAnnotation)) {
608 return true;
609 }
610 }
611
612 if (Style.isJavaScript() && Previous.is(tok::r_paren) &&
613 Previous.is(TT_JavaAnnotation)) {
614 // Break after the closing parenthesis of TypeScript decorators before
615 // functions, getters and setters.
616 static const llvm::StringSet<> BreakBeforeDecoratedTokens = {"get", "set",
617 "function"};
618 if (BreakBeforeDecoratedTokens.contains(Current.TokenText))
619 return true;
620 }
621
622 if (Current.is(TT_FunctionDeclarationName) &&
623 !State.Line->ReturnTypeWrapped &&
624 // Don't break before a C# function when no break after return type.
625 (!Style.isCSharp() ||
627 // Don't always break between a JavaScript `function` and the function
628 // name.
629 !Style.isJavaScript() && Previous.isNot(tok::kw_template) &&
630 CurrentState.BreakBeforeParameter) {
631 return true;
632 }
633
634 // The following could be precomputed as they do not depend on the state.
635 // However, as they should take effect only if the UnwrappedLine does not fit
636 // into the ColumnLimit, they are checked here in the ContinuationIndenter.
637 if (Style.ColumnLimit != 0 && Previous.is(BK_Block) &&
638 Previous.is(tok::l_brace) &&
639 !Current.isOneOf(tok::r_brace, tok::comment)) {
640 return true;
641 }
642
643 if (Current.is(tok::lessless) &&
644 ((Previous.is(tok::identifier) && Previous.TokenText == "endl") ||
645 (Previous.Tok.isLiteral() && (Previous.TokenText.ends_with("\\n\"") ||
646 Previous.TokenText == "\'\\n\'")))) {
647 return true;
648 }
649
650 if (Previous.is(TT_BlockComment) && Previous.IsMultiline)
651 return true;
652
653 if (State.NoContinuation)
654 return true;
655
656 return false;
657}
658
660 bool DryRun,
661 unsigned ExtraSpaces) {
662 const FormatToken &Current = *State.NextToken;
663 assert(State.NextToken->Previous);
664 const FormatToken &Previous = *State.NextToken->Previous;
665
666 assert(!State.Stack.empty());
667 State.NoContinuation = false;
668
669 if (Current.is(TT_ImplicitStringLiteral) &&
670 (!Previous.Tok.getIdentifierInfo() ||
671 Previous.Tok.getIdentifierInfo()->getPPKeywordID() ==
672 tok::pp_not_keyword)) {
673 unsigned EndColumn =
674 SourceMgr.getSpellingColumnNumber(Current.WhitespaceRange.getEnd());
675 if (Current.LastNewlineOffset != 0) {
676 // If there is a newline within this token, the final column will solely
677 // determined by the current end column.
678 State.Column = EndColumn;
679 } else {
680 unsigned StartColumn =
681 SourceMgr.getSpellingColumnNumber(Current.WhitespaceRange.getBegin());
682 assert(EndColumn >= StartColumn);
683 State.Column += EndColumn - StartColumn;
684 }
685 moveStateToNextToken(State, DryRun, /*Newline=*/false);
686 return 0;
687 }
688
689 unsigned Penalty = 0;
690 if (Newline)
691 Penalty = addTokenOnNewLine(State, DryRun);
692 else
693 addTokenOnCurrentLine(State, DryRun, ExtraSpaces);
694
695 return moveStateToNextToken(State, DryRun, Newline) + Penalty;
696}
697
698void ContinuationIndenter::addTokenOnCurrentLine(LineState &State, bool DryRun,
699 unsigned ExtraSpaces) {
700 FormatToken &Current = *State.NextToken;
701 assert(State.NextToken->Previous);
702 const FormatToken &Previous = *State.NextToken->Previous;
703 auto &CurrentState = State.Stack.back();
704
705 bool DisallowLineBreaksOnThisLine =
707 Style.isCpp() && [&Current] {
708 // Deal with lambda arguments in C++. The aim here is to ensure that we
709 // don't over-indent lambda function bodies when lambdas are passed as
710 // arguments to function calls. We do this by ensuring that either all
711 // arguments (including any lambdas) go on the same line as the function
712 // call, or we break before the first argument.
713 const auto *Prev = Current.Previous;
714 if (!Prev)
715 return false;
716 // For example, `/*Newline=*/false`.
717 if (Prev->is(TT_BlockComment) && Current.SpacesRequiredBefore == 0)
718 return false;
719 const auto *PrevNonComment = Current.getPreviousNonComment();
720 if (!PrevNonComment || PrevNonComment->isNot(tok::l_paren))
721 return false;
722 if (Current.isOneOf(tok::comment, tok::l_paren, TT_LambdaLSquare))
723 return false;
724 auto BlockParameterCount = PrevNonComment->BlockParameterCount;
725 if (BlockParameterCount == 0)
726 return false;
727
728 // Multiple lambdas in the same function call.
729 if (BlockParameterCount > 1)
730 return true;
731
732 // A lambda followed by another arg.
733 if (!PrevNonComment->Role)
734 return false;
735 auto Comma = PrevNonComment->Role->lastComma();
736 if (!Comma)
737 return false;
738 auto Next = Comma->getNextNonComment();
739 return Next &&
740 !Next->isOneOf(TT_LambdaLSquare, tok::l_brace, tok::caret);
741 }();
742
743 if (DisallowLineBreaksOnThisLine)
744 State.NoLineBreak = true;
745
746 if (Current.is(tok::equal) &&
747 (State.Line->First->is(tok::kw_for) || Current.NestingLevel == 0) &&
748 CurrentState.VariablePos == 0 &&
749 (!Previous.Previous ||
750 Previous.Previous->isNot(TT_DesignatedInitializerPeriod))) {
751 CurrentState.VariablePos = State.Column;
752 // Move over * and & if they are bound to the variable name.
753 const FormatToken *Tok = &Previous;
754 while (Tok && CurrentState.VariablePos >= Tok->ColumnWidth) {
755 CurrentState.VariablePos -= Tok->ColumnWidth;
756 if (Tok->SpacesRequiredBefore != 0)
757 break;
758 Tok = Tok->Previous;
759 }
760 if (Previous.PartOfMultiVariableDeclStmt)
761 CurrentState.LastSpace = CurrentState.VariablePos;
762 }
763
764 unsigned Spaces = Current.SpacesRequiredBefore + ExtraSpaces;
765
766 // Indent preprocessor directives after the hash if required.
767 int PPColumnCorrection = 0;
769 Previous.is(tok::hash) && State.FirstIndent > 0 &&
770 &Previous == State.Line->First &&
771 (State.Line->Type == LT_PreprocessorDirective ||
772 State.Line->Type == LT_ImportStatement)) {
773 Spaces += State.FirstIndent;
774
775 // For preprocessor indent with tabs, State.Column will be 1 because of the
776 // hash. This causes second-level indents onward to have an extra space
777 // after the tabs. We avoid this misalignment by subtracting 1 from the
778 // column value passed to replaceWhitespace().
779 if (Style.UseTab != FormatStyle::UT_Never)
780 PPColumnCorrection = -1;
781 }
782
783 if (!DryRun) {
784 Whitespaces.replaceWhitespace(Current, /*Newlines=*/0, Spaces,
785 State.Column + Spaces + PPColumnCorrection,
786 /*IsAligned=*/false, State.Line->InMacroBody);
787 }
788
789 // If "BreakBeforeInheritanceComma" mode, don't break within the inheritance
790 // declaration unless there is multiple inheritance.
792 Current.is(TT_InheritanceColon)) {
793 CurrentState.NoLineBreak = true;
794 }
796 Previous.is(TT_InheritanceColon)) {
797 CurrentState.NoLineBreak = true;
798 }
799
800 if (Current.is(TT_SelectorName) && !CurrentState.ObjCSelectorNameFound) {
801 unsigned MinIndent = std::max(
802 State.FirstIndent + Style.ContinuationIndentWidth, CurrentState.Indent);
803 unsigned FirstColonPos = State.Column + Spaces + Current.ColumnWidth;
804 if (Current.LongestObjCSelectorName == 0)
805 CurrentState.AlignColons = false;
806 else if (MinIndent + Current.LongestObjCSelectorName > FirstColonPos)
807 CurrentState.ColonPos = MinIndent + Current.LongestObjCSelectorName;
808 else
809 CurrentState.ColonPos = FirstColonPos;
810 }
811
812 // In "AlwaysBreak" or "BlockIndent" mode, enforce wrapping directly after the
813 // parenthesis by disallowing any further line breaks if there is no line
814 // break after the opening parenthesis. Don't break if it doesn't conserve
815 // columns.
816 auto IsOpeningBracket = [&](const FormatToken &Tok) {
817 auto IsStartOfBracedList = [&]() {
818 return Tok.is(tok::l_brace) && Tok.isNot(BK_Block) &&
820 };
821 if (!Tok.isOneOf(tok::l_paren, TT_TemplateOpener, tok::l_square) &&
822 !IsStartOfBracedList()) {
823 return false;
824 }
825 if (!Tok.Previous)
826 return true;
827 if (Tok.Previous->isIf())
829 return !Tok.Previous->isOneOf(TT_CastRParen, tok::kw_for, tok::kw_while,
830 tok::kw_switch);
831 };
832 auto IsFunctionCallParen = [](const FormatToken &Tok) {
833 return Tok.is(tok::l_paren) && Tok.ParameterCount > 0 && Tok.Previous &&
834 Tok.Previous->is(tok::identifier);
835 };
836 const auto IsInTemplateString = [this](const FormatToken &Tok) {
837 if (!Style.isJavaScript())
838 return false;
839 for (const auto *Prev = &Tok; Prev; Prev = Prev->Previous) {
840 if (Prev->is(TT_TemplateString) && Prev->opensScope())
841 return true;
842 if (Prev->is(TT_TemplateString) && Prev->closesScope())
843 break;
844 }
845 return false;
846 };
847 // Identifies simple (no expression) one-argument function calls.
848 const auto IsSimpleFunction = [&](const FormatToken &Tok) {
849 if (!Tok.FakeLParens.empty() && Tok.FakeLParens.back() > prec::Unknown)
850 return false;
851 const auto *Previous = Tok.Previous;
852 if (!Previous || (!Previous->isOneOf(TT_FunctionDeclarationLParen,
853 TT_LambdaDefinitionLParen) &&
854 !IsFunctionCallParen(*Previous))) {
855 return true;
856 }
857 if (IsOpeningBracket(Tok) || IsInTemplateString(Tok))
858 return true;
859 const auto *Next = Tok.Next;
860 return !Next || Next->isMemberAccess() ||
861 Next->is(TT_FunctionDeclarationLParen) || IsFunctionCallParen(*Next);
862 };
865 IsOpeningBracket(Previous) && State.Column > getNewLineColumn(State) &&
866 // Don't do this for simple (no expressions) one-argument function calls
867 // as that feels like needlessly wasting whitespace, e.g.:
868 //
869 // caaaaaaaaaaaall(
870 // caaaaaaaaaaaall(
871 // caaaaaaaaaaaall(
872 // caaaaaaaaaaaaaaaaaaaaaaall(aaaaaaaaaaaaaa, aaaaaaaaa))));
873 !IsSimpleFunction(Current)) {
874 CurrentState.NoLineBreak = true;
875 }
876
877 if (Previous.is(TT_TemplateString) && Previous.opensScope())
878 CurrentState.NoLineBreak = true;
879
880 // Align following lines within parentheses / brackets if configured.
881 // Note: This doesn't apply to macro expansion lines, which are MACRO( , , )
882 // with args as children of the '(' and ',' tokens. It does not make sense to
883 // align the commas with the opening paren.
885 !CurrentState.IsCSharpGenericTypeConstraint && Previous.opensScope() &&
886 Previous.isNot(TT_ObjCMethodExpr) && Previous.isNot(TT_RequiresClause) &&
887 Previous.isNot(TT_TableGenDAGArgOpener) &&
888 Previous.isNot(TT_TableGenDAGArgOpenerToBreak) &&
889 !(Current.MacroParent && Previous.MacroParent) &&
890 (Current.isNot(TT_LineComment) ||
891 Previous.isOneOf(BK_BracedInit, TT_VerilogMultiLineListLParen)) &&
892 !IsInTemplateString(Current)) {
893 CurrentState.Indent = State.Column + Spaces;
894 CurrentState.IsAligned = true;
895 }
896 if (CurrentState.AvoidBinPacking && startsNextParameter(Current, Style))
897 CurrentState.NoLineBreak = true;
898 if (mustBreakBinaryOperation(Current, Style))
899 CurrentState.NoLineBreak = true;
900
901 if (startsSegmentOfBuilderTypeCall(Current) &&
902 State.Column > getNewLineColumn(State)) {
903 CurrentState.ContainsUnwrappedBuilder = true;
904 }
905
906 if (Current.is(TT_TrailingReturnArrow) &&
908 CurrentState.NoLineBreak = true;
909 }
910 if (Current.isMemberAccess() && Previous.is(tok::r_paren) &&
911 (Previous.MatchingParen &&
912 (Previous.TotalLength - Previous.MatchingParen->TotalLength > 10))) {
913 // If there is a function call with long parameters, break before trailing
914 // calls. This prevents things like:
915 // EXPECT_CALL(SomeLongParameter).Times(
916 // 2);
917 // We don't want to do this for short parameters as they can just be
918 // indexes.
919 CurrentState.NoLineBreak = true;
920 }
921
922 // Don't allow the RHS of an operator to be split over multiple lines unless
923 // there is a line-break right after the operator.
924 // Exclude relational operators, as there, it is always more desirable to
925 // have the LHS 'left' of the RHS.
926 const FormatToken *P = Current.getPreviousNonComment();
927 if (Current.isNot(tok::comment) && P &&
928 (P->isOneOf(TT_BinaryOperator, tok::comma) ||
929 (P->is(TT_ConditionalExpr) && P->is(tok::colon))) &&
930 !P->isOneOf(TT_OverloadedOperator, TT_CtorInitializerComma) &&
931 P->getPrecedence() != prec::Assignment &&
932 P->getPrecedence() != prec::Relational &&
933 P->getPrecedence() != prec::Spaceship) {
934 bool BreakBeforeOperator =
935 P->MustBreakBefore || P->is(tok::lessless) ||
936 (P->is(TT_BinaryOperator) &&
938 (P->is(TT_ConditionalExpr) && Style.BreakBeforeTernaryOperators);
939 // Don't do this if there are only two operands. In these cases, there is
940 // always a nice vertical separation between them and the extra line break
941 // does not help.
942 bool HasTwoOperands = P->OperatorIndex == 0 && !P->NextOperator &&
943 P->isNot(TT_ConditionalExpr);
944 if ((!BreakBeforeOperator &&
945 !(HasTwoOperands &&
947 (!CurrentState.LastOperatorWrapped && BreakBeforeOperator)) {
948 CurrentState.NoLineBreakInOperand = true;
949 }
950 }
951
952 State.Column += Spaces;
953 if (Current.isNot(tok::comment) && Previous.is(tok::l_paren) &&
954 Previous.Previous &&
955 (Previous.Previous->is(tok::kw_for) || Previous.Previous->isIf())) {
956 // Treat the condition inside an if as if it was a second function
957 // parameter, i.e. let nested calls have a continuation indent.
958 CurrentState.LastSpace = State.Column;
959 CurrentState.NestedBlockIndent = State.Column;
960 } else if (!Current.isOneOf(tok::comment, tok::caret) &&
961 ((Previous.is(tok::comma) &&
962 Previous.isNot(TT_OverloadedOperator)) ||
963 (Previous.is(tok::colon) && Previous.is(TT_ObjCMethodExpr)))) {
964 CurrentState.LastSpace = State.Column;
965 } else if (Previous.is(TT_CtorInitializerColon) &&
966 (!Current.isTrailingComment() || Current.NewlinesBefore > 0) &&
969 CurrentState.Indent = State.Column;
970 CurrentState.LastSpace = State.Column;
971 } else if (Previous.isOneOf(TT_ConditionalExpr, TT_CtorInitializerColon)) {
972 CurrentState.LastSpace = State.Column;
973 } else if (Previous.is(TT_BinaryOperator) &&
974 ((Previous.getPrecedence() != prec::Assignment &&
975 (Previous.isNot(tok::lessless) || Previous.OperatorIndex != 0 ||
976 Previous.NextOperator)) ||
977 Current.StartsBinaryExpression)) {
978 // Indent relative to the RHS of the expression unless this is a simple
979 // assignment without binary expression on the RHS.
981 CurrentState.LastSpace = State.Column;
982 } else if (Previous.is(TT_InheritanceColon)) {
983 CurrentState.Indent = State.Column;
984 CurrentState.LastSpace = State.Column;
985 } else if (Current.is(TT_CSharpGenericTypeConstraintColon)) {
986 CurrentState.ColonPos = State.Column;
987 } else if (Previous.opensScope()) {
988 // If a function has a trailing call, indent all parameters from the
989 // opening parenthesis. This avoids confusing indents like:
990 // OuterFunction(InnerFunctionCall( // break
991 // ParameterToInnerFunction)) // break
992 // .SecondInnerFunctionCall();
993 if (Previous.MatchingParen) {
994 const FormatToken *Next = Previous.MatchingParen->getNextNonComment();
995 if (Next && Next->isMemberAccess() && State.Stack.size() > 1 &&
996 State.Stack[State.Stack.size() - 2].CallContinuation == 0) {
997 CurrentState.LastSpace = State.Column;
998 }
999 }
1000 }
1001}
1002
1003unsigned ContinuationIndenter::addTokenOnNewLine(LineState &State,
1004 bool DryRun) {
1005 FormatToken &Current = *State.NextToken;
1006 assert(State.NextToken->Previous);
1007 const FormatToken &Previous = *State.NextToken->Previous;
1008 auto &CurrentState = State.Stack.back();
1009
1010 // Extra penalty that needs to be added because of the way certain line
1011 // breaks are chosen.
1012 unsigned Penalty = 0;
1013
1014 const FormatToken *PreviousNonComment = Current.getPreviousNonComment();
1015 const FormatToken *NextNonComment = Previous.getNextNonComment();
1016 if (!NextNonComment)
1017 NextNonComment = &Current;
1018 // The first line break on any NestingLevel causes an extra penalty in order
1019 // prefer similar line breaks.
1020 if (!CurrentState.ContainsLineBreak)
1021 Penalty += 15;
1022 CurrentState.ContainsLineBreak = true;
1023
1024 Penalty += State.NextToken->SplitPenalty;
1025
1026 // Breaking before the first "<<" is generally not desirable if the LHS is
1027 // short. Also always add the penalty if the LHS is split over multiple lines
1028 // to avoid unnecessary line breaks that just work around this penalty.
1029 if (NextNonComment->is(tok::lessless) && CurrentState.FirstLessLess == 0 &&
1030 (State.Column <= Style.ColumnLimit / 3 ||
1031 CurrentState.BreakBeforeParameter)) {
1032 Penalty += Style.PenaltyBreakFirstLessLess;
1033 }
1034
1035 State.Column = getNewLineColumn(State);
1036
1037 // Add Penalty proportional to amount of whitespace away from FirstColumn
1038 // This tends to penalize several lines that are far-right indented,
1039 // and prefers a line-break prior to such a block, e.g:
1040 //
1041 // Constructor() :
1042 // member(value), looooooooooooooooong_member(
1043 // looooooooooong_call(param_1, param_2, param_3))
1044 // would then become
1045 // Constructor() :
1046 // member(value),
1047 // looooooooooooooooong_member(
1048 // looooooooooong_call(param_1, param_2, param_3))
1049 if (State.Column > State.FirstIndent) {
1050 Penalty +=
1051 Style.PenaltyIndentedWhitespace * (State.Column - State.FirstIndent);
1052 }
1053
1054 // Indent nested blocks relative to this column, unless in a very specific
1055 // JavaScript special case where:
1056 //
1057 // var loooooong_name =
1058 // function() {
1059 // // code
1060 // }
1061 //
1062 // is common and should be formatted like a free-standing function. The same
1063 // goes for wrapping before the lambda return type arrow.
1064 if (Current.isNot(TT_TrailingReturnArrow) &&
1065 (!Style.isJavaScript() || Current.NestingLevel != 0 ||
1066 !PreviousNonComment || PreviousNonComment->isNot(tok::equal) ||
1067 !Current.isOneOf(Keywords.kw_async, Keywords.kw_function))) {
1068 CurrentState.NestedBlockIndent = State.Column;
1069 }
1070
1071 if (NextNonComment->isMemberAccess()) {
1072 if (CurrentState.CallContinuation == 0)
1073 CurrentState.CallContinuation = State.Column;
1074 } else if (NextNonComment->is(TT_SelectorName)) {
1075 if (!CurrentState.ObjCSelectorNameFound) {
1076 if (NextNonComment->LongestObjCSelectorName == 0) {
1077 CurrentState.AlignColons = false;
1078 } else {
1079 CurrentState.ColonPos =
1080 (shouldIndentWrappedSelectorName(Style, State.Line->Type)
1081 ? std::max(CurrentState.Indent,
1082 State.FirstIndent + Style.ContinuationIndentWidth)
1083 : CurrentState.Indent) +
1084 std::max(NextNonComment->LongestObjCSelectorName,
1085 NextNonComment->ColumnWidth);
1086 }
1087 } else if (CurrentState.AlignColons &&
1088 CurrentState.ColonPos <= NextNonComment->ColumnWidth) {
1089 CurrentState.ColonPos = State.Column + NextNonComment->ColumnWidth;
1090 }
1091 } else if (PreviousNonComment && PreviousNonComment->is(tok::colon) &&
1092 PreviousNonComment->isOneOf(TT_ObjCMethodExpr, TT_DictLiteral)) {
1093 // FIXME: This is hacky, find a better way. The problem is that in an ObjC
1094 // method expression, the block should be aligned to the line starting it,
1095 // e.g.:
1096 // [aaaaaaaaaaaaaaa aaaaaaaaa: \\ break for some reason
1097 // ^(int *i) {
1098 // // ...
1099 // }];
1100 // Thus, we set LastSpace of the next higher NestingLevel, to which we move
1101 // when we consume all of the "}"'s FakeRParens at the "{".
1102 if (State.Stack.size() > 1) {
1103 State.Stack[State.Stack.size() - 2].LastSpace =
1104 std::max(CurrentState.LastSpace, CurrentState.Indent) +
1106 }
1107 }
1108
1109 if ((PreviousNonComment &&
1110 PreviousNonComment->isOneOf(tok::comma, tok::semi) &&
1111 !CurrentState.AvoidBinPacking) ||
1112 Previous.is(TT_BinaryOperator)) {
1113 CurrentState.BreakBeforeParameter = false;
1114 }
1115 if (PreviousNonComment &&
1116 (PreviousNonComment->isOneOf(TT_TemplateCloser, TT_JavaAnnotation) ||
1117 PreviousNonComment->ClosesRequiresClause) &&
1118 Current.NestingLevel == 0) {
1119 CurrentState.BreakBeforeParameter = false;
1120 }
1121 if (NextNonComment->is(tok::question) ||
1122 (PreviousNonComment && PreviousNonComment->is(tok::question))) {
1123 CurrentState.BreakBeforeParameter = true;
1124 }
1125 if (Current.is(TT_BinaryOperator) && Current.CanBreakBefore)
1126 CurrentState.BreakBeforeParameter = false;
1127
1128 if (!DryRun) {
1129 unsigned MaxEmptyLinesToKeep = Style.MaxEmptyLinesToKeep + 1;
1130 if (Current.is(tok::r_brace) && Current.MatchingParen &&
1131 // Only strip trailing empty lines for l_braces that have children, i.e.
1132 // for function expressions (lambdas, arrows, etc).
1133 !Current.MatchingParen->Children.empty()) {
1134 // lambdas and arrow functions are expressions, thus their r_brace is not
1135 // on its own line, and thus not covered by UnwrappedLineFormatter's logic
1136 // about removing empty lines on closing blocks. Special case them here.
1137 MaxEmptyLinesToKeep = 1;
1138 }
1139 unsigned Newlines =
1140 std::max(1u, std::min(Current.NewlinesBefore, MaxEmptyLinesToKeep));
1141 bool ContinuePPDirective =
1142 State.Line->InPPDirective && State.Line->Type != LT_ImportStatement;
1143 Whitespaces.replaceWhitespace(Current, Newlines, State.Column, State.Column,
1144 CurrentState.IsAligned, ContinuePPDirective);
1145 }
1146
1147 if (!Current.isTrailingComment())
1148 CurrentState.LastSpace = State.Column;
1149 if (Current.is(tok::lessless)) {
1150 // If we are breaking before a "<<", we always want to indent relative to
1151 // RHS. This is necessary only for "<<", as we special-case it and don't
1152 // always indent relative to the RHS.
1153 CurrentState.LastSpace += 3; // 3 -> width of "<< ".
1154 }
1155
1156 State.StartOfLineLevel = Current.NestingLevel;
1157 State.LowestLevelOnLine = Current.NestingLevel;
1158
1159 // Any break on this level means that the parent level has been broken
1160 // and we need to avoid bin packing there.
1161 bool NestedBlockSpecialCase =
1162 (!Style.isCpp() && Current.is(tok::r_brace) && State.Stack.size() > 1 &&
1163 State.Stack[State.Stack.size() - 2].NestedBlockInlined) ||
1164 (Style.Language == FormatStyle::LK_ObjC && Current.is(tok::r_brace) &&
1165 State.Stack.size() > 1 && !Style.ObjCBreakBeforeNestedBlockParam);
1166 // Do not force parameter break for statements with requires expressions.
1167 NestedBlockSpecialCase =
1168 NestedBlockSpecialCase ||
1169 (Current.MatchingParen &&
1170 Current.MatchingParen->is(TT_RequiresExpressionLBrace));
1171 if (!NestedBlockSpecialCase) {
1172 auto ParentLevelIt = std::next(State.Stack.rbegin());
1174 Current.MatchingParen && Current.MatchingParen->is(TT_LambdaLBrace)) {
1175 // If the first character on the new line is a lambda's closing brace, the
1176 // stack still contains that lambda's parenthesis. As such, we need to
1177 // recurse further down the stack than usual to find the parenthesis level
1178 // containing the lambda, which is where we want to set
1179 // BreakBeforeParameter.
1180 //
1181 // We specifically special case "OuterScope"-formatted lambdas here
1182 // because, when using that setting, breaking before the parameter
1183 // directly following the lambda is particularly unsightly. However, when
1184 // "OuterScope" is not set, the logic to find the parent parenthesis level
1185 // still appears to be sometimes incorrect. It has not been fixed yet
1186 // because it would lead to significant changes in existing behaviour.
1187 //
1188 // TODO: fix the non-"OuterScope" case too.
1189 auto FindCurrentLevel = [&](const auto &It) {
1190 return std::find_if(It, State.Stack.rend(), [](const auto &PState) {
1191 return PState.Tok != nullptr; // Ignore fake parens.
1192 });
1193 };
1194 auto MaybeIncrement = [&](const auto &It) {
1195 return It != State.Stack.rend() ? std::next(It) : It;
1196 };
1197 auto LambdaLevelIt = FindCurrentLevel(State.Stack.rbegin());
1198 auto LevelContainingLambdaIt =
1199 FindCurrentLevel(MaybeIncrement(LambdaLevelIt));
1200 ParentLevelIt = MaybeIncrement(LevelContainingLambdaIt);
1201 }
1202 for (auto I = ParentLevelIt, E = State.Stack.rend(); I != E; ++I)
1203 I->BreakBeforeParameter = true;
1204 }
1205
1206 if (PreviousNonComment &&
1207 !PreviousNonComment->isOneOf(tok::comma, tok::colon, tok::semi) &&
1208 ((PreviousNonComment->isNot(TT_TemplateCloser) &&
1209 !PreviousNonComment->ClosesRequiresClause) ||
1210 Current.NestingLevel != 0) &&
1211 !PreviousNonComment->isOneOf(
1212 TT_BinaryOperator, TT_FunctionAnnotationRParen, TT_JavaAnnotation,
1213 TT_LeadingJavaAnnotation) &&
1214 Current.isNot(TT_BinaryOperator) && !PreviousNonComment->opensScope() &&
1215 // We don't want to enforce line breaks for subsequent arguments just
1216 // because we have been forced to break before a lambda body.
1218 Current.isNot(TT_LambdaLBrace))) {
1219 CurrentState.BreakBeforeParameter = true;
1220 }
1221
1222 // If we break after { or the [ of an array initializer, we should also break
1223 // before the corresponding } or ].
1224 if (PreviousNonComment &&
1225 (PreviousNonComment->isOneOf(tok::l_brace, TT_ArrayInitializerLSquare) ||
1226 opensProtoMessageField(*PreviousNonComment, Style))) {
1227 CurrentState.BreakBeforeClosingBrace = true;
1228 }
1229
1230 if (PreviousNonComment && PreviousNonComment->is(tok::l_paren)) {
1231 CurrentState.BreakBeforeClosingParen =
1233 }
1234
1235 if (CurrentState.AvoidBinPacking) {
1236 // If we are breaking after '(', '{', '<', or this is the break after a ':'
1237 // to start a member initializer list in a constructor, this should not
1238 // be considered bin packing unless the relevant AllowAll option is false or
1239 // this is a dict/object literal.
1240 bool PreviousIsBreakingCtorInitializerColon =
1241 PreviousNonComment && PreviousNonComment->is(TT_CtorInitializerColon) &&
1243 bool AllowAllConstructorInitializersOnNextLine =
1246 if (!(Previous.isOneOf(tok::l_paren, tok::l_brace, TT_BinaryOperator) ||
1247 PreviousIsBreakingCtorInitializerColon) ||
1249 State.Line->MustBeDeclaration) ||
1251 !State.Line->MustBeDeclaration) ||
1252 (!AllowAllConstructorInitializersOnNextLine &&
1253 PreviousIsBreakingCtorInitializerColon) ||
1254 Previous.is(TT_DictLiteral)) {
1255 CurrentState.BreakBeforeParameter = true;
1256 }
1257
1258 // If we are breaking after a ':' to start a member initializer list,
1259 // and we allow all arguments on the next line, we should not break
1260 // before the next parameter.
1261 if (PreviousIsBreakingCtorInitializerColon &&
1262 AllowAllConstructorInitializersOnNextLine) {
1263 CurrentState.BreakBeforeParameter = false;
1264 }
1265 }
1266
1267 if (mustBreakBinaryOperation(Current, Style))
1268 CurrentState.BreakBeforeParameter = true;
1269
1270 return Penalty;
1271}
1272
1273unsigned ContinuationIndenter::getNewLineColumn(const LineState &State) {
1274 if (!State.NextToken || !State.NextToken->Previous)
1275 return 0;
1276
1277 FormatToken &Current = *State.NextToken;
1278 const auto &CurrentState = State.Stack.back();
1279
1280 if (CurrentState.IsCSharpGenericTypeConstraint &&
1281 Current.isNot(TT_CSharpGenericTypeConstraint)) {
1282 return CurrentState.ColonPos + 2;
1283 }
1284
1285 const FormatToken &Previous = *Current.Previous;
1286 // If we are continuing an expression, we want to use the continuation indent.
1287 unsigned ContinuationIndent =
1288 std::max(CurrentState.LastSpace, CurrentState.Indent) +
1290 const FormatToken *PreviousNonComment = Current.getPreviousNonComment();
1291 const FormatToken *NextNonComment = Previous.getNextNonComment();
1292 if (!NextNonComment)
1293 NextNonComment = &Current;
1294
1295 // Java specific bits.
1296 if (Style.Language == FormatStyle::LK_Java &&
1297 Current.isOneOf(Keywords.kw_implements, Keywords.kw_extends)) {
1298 return std::max(CurrentState.LastSpace,
1299 CurrentState.Indent + Style.ContinuationIndentWidth);
1300 }
1301
1302 // Indentation of the statement following a Verilog case label is taken care
1303 // of in moveStateToNextToken.
1304 if (Style.isVerilog() && PreviousNonComment &&
1305 Keywords.isVerilogEndOfLabel(*PreviousNonComment)) {
1306 return State.FirstIndent;
1307 }
1308
1310 State.Line->First->is(tok::kw_enum)) {
1311 return (Style.IndentWidth * State.Line->First->IndentLevel) +
1312 Style.IndentWidth;
1313 }
1314
1315 if ((NextNonComment->is(tok::l_brace) && NextNonComment->is(BK_Block)) ||
1316 (Style.isVerilog() && Keywords.isVerilogBegin(*NextNonComment))) {
1317 if (Current.NestingLevel == 0 ||
1319 State.NextToken->is(TT_LambdaLBrace))) {
1320 return State.FirstIndent;
1321 }
1322 return CurrentState.Indent;
1323 }
1324 if (Current.is(TT_TrailingReturnArrow) &&
1325 Previous.isOneOf(tok::kw_noexcept, tok::kw_mutable, tok::kw_constexpr,
1326 tok::kw_consteval, tok::kw_static, TT_AttributeSquare)) {
1327 return ContinuationIndent;
1328 }
1329 if ((Current.isOneOf(tok::r_brace, tok::r_square) ||
1330 (Current.is(tok::greater) && (Style.isProto() || Style.isTableGen()))) &&
1331 State.Stack.size() > 1) {
1332 if (Current.closesBlockOrBlockTypeList(Style))
1333 return State.Stack[State.Stack.size() - 2].NestedBlockIndent;
1334 if (Current.MatchingParen && Current.MatchingParen->is(BK_BracedInit))
1335 return State.Stack[State.Stack.size() - 2].LastSpace;
1336 return State.FirstIndent;
1337 }
1338 // Indent a closing parenthesis at the previous level if followed by a semi,
1339 // const, or opening brace. This allows indentations such as:
1340 // foo(
1341 // a,
1342 // );
1343 // int Foo::getter(
1344 // //
1345 // ) const {
1346 // return foo;
1347 // }
1348 // function foo(
1349 // a,
1350 // ) {
1351 // code(); //
1352 // }
1353 if (Current.is(tok::r_paren) && State.Stack.size() > 1 &&
1354 (!Current.Next ||
1355 Current.Next->isOneOf(tok::semi, tok::kw_const, tok::l_brace))) {
1356 return State.Stack[State.Stack.size() - 2].LastSpace;
1357 }
1358 // When DAGArg closer exists top of line, it should be aligned in the similar
1359 // way as function call above.
1360 if (Style.isTableGen() && Current.is(TT_TableGenDAGArgCloser) &&
1361 State.Stack.size() > 1) {
1362 return State.Stack[State.Stack.size() - 2].LastSpace;
1363 }
1365 (Current.is(tok::r_paren) ||
1366 (Current.is(tok::r_brace) && Current.MatchingParen &&
1367 Current.MatchingParen->is(BK_BracedInit))) &&
1368 State.Stack.size() > 1) {
1369 return State.Stack[State.Stack.size() - 2].LastSpace;
1370 }
1371 if (NextNonComment->is(TT_TemplateString) && NextNonComment->closesScope())
1372 return State.Stack[State.Stack.size() - 2].LastSpace;
1373 // Field labels in a nested type should be aligned to the brace. For example
1374 // in ProtoBuf:
1375 // optional int32 b = 2 [(foo_options) = {aaaaaaaaaaaaaaaaaaa: 123,
1376 // bbbbbbbbbbbbbbbbbbbbbbbb:"baz"}];
1377 // For Verilog, a quote following a brace is treated as an identifier. And
1378 // Both braces and colons get annotated as TT_DictLiteral. So we have to
1379 // check.
1380 if (Current.is(tok::identifier) && Current.Next &&
1381 (!Style.isVerilog() || Current.Next->is(tok::colon)) &&
1382 (Current.Next->is(TT_DictLiteral) ||
1383 (Style.isProto() && Current.Next->isOneOf(tok::less, tok::l_brace)))) {
1384 return CurrentState.Indent;
1385 }
1386 if (NextNonComment->is(TT_ObjCStringLiteral) &&
1387 State.StartOfStringLiteral != 0) {
1388 return State.StartOfStringLiteral - 1;
1389 }
1390 if (NextNonComment->isStringLiteral() && State.StartOfStringLiteral != 0)
1391 return State.StartOfStringLiteral;
1392 if (NextNonComment->is(tok::lessless) && CurrentState.FirstLessLess != 0)
1393 return CurrentState.FirstLessLess;
1394 if (NextNonComment->isMemberAccess()) {
1395 if (CurrentState.CallContinuation == 0)
1396 return ContinuationIndent;
1397 return CurrentState.CallContinuation;
1398 }
1399 if (CurrentState.QuestionColumn != 0 &&
1400 ((NextNonComment->is(tok::colon) &&
1401 NextNonComment->is(TT_ConditionalExpr)) ||
1402 Previous.is(TT_ConditionalExpr))) {
1403 if (((NextNonComment->is(tok::colon) && NextNonComment->Next &&
1404 !NextNonComment->Next->FakeLParens.empty() &&
1405 NextNonComment->Next->FakeLParens.back() == prec::Conditional) ||
1406 (Previous.is(tok::colon) && !Current.FakeLParens.empty() &&
1407 Current.FakeLParens.back() == prec::Conditional)) &&
1408 !CurrentState.IsWrappedConditional) {
1409 // NOTE: we may tweak this slightly:
1410 // * not remove the 'lead' ContinuationIndentWidth
1411 // * always un-indent by the operator when
1412 // BreakBeforeTernaryOperators=true
1413 unsigned Indent = CurrentState.Indent;
1415 Indent -= Style.ContinuationIndentWidth;
1416 if (Style.BreakBeforeTernaryOperators && CurrentState.UnindentOperator)
1417 Indent -= 2;
1418 return Indent;
1419 }
1420 return CurrentState.QuestionColumn;
1421 }
1422 if (Previous.is(tok::comma) && CurrentState.VariablePos != 0)
1423 return CurrentState.VariablePos;
1424 if (Current.is(TT_RequiresClause)) {
1425 if (Style.IndentRequiresClause)
1426 return CurrentState.Indent + Style.IndentWidth;
1427 switch (Style.RequiresClausePosition) {
1430 return CurrentState.Indent;
1431 default:
1432 break;
1433 }
1434 }
1435 if (NextNonComment->isOneOf(TT_CtorInitializerColon, TT_InheritanceColon,
1436 TT_InheritanceComma)) {
1437 return State.FirstIndent + Style.ConstructorInitializerIndentWidth;
1438 }
1439 if ((PreviousNonComment &&
1440 (PreviousNonComment->ClosesTemplateDeclaration ||
1441 PreviousNonComment->ClosesRequiresClause ||
1442 (PreviousNonComment->is(TT_AttributeMacro) &&
1443 Current.isNot(tok::l_paren)) ||
1444 PreviousNonComment->isOneOf(
1445 TT_AttributeRParen, TT_AttributeSquare, TT_FunctionAnnotationRParen,
1446 TT_JavaAnnotation, TT_LeadingJavaAnnotation))) ||
1448 NextNonComment->isOneOf(tok::kw_operator, TT_FunctionDeclarationName))) {
1449 return std::max(CurrentState.LastSpace, CurrentState.Indent);
1450 }
1451 if (NextNonComment->is(TT_SelectorName)) {
1452 if (!CurrentState.ObjCSelectorNameFound) {
1453 unsigned MinIndent = CurrentState.Indent;
1454 if (shouldIndentWrappedSelectorName(Style, State.Line->Type)) {
1455 MinIndent = std::max(MinIndent,
1456 State.FirstIndent + Style.ContinuationIndentWidth);
1457 }
1458 // If LongestObjCSelectorName is 0, we are indenting the first
1459 // part of an ObjC selector (or a selector component which is
1460 // not colon-aligned due to block formatting).
1461 //
1462 // Otherwise, we are indenting a subsequent part of an ObjC
1463 // selector which should be colon-aligned to the longest
1464 // component of the ObjC selector.
1465 //
1466 // In either case, we want to respect Style.IndentWrappedFunctionNames.
1467 return MinIndent +
1468 std::max(NextNonComment->LongestObjCSelectorName,
1469 NextNonComment->ColumnWidth) -
1470 NextNonComment->ColumnWidth;
1471 }
1472 if (!CurrentState.AlignColons)
1473 return CurrentState.Indent;
1474 if (CurrentState.ColonPos > NextNonComment->ColumnWidth)
1475 return CurrentState.ColonPos - NextNonComment->ColumnWidth;
1476 return CurrentState.Indent;
1477 }
1478 if (NextNonComment->is(tok::colon) && NextNonComment->is(TT_ObjCMethodExpr))
1479 return CurrentState.ColonPos;
1480 if (NextNonComment->is(TT_ArraySubscriptLSquare)) {
1481 if (CurrentState.StartOfArraySubscripts != 0) {
1482 return CurrentState.StartOfArraySubscripts;
1483 } else if (Style.isCSharp()) { // C# allows `["key"] = value` inside object
1484 // initializers.
1485 return CurrentState.Indent;
1486 }
1487 return ContinuationIndent;
1488 }
1489
1490 // OpenMP clauses want to get additional indentation when they are pushed onto
1491 // the next line.
1492 if (State.Line->InPragmaDirective) {
1493 FormatToken *PragmaType = State.Line->First->Next->Next;
1494 if (PragmaType && PragmaType->TokenText == "omp")
1495 return CurrentState.Indent + Style.ContinuationIndentWidth;
1496 }
1497
1498 // This ensure that we correctly format ObjC methods calls without inputs,
1499 // i.e. where the last element isn't selector like: [callee method];
1500 if (NextNonComment->is(tok::identifier) && NextNonComment->FakeRParens == 0 &&
1501 NextNonComment->Next && NextNonComment->Next->is(TT_ObjCMethodExpr)) {
1502 return CurrentState.Indent;
1503 }
1504
1505 if (NextNonComment->isOneOf(TT_StartOfName, TT_PointerOrReference) ||
1506 Previous.isOneOf(tok::coloncolon, tok::equal, TT_JsTypeColon)) {
1507 return ContinuationIndent;
1508 }
1509 if (PreviousNonComment && PreviousNonComment->is(tok::colon) &&
1510 PreviousNonComment->isOneOf(TT_ObjCMethodExpr, TT_DictLiteral)) {
1511 return ContinuationIndent;
1512 }
1513 if (NextNonComment->is(TT_CtorInitializerComma))
1514 return CurrentState.Indent;
1515 if (PreviousNonComment && PreviousNonComment->is(TT_CtorInitializerColon) &&
1517 return CurrentState.Indent;
1518 }
1519 if (PreviousNonComment && PreviousNonComment->is(TT_InheritanceColon) &&
1521 return CurrentState.Indent;
1522 }
1523 if (Previous.is(tok::r_paren) &&
1524 Previous.isNot(TT_TableGenDAGArgOperatorToBreak) &&
1525 !Current.isBinaryOperator() &&
1526 !Current.isOneOf(tok::colon, tok::comment)) {
1527 return ContinuationIndent;
1528 }
1529 if (Current.is(TT_ProtoExtensionLSquare))
1530 return CurrentState.Indent;
1531 if (Current.isBinaryOperator() && CurrentState.UnindentOperator) {
1532 return CurrentState.Indent - Current.Tok.getLength() -
1533 Current.SpacesRequiredBefore;
1534 }
1535 if (Current.is(tok::comment) && NextNonComment->isBinaryOperator() &&
1536 CurrentState.UnindentOperator) {
1537 return CurrentState.Indent - NextNonComment->Tok.getLength() -
1538 NextNonComment->SpacesRequiredBefore;
1539 }
1540 if (CurrentState.Indent == State.FirstIndent && PreviousNonComment &&
1541 !PreviousNonComment->isOneOf(tok::r_brace, TT_CtorInitializerComma)) {
1542 // Ensure that we fall back to the continuation indent width instead of
1543 // just flushing continuations left.
1544 return CurrentState.Indent + Style.ContinuationIndentWidth;
1545 }
1546 return CurrentState.Indent;
1547}
1548
1550 const FormatToken &Current,
1551 const FormatStyle &Style) {
1552 if (Previous->isNot(tok::l_paren))
1553 return true;
1554 if (Previous->ParameterCount > 1)
1555 return true;
1556
1557 // Also a nested block if contains a lambda inside function with 1 parameter.
1558 return Style.BraceWrapping.BeforeLambdaBody && Current.is(TT_LambdaLSquare);
1559}
1560
1561unsigned ContinuationIndenter::moveStateToNextToken(LineState &State,
1562 bool DryRun, bool Newline) {
1563 assert(State.Stack.size());
1564 const FormatToken &Current = *State.NextToken;
1565 auto &CurrentState = State.Stack.back();
1566
1567 if (Current.is(TT_CSharpGenericTypeConstraint))
1568 CurrentState.IsCSharpGenericTypeConstraint = true;
1569 if (Current.isOneOf(tok::comma, TT_BinaryOperator))
1570 CurrentState.NoLineBreakInOperand = false;
1571 if (Current.isOneOf(TT_InheritanceColon, TT_CSharpGenericTypeConstraintColon))
1572 CurrentState.AvoidBinPacking = true;
1573 if (Current.is(tok::lessless) && Current.isNot(TT_OverloadedOperator)) {
1574 if (CurrentState.FirstLessLess == 0)
1575 CurrentState.FirstLessLess = State.Column;
1576 else
1577 CurrentState.LastOperatorWrapped = Newline;
1578 }
1579 if (Current.is(TT_BinaryOperator) && Current.isNot(tok::lessless))
1580 CurrentState.LastOperatorWrapped = Newline;
1581 if (Current.is(TT_ConditionalExpr) && Current.Previous &&
1582 Current.Previous->isNot(TT_ConditionalExpr)) {
1583 CurrentState.LastOperatorWrapped = Newline;
1584 }
1585 if (Current.is(TT_ArraySubscriptLSquare) &&
1586 CurrentState.StartOfArraySubscripts == 0) {
1587 CurrentState.StartOfArraySubscripts = State.Column;
1588 }
1589
1590 auto IsWrappedConditional = [](const FormatToken &Tok) {
1591 if (!(Tok.is(TT_ConditionalExpr) && Tok.is(tok::question)))
1592 return false;
1593 if (Tok.MustBreakBefore)
1594 return true;
1595
1596 const FormatToken *Next = Tok.getNextNonComment();
1597 return Next && Next->MustBreakBefore;
1598 };
1599 if (IsWrappedConditional(Current))
1600 CurrentState.IsWrappedConditional = true;
1601 if (Style.BreakBeforeTernaryOperators && Current.is(tok::question))
1602 CurrentState.QuestionColumn = State.Column;
1603 if (!Style.BreakBeforeTernaryOperators && Current.isNot(tok::colon)) {
1604 const FormatToken *Previous = Current.Previous;
1605 while (Previous && Previous->isTrailingComment())
1606 Previous = Previous->Previous;
1607 if (Previous && Previous->is(tok::question))
1608 CurrentState.QuestionColumn = State.Column;
1609 }
1610 if (!Current.opensScope() && !Current.closesScope() &&
1611 Current.isNot(TT_PointerOrReference)) {
1612 State.LowestLevelOnLine =
1613 std::min(State.LowestLevelOnLine, Current.NestingLevel);
1614 }
1615 if (Current.isMemberAccess())
1616 CurrentState.StartOfFunctionCall = !Current.NextOperator ? 0 : State.Column;
1617 if (Current.is(TT_SelectorName))
1618 CurrentState.ObjCSelectorNameFound = true;
1619 if (Current.is(TT_CtorInitializerColon) &&
1621 // Indent 2 from the column, so:
1622 // SomeClass::SomeClass()
1623 // : First(...), ...
1624 // Next(...)
1625 // ^ line up here.
1626 CurrentState.Indent = State.Column + (Style.BreakConstructorInitializers ==
1628 ? 0
1629 : 2);
1630 CurrentState.NestedBlockIndent = CurrentState.Indent;
1632 CurrentState.AvoidBinPacking = true;
1633 CurrentState.BreakBeforeParameter =
1634 Style.ColumnLimit > 0 &&
1637 } else {
1638 CurrentState.BreakBeforeParameter = false;
1639 }
1640 }
1641 if (Current.is(TT_CtorInitializerColon) &&
1643 CurrentState.Indent =
1644 State.FirstIndent + Style.ConstructorInitializerIndentWidth;
1645 CurrentState.NestedBlockIndent = CurrentState.Indent;
1647 CurrentState.AvoidBinPacking = true;
1648 else
1649 CurrentState.BreakBeforeParameter = false;
1650 }
1651 if (Current.is(TT_InheritanceColon)) {
1652 CurrentState.Indent =
1653 State.FirstIndent + Style.ConstructorInitializerIndentWidth;
1654 }
1655 if (Current.isOneOf(TT_BinaryOperator, TT_ConditionalExpr) && Newline)
1656 CurrentState.NestedBlockIndent = State.Column + Current.ColumnWidth + 1;
1657 if (Current.isOneOf(TT_LambdaLSquare, TT_TrailingReturnArrow))
1658 CurrentState.LastSpace = State.Column;
1659 if (Current.is(TT_RequiresExpression) &&
1661 CurrentState.NestedBlockIndent = State.Column;
1662 }
1663
1664 // Insert scopes created by fake parenthesis.
1665 const FormatToken *Previous = Current.getPreviousNonComment();
1666
1667 // Add special behavior to support a format commonly used for JavaScript
1668 // closures:
1669 // SomeFunction(function() {
1670 // foo();
1671 // bar();
1672 // }, a, b, c);
1673 if (Current.isNot(tok::comment) && !Current.ClosesRequiresClause &&
1674 Previous && Previous->isOneOf(tok::l_brace, TT_ArrayInitializerLSquare) &&
1675 Previous->isNot(TT_DictLiteral) && State.Stack.size() > 1 &&
1676 !CurrentState.HasMultipleNestedBlocks) {
1677 if (State.Stack[State.Stack.size() - 2].NestedBlockInlined && Newline)
1678 for (ParenState &PState : llvm::drop_end(State.Stack))
1679 PState.NoLineBreak = true;
1680 State.Stack[State.Stack.size() - 2].NestedBlockInlined = false;
1681 }
1682 if (Previous && (Previous->isOneOf(TT_BinaryOperator, TT_ConditionalExpr) ||
1683 (Previous->isOneOf(tok::l_paren, tok::comma, tok::colon) &&
1684 !Previous->isOneOf(TT_DictLiteral, TT_ObjCMethodExpr)))) {
1685 CurrentState.NestedBlockInlined =
1686 !Newline && hasNestedBlockInlined(Previous, Current, Style);
1687 }
1688
1689 moveStatePastFakeLParens(State, Newline);
1690 moveStatePastScopeCloser(State);
1691 // Do not use CurrentState here, since the two functions before may change the
1692 // Stack.
1693 bool AllowBreak = !State.Stack.back().NoLineBreak &&
1694 !State.Stack.back().NoLineBreakInOperand;
1695 moveStatePastScopeOpener(State, Newline);
1696 moveStatePastFakeRParens(State);
1697
1698 if (Current.is(TT_ObjCStringLiteral) && State.StartOfStringLiteral == 0)
1699 State.StartOfStringLiteral = State.Column + 1;
1700 if (Current.is(TT_CSharpStringLiteral) && State.StartOfStringLiteral == 0) {
1701 State.StartOfStringLiteral = State.Column + 1;
1702 } else if (Current.is(TT_TableGenMultiLineString) &&
1703 State.StartOfStringLiteral == 0) {
1704 State.StartOfStringLiteral = State.Column + 1;
1705 } else if (Current.isStringLiteral() && State.StartOfStringLiteral == 0) {
1706 State.StartOfStringLiteral = State.Column;
1707 } else if (!Current.isOneOf(tok::comment, tok::identifier, tok::hash) &&
1708 !Current.isStringLiteral()) {
1709 State.StartOfStringLiteral = 0;
1710 }
1711
1712 State.Column += Current.ColumnWidth;
1713 State.NextToken = State.NextToken->Next;
1714 // Verilog case labels are on the same unwrapped lines as the statements that
1715 // follow. TokenAnnotator identifies them and sets MustBreakBefore.
1716 // Indentation is taken care of here. A case label can only have 1 statement
1717 // in Verilog, so we don't have to worry about lines that follow.
1718 if (Style.isVerilog() && State.NextToken &&
1719 State.NextToken->MustBreakBefore &&
1720 Keywords.isVerilogEndOfLabel(Current)) {
1721 State.FirstIndent += Style.IndentWidth;
1722 CurrentState.Indent = State.FirstIndent;
1723 }
1724
1725 unsigned Penalty =
1726 handleEndOfLine(Current, State, DryRun, AllowBreak, Newline);
1727
1728 if (Current.Role)
1729 Current.Role->formatFromToken(State, this, DryRun);
1730 // If the previous has a special role, let it consume tokens as appropriate.
1731 // It is necessary to start at the previous token for the only implemented
1732 // role (comma separated list). That way, the decision whether or not to break
1733 // after the "{" is already done and both options are tried and evaluated.
1734 // FIXME: This is ugly, find a better way.
1735 if (Previous && Previous->Role)
1736 Penalty += Previous->Role->formatAfterToken(State, this, DryRun);
1737
1738 return Penalty;
1739}
1740
1741void ContinuationIndenter::moveStatePastFakeLParens(LineState &State,
1742 bool Newline) {
1743 const FormatToken &Current = *State.NextToken;
1744 if (Current.FakeLParens.empty())
1745 return;
1746
1747 const FormatToken *Previous = Current.getPreviousNonComment();
1748
1749 // Don't add extra indentation for the first fake parenthesis after
1750 // 'return', assignments, opening <({[, or requires clauses. The indentation
1751 // for these cases is special cased.
1752 bool SkipFirstExtraIndent =
1753 Previous &&
1754 (Previous->opensScope() ||
1755 Previous->isOneOf(tok::semi, tok::kw_return, TT_RequiresClause) ||
1756 (Previous->getPrecedence() == prec::Assignment &&
1758 Previous->is(TT_ObjCMethodExpr));
1759 for (const auto &PrecedenceLevel : llvm::reverse(Current.FakeLParens)) {
1760 const auto &CurrentState = State.Stack.back();
1761 ParenState NewParenState = CurrentState;
1762 NewParenState.Tok = nullptr;
1763 NewParenState.ContainsLineBreak = false;
1764 NewParenState.LastOperatorWrapped = true;
1765 NewParenState.IsChainedConditional = false;
1766 NewParenState.IsWrappedConditional = false;
1767 NewParenState.UnindentOperator = false;
1768 NewParenState.NoLineBreak =
1769 NewParenState.NoLineBreak || CurrentState.NoLineBreakInOperand;
1770
1771 // Don't propagate AvoidBinPacking into subexpressions of arg/param lists.
1772 if (PrecedenceLevel > prec::Comma)
1773 NewParenState.AvoidBinPacking = false;
1774
1775 // Indent from 'LastSpace' unless these are fake parentheses encapsulating
1776 // a builder type call after 'return' or, if the alignment after opening
1777 // brackets is disabled.
1778 if (!Current.isTrailingComment() &&
1780 PrecedenceLevel < prec::Assignment) &&
1781 (!Previous || Previous->isNot(tok::kw_return) ||
1782 (Style.Language != FormatStyle::LK_Java && PrecedenceLevel > 0)) &&
1784 PrecedenceLevel > prec::Comma || Current.NestingLevel == 0) &&
1785 (!Style.isTableGen() ||
1786 (Previous && Previous->isOneOf(TT_TableGenDAGArgListComma,
1787 TT_TableGenDAGArgListCommaToBreak)))) {
1788 NewParenState.Indent = std::max(
1789 std::max(State.Column, NewParenState.Indent), CurrentState.LastSpace);
1790 }
1791
1792 // Special case for generic selection expressions, its comma-separated
1793 // expressions are not aligned to the opening paren like regular calls, but
1794 // rather continuation-indented relative to the _Generic keyword.
1795 if (Previous && Previous->endsSequence(tok::l_paren, tok::kw__Generic) &&
1796 State.Stack.size() > 1) {
1797 NewParenState.Indent = State.Stack[State.Stack.size() - 2].Indent +
1799 }
1800
1801 if ((shouldUnindentNextOperator(Current) ||
1802 (Previous &&
1803 (PrecedenceLevel == prec::Conditional &&
1804 Previous->is(tok::question) && Previous->is(TT_ConditionalExpr)))) &&
1805 !Newline) {
1806 // If BreakBeforeBinaryOperators is set, un-indent a bit to account for
1807 // the operator and keep the operands aligned.
1809 NewParenState.UnindentOperator = true;
1810 // Mark indentation as alignment if the expression is aligned.
1812 NewParenState.IsAligned = true;
1813 }
1814
1815 // Do not indent relative to the fake parentheses inserted for "." or "->".
1816 // This is a special case to make the following to statements consistent:
1817 // OuterFunction(InnerFunctionCall( // break
1818 // ParameterToInnerFunction));
1819 // OuterFunction(SomeObject.InnerFunctionCall( // break
1820 // ParameterToInnerFunction));
1821 if (PrecedenceLevel > prec::Unknown)
1822 NewParenState.LastSpace = std::max(NewParenState.LastSpace, State.Column);
1823 if (PrecedenceLevel != prec::Conditional &&
1824 Current.isNot(TT_UnaryOperator) &&
1826 NewParenState.StartOfFunctionCall = State.Column;
1827 }
1828
1829 // Indent conditional expressions, unless they are chained "else-if"
1830 // conditionals. Never indent expression where the 'operator' is ',', ';' or
1831 // an assignment (i.e. *I <= prec::Assignment) as those have different
1832 // indentation rules. Indent other expression, unless the indentation needs
1833 // to be skipped.
1834 if (PrecedenceLevel == prec::Conditional && Previous &&
1835 Previous->is(tok::colon) && Previous->is(TT_ConditionalExpr) &&
1836 &PrecedenceLevel == &Current.FakeLParens.back() &&
1837 !CurrentState.IsWrappedConditional) {
1838 NewParenState.IsChainedConditional = true;
1839 NewParenState.UnindentOperator = State.Stack.back().UnindentOperator;
1840 } else if (PrecedenceLevel == prec::Conditional ||
1841 (!SkipFirstExtraIndent && PrecedenceLevel > prec::Assignment &&
1842 !Current.isTrailingComment())) {
1843 NewParenState.Indent += Style.ContinuationIndentWidth;
1844 }
1845 if ((Previous && !Previous->opensScope()) || PrecedenceLevel != prec::Comma)
1846 NewParenState.BreakBeforeParameter = false;
1847 State.Stack.push_back(NewParenState);
1848 SkipFirstExtraIndent = false;
1849 }
1850}
1851
1852void ContinuationIndenter::moveStatePastFakeRParens(LineState &State) {
1853 for (unsigned i = 0, e = State.NextToken->FakeRParens; i != e; ++i) {
1854 unsigned VariablePos = State.Stack.back().VariablePos;
1855 if (State.Stack.size() == 1) {
1856 // Do not pop the last element.
1857 break;
1858 }
1859 State.Stack.pop_back();
1860 State.Stack.back().VariablePos = VariablePos;
1861 }
1862
1863 if (State.NextToken->ClosesRequiresClause && Style.IndentRequiresClause) {
1864 // Remove the indentation of the requires clauses (which is not in Indent,
1865 // but in LastSpace).
1866 State.Stack.back().LastSpace -= Style.IndentWidth;
1867 }
1868}
1869
1870void ContinuationIndenter::moveStatePastScopeOpener(LineState &State,
1871 bool Newline) {
1872 const FormatToken &Current = *State.NextToken;
1873 if (!Current.opensScope())
1874 return;
1875
1876 const auto &CurrentState = State.Stack.back();
1877
1878 // Don't allow '<' or '(' in C# generic type constraints to start new scopes.
1879 if (Current.isOneOf(tok::less, tok::l_paren) &&
1880 CurrentState.IsCSharpGenericTypeConstraint) {
1881 return;
1882 }
1883
1884 if (Current.MatchingParen && Current.is(BK_Block)) {
1885 moveStateToNewBlock(State, Newline);
1886 return;
1887 }
1888
1889 unsigned NewIndent;
1890 unsigned LastSpace = CurrentState.LastSpace;
1891 bool AvoidBinPacking;
1892 bool BreakBeforeParameter = false;
1893 unsigned NestedBlockIndent = std::max(CurrentState.StartOfFunctionCall,
1894 CurrentState.NestedBlockIndent);
1895 if (Current.isOneOf(tok::l_brace, TT_ArrayInitializerLSquare) ||
1896 opensProtoMessageField(Current, Style)) {
1897 if (Current.opensBlockOrBlockTypeList(Style)) {
1898 NewIndent = Style.IndentWidth +
1899 std::min(State.Column, CurrentState.NestedBlockIndent);
1900 } else if (Current.is(tok::l_brace)) {
1901 NewIndent =
1902 CurrentState.LastSpace + Style.BracedInitializerIndentWidth.value_or(
1904 } else {
1905 NewIndent = CurrentState.LastSpace + Style.ContinuationIndentWidth;
1906 }
1907 const FormatToken *NextNonComment = Current.getNextNonComment();
1908 bool EndsInComma = Current.MatchingParen &&
1909 Current.MatchingParen->Previous &&
1910 Current.MatchingParen->Previous->is(tok::comma);
1911 AvoidBinPacking = EndsInComma || Current.is(TT_DictLiteral) ||
1912 Style.isProto() || !Style.BinPackArguments ||
1913 (NextNonComment && NextNonComment->isOneOf(
1914 TT_DesignatedInitializerPeriod,
1915 TT_DesignatedInitializerLSquare));
1916 BreakBeforeParameter = EndsInComma;
1917 if (Current.ParameterCount > 1)
1918 NestedBlockIndent = std::max(NestedBlockIndent, State.Column + 1);
1919 } else {
1920 NewIndent =
1922 std::max(CurrentState.LastSpace, CurrentState.StartOfFunctionCall);
1923
1924 if (Style.isTableGen() && Current.is(TT_TableGenDAGArgOpenerToBreak) &&
1926 // For the case the next token is a TableGen DAGArg operator identifier
1927 // that is not marked to have a line break after it.
1928 // In this case the option DAS_BreakElements requires to align the
1929 // DAGArg elements to the operator.
1930 const FormatToken *Next = Current.Next;
1931 if (Next && Next->is(TT_TableGenDAGArgOperatorID))
1932 NewIndent = State.Column + Next->TokenText.size() + 2;
1933 }
1934
1935 // Ensure that different different brackets force relative alignment, e.g.:
1936 // void SomeFunction(vector< // break
1937 // int> v);
1938 // FIXME: We likely want to do this for more combinations of brackets.
1939 if (Current.is(tok::less) && Current.ParentBracket == tok::l_paren) {
1940 NewIndent = std::max(NewIndent, CurrentState.Indent);
1941 LastSpace = std::max(LastSpace, CurrentState.Indent);
1942 }
1943
1944 bool EndsInComma =
1945 Current.MatchingParen &&
1946 Current.MatchingParen->getPreviousNonComment() &&
1947 Current.MatchingParen->getPreviousNonComment()->is(tok::comma);
1948
1949 // If ObjCBinPackProtocolList is unspecified, fall back to BinPackParameters
1950 // for backwards compatibility.
1951 bool ObjCBinPackProtocolList =
1953 Style.BinPackParameters) ||
1955
1956 bool BinPackDeclaration =
1957 (State.Line->Type != LT_ObjCDecl && Style.BinPackParameters) ||
1958 (State.Line->Type == LT_ObjCDecl && ObjCBinPackProtocolList);
1959
1960 bool GenericSelection =
1961 Current.getPreviousNonComment() &&
1962 Current.getPreviousNonComment()->is(tok::kw__Generic);
1963
1964 AvoidBinPacking =
1965 (CurrentState.IsCSharpGenericTypeConstraint) || GenericSelection ||
1966 (Style.isJavaScript() && EndsInComma) ||
1967 (State.Line->MustBeDeclaration && !BinPackDeclaration) ||
1968 (!State.Line->MustBeDeclaration && !Style.BinPackArguments) ||
1970 (Current.is(PPK_OnePerLine) ||
1971 (!BinPackInconclusiveFunctions && Current.is(PPK_Inconclusive))));
1972
1973 if (Current.is(TT_ObjCMethodExpr) && Current.MatchingParen &&
1975 if (Style.ColumnLimit) {
1976 // If this '[' opens an ObjC call, determine whether all parameters fit
1977 // into one line and put one per line if they don't.
1978 if (getLengthToMatchingParen(Current, State.Stack) + State.Column >
1979 getColumnLimit(State)) {
1980 BreakBeforeParameter = true;
1981 }
1982 } else {
1983 // For ColumnLimit = 0, we have to figure out whether there is or has to
1984 // be a line break within this call.
1985 for (const FormatToken *Tok = &Current;
1986 Tok && Tok != Current.MatchingParen; Tok = Tok->Next) {
1987 if (Tok->MustBreakBefore ||
1988 (Tok->CanBreakBefore && Tok->NewlinesBefore > 0)) {
1989 BreakBeforeParameter = true;
1990 break;
1991 }
1992 }
1993 }
1994 }
1995
1996 if (Style.isJavaScript() && EndsInComma)
1997 BreakBeforeParameter = true;
1998 }
1999 // Generally inherit NoLineBreak from the current scope to nested scope.
2000 // However, don't do this for non-empty nested blocks, dict literals and
2001 // array literals as these follow different indentation rules.
2002 bool NoLineBreak =
2003 Current.Children.empty() &&
2004 !Current.isOneOf(TT_DictLiteral, TT_ArrayInitializerLSquare) &&
2005 (CurrentState.NoLineBreak || CurrentState.NoLineBreakInOperand ||
2006 (Current.is(TT_TemplateOpener) &&
2007 CurrentState.ContainsUnwrappedBuilder));
2008 State.Stack.push_back(
2009 ParenState(&Current, NewIndent, LastSpace, AvoidBinPacking, NoLineBreak));
2010 auto &NewState = State.Stack.back();
2011 NewState.NestedBlockIndent = NestedBlockIndent;
2012 NewState.BreakBeforeParameter = BreakBeforeParameter;
2013 NewState.HasMultipleNestedBlocks = (Current.BlockParameterCount > 1);
2014
2015 if (Style.BraceWrapping.BeforeLambdaBody && Current.Next &&
2016 Current.is(tok::l_paren)) {
2017 // Search for any parameter that is a lambda.
2018 FormatToken const *next = Current.Next;
2019 while (next) {
2020 if (next->is(TT_LambdaLSquare)) {
2021 NewState.HasMultipleNestedBlocks = true;
2022 break;
2023 }
2024 next = next->Next;
2025 }
2026 }
2027
2028 NewState.IsInsideObjCArrayLiteral = Current.is(TT_ArrayInitializerLSquare) &&
2029 Current.Previous &&
2030 Current.Previous->is(tok::at);
2031}
2032
2033void ContinuationIndenter::moveStatePastScopeCloser(LineState &State) {
2034 const FormatToken &Current = *State.NextToken;
2035 if (!Current.closesScope())
2036 return;
2037
2038 // If we encounter a closing ), ], } or >, we can remove a level from our
2039 // stacks.
2040 if (State.Stack.size() > 1 &&
2041 (Current.isOneOf(tok::r_paren, tok::r_square, TT_TemplateString) ||
2042 (Current.is(tok::r_brace) && State.NextToken != State.Line->First) ||
2043 State.NextToken->is(TT_TemplateCloser) ||
2044 State.NextToken->is(TT_TableGenListCloser) ||
2045 (Current.is(tok::greater) && Current.is(TT_DictLiteral)))) {
2046 State.Stack.pop_back();
2047 }
2048
2049 auto &CurrentState = State.Stack.back();
2050
2051 // Reevaluate whether ObjC message arguments fit into one line.
2052 // If a receiver spans multiple lines, e.g.:
2053 // [[object block:^{
2054 // return 42;
2055 // }] a:42 b:42];
2056 // BreakBeforeParameter is calculated based on an incorrect assumption
2057 // (it is checked whether the whole expression fits into one line without
2058 // considering a line break inside a message receiver).
2059 // We check whether arguments fit after receiver scope closer (into the same
2060 // line).
2061 if (CurrentState.BreakBeforeParameter && Current.MatchingParen &&
2062 Current.MatchingParen->Previous) {
2063 const FormatToken &CurrentScopeOpener = *Current.MatchingParen->Previous;
2064 if (CurrentScopeOpener.is(TT_ObjCMethodExpr) &&
2065 CurrentScopeOpener.MatchingParen) {
2066 int NecessarySpaceInLine =
2067 getLengthToMatchingParen(CurrentScopeOpener, State.Stack) +
2068 CurrentScopeOpener.TotalLength - Current.TotalLength - 1;
2069 if (State.Column + Current.ColumnWidth + NecessarySpaceInLine <=
2070 Style.ColumnLimit) {
2071 CurrentState.BreakBeforeParameter = false;
2072 }
2073 }
2074 }
2075
2076 if (Current.is(tok::r_square)) {
2077 // If this ends the array subscript expr, reset the corresponding value.
2078 const FormatToken *NextNonComment = Current.getNextNonComment();
2079 if (NextNonComment && NextNonComment->isNot(tok::l_square))
2080 CurrentState.StartOfArraySubscripts = 0;
2081 }
2082}
2083
2084void ContinuationIndenter::moveStateToNewBlock(LineState &State, bool NewLine) {
2086 State.NextToken->is(TT_LambdaLBrace) &&
2087 !State.Line->MightBeFunctionDecl) {
2088 State.Stack.back().NestedBlockIndent = State.FirstIndent;
2089 }
2090 unsigned NestedBlockIndent = State.Stack.back().NestedBlockIndent;
2091 // ObjC block sometimes follow special indentation rules.
2092 unsigned NewIndent =
2093 NestedBlockIndent + (State.NextToken->is(TT_ObjCBlockLBrace)
2094 ? Style.ObjCBlockIndentWidth
2095 : Style.IndentWidth);
2096
2097 // Even when wrapping before lambda body, the left brace can still be added to
2098 // the same line. This occurs when checking whether the whole lambda body can
2099 // go on a single line. In this case we have to make sure there are no line
2100 // breaks in the body, otherwise we could just end up with a regular lambda
2101 // body without the brace wrapped.
2102 bool NoLineBreak = Style.BraceWrapping.BeforeLambdaBody && !NewLine &&
2103 State.NextToken->is(TT_LambdaLBrace);
2104
2105 State.Stack.push_back(ParenState(State.NextToken, NewIndent,
2106 State.Stack.back().LastSpace,
2107 /*AvoidBinPacking=*/true, NoLineBreak));
2108 State.Stack.back().NestedBlockIndent = NestedBlockIndent;
2109 State.Stack.back().BreakBeforeParameter = true;
2110}
2111
2112static unsigned getLastLineEndColumn(StringRef Text, unsigned StartColumn,
2113 unsigned TabWidth,
2114 encoding::Encoding Encoding) {
2115 size_t LastNewlinePos = Text.find_last_of("\n");
2116 if (LastNewlinePos == StringRef::npos) {
2117 return StartColumn +
2118 encoding::columnWidthWithTabs(Text, StartColumn, TabWidth, Encoding);
2119 } else {
2120 return encoding::columnWidthWithTabs(Text.substr(LastNewlinePos),
2121 /*StartColumn=*/0, TabWidth, Encoding);
2122 }
2123}
2124
2125unsigned ContinuationIndenter::reformatRawStringLiteral(
2126 const FormatToken &Current, LineState &State,
2127 const FormatStyle &RawStringStyle, bool DryRun, bool Newline) {
2128 unsigned StartColumn = State.Column - Current.ColumnWidth;
2129 StringRef OldDelimiter = *getRawStringDelimiter(Current.TokenText);
2130 StringRef NewDelimiter =
2131 getCanonicalRawStringDelimiter(Style, RawStringStyle.Language);
2132 if (NewDelimiter.empty())
2133 NewDelimiter = OldDelimiter;
2134 // The text of a raw string is between the leading 'R"delimiter(' and the
2135 // trailing 'delimiter)"'.
2136 unsigned OldPrefixSize = 3 + OldDelimiter.size();
2137 unsigned OldSuffixSize = 2 + OldDelimiter.size();
2138 // We create a virtual text environment which expects a null-terminated
2139 // string, so we cannot use StringRef.
2140 std::string RawText = std::string(
2141 Current.TokenText.substr(OldPrefixSize).drop_back(OldSuffixSize));
2142 if (NewDelimiter != OldDelimiter) {
2143 // Don't update to the canonical delimiter 'deli' if ')deli"' occurs in the
2144 // raw string.
2145 std::string CanonicalDelimiterSuffix = (")" + NewDelimiter + "\"").str();
2146 if (StringRef(RawText).contains(CanonicalDelimiterSuffix))
2147 NewDelimiter = OldDelimiter;
2148 }
2149
2150 unsigned NewPrefixSize = 3 + NewDelimiter.size();
2151 unsigned NewSuffixSize = 2 + NewDelimiter.size();
2152
2153 // The first start column is the column the raw text starts after formatting.
2154 unsigned FirstStartColumn = StartColumn + NewPrefixSize;
2155
2156 // The next start column is the intended indentation a line break inside
2157 // the raw string at level 0. It is determined by the following rules:
2158 // - if the content starts on newline, it is one level more than the current
2159 // indent, and
2160 // - if the content does not start on a newline, it is the first start
2161 // column.
2162 // These rules have the advantage that the formatted content both does not
2163 // violate the rectangle rule and visually flows within the surrounding
2164 // source.
2165 bool ContentStartsOnNewline = Current.TokenText[OldPrefixSize] == '\n';
2166 // If this token is the last parameter (checked by looking if it's followed by
2167 // `)` and is not on a newline, the base the indent off the line's nested
2168 // block indent. Otherwise, base the indent off the arguments indent, so we
2169 // can achieve:
2170 //
2171 // fffffffffff(1, 2, 3, R"pb(
2172 // key1: 1 #
2173 // key2: 2)pb");
2174 //
2175 // fffffffffff(1, 2, 3,
2176 // R"pb(
2177 // key1: 1 #
2178 // key2: 2
2179 // )pb");
2180 //
2181 // fffffffffff(1, 2, 3,
2182 // R"pb(
2183 // key1: 1 #
2184 // key2: 2
2185 // )pb",
2186 // 5);
2187 unsigned CurrentIndent =
2188 (!Newline && Current.Next && Current.Next->is(tok::r_paren))
2189 ? State.Stack.back().NestedBlockIndent
2190 : State.Stack.back().Indent;
2191 unsigned NextStartColumn = ContentStartsOnNewline
2192 ? CurrentIndent + Style.IndentWidth
2193 : FirstStartColumn;
2194
2195 // The last start column is the column the raw string suffix starts if it is
2196 // put on a newline.
2197 // The last start column is the intended indentation of the raw string postfix
2198 // if it is put on a newline. It is determined by the following rules:
2199 // - if the raw string prefix starts on a newline, it is the column where
2200 // that raw string prefix starts, and
2201 // - if the raw string prefix does not start on a newline, it is the current
2202 // indent.
2203 unsigned LastStartColumn =
2204 Current.NewlinesBefore ? FirstStartColumn - NewPrefixSize : CurrentIndent;
2205
2206 std::pair<tooling::Replacements, unsigned> Fixes = internal::reformat(
2207 RawStringStyle, RawText, {tooling::Range(0, RawText.size())},
2208 FirstStartColumn, NextStartColumn, LastStartColumn, "<stdin>",
2209 /*Status=*/nullptr);
2210
2211 auto NewCode = applyAllReplacements(RawText, Fixes.first);
2212 tooling::Replacements NoFixes;
2213 if (!NewCode)
2214 return addMultilineToken(Current, State);
2215 if (!DryRun) {
2216 if (NewDelimiter != OldDelimiter) {
2217 // In 'R"delimiter(...', the delimiter starts 2 characters after the start
2218 // of the token.
2219 SourceLocation PrefixDelimiterStart =
2220 Current.Tok.getLocation().getLocWithOffset(2);
2221 auto PrefixErr = Whitespaces.addReplacement(tooling::Replacement(
2222 SourceMgr, PrefixDelimiterStart, OldDelimiter.size(), NewDelimiter));
2223 if (PrefixErr) {
2224 llvm::errs()
2225 << "Failed to update the prefix delimiter of a raw string: "
2226 << llvm::toString(std::move(PrefixErr)) << "\n";
2227 }
2228 // In 'R"delimiter(...)delimiter"', the suffix delimiter starts at
2229 // position length - 1 - |delimiter|.
2230 SourceLocation SuffixDelimiterStart =
2231 Current.Tok.getLocation().getLocWithOffset(Current.TokenText.size() -
2232 1 - OldDelimiter.size());
2233 auto SuffixErr = Whitespaces.addReplacement(tooling::Replacement(
2234 SourceMgr, SuffixDelimiterStart, OldDelimiter.size(), NewDelimiter));
2235 if (SuffixErr) {
2236 llvm::errs()
2237 << "Failed to update the suffix delimiter of a raw string: "
2238 << llvm::toString(std::move(SuffixErr)) << "\n";
2239 }
2240 }
2241 SourceLocation OriginLoc =
2242 Current.Tok.getLocation().getLocWithOffset(OldPrefixSize);
2243 for (const tooling::Replacement &Fix : Fixes.first) {
2244 auto Err = Whitespaces.addReplacement(tooling::Replacement(
2245 SourceMgr, OriginLoc.getLocWithOffset(Fix.getOffset()),
2246 Fix.getLength(), Fix.getReplacementText()));
2247 if (Err) {
2248 llvm::errs() << "Failed to reformat raw string: "
2249 << llvm::toString(std::move(Err)) << "\n";
2250 }
2251 }
2252 }
2253 unsigned RawLastLineEndColumn = getLastLineEndColumn(
2254 *NewCode, FirstStartColumn, Style.TabWidth, Encoding);
2255 State.Column = RawLastLineEndColumn + NewSuffixSize;
2256 // Since we're updating the column to after the raw string literal here, we
2257 // have to manually add the penalty for the prefix R"delim( over the column
2258 // limit.
2259 unsigned PrefixExcessCharacters =
2260 StartColumn + NewPrefixSize > Style.ColumnLimit
2261 ? StartColumn + NewPrefixSize - Style.ColumnLimit
2262 : 0;
2263 bool IsMultiline =
2264 ContentStartsOnNewline || (NewCode->find('\n') != std::string::npos);
2265 if (IsMultiline) {
2266 // Break before further function parameters on all levels.
2267 for (ParenState &Paren : State.Stack)
2268 Paren.BreakBeforeParameter = true;
2269 }
2270 return Fixes.second + PrefixExcessCharacters * Style.PenaltyExcessCharacter;
2271}
2272
2273unsigned ContinuationIndenter::addMultilineToken(const FormatToken &Current,
2274 LineState &State) {
2275 // Break before further function parameters on all levels.
2276 for (ParenState &Paren : State.Stack)
2277 Paren.BreakBeforeParameter = true;
2278
2279 unsigned ColumnsUsed = State.Column;
2280 // We can only affect layout of the first and the last line, so the penalty
2281 // for all other lines is constant, and we ignore it.
2282 State.Column = Current.LastLineColumnWidth;
2283
2284 if (ColumnsUsed > getColumnLimit(State))
2285 return Style.PenaltyExcessCharacter * (ColumnsUsed - getColumnLimit(State));
2286 return 0;
2287}
2288
2289unsigned ContinuationIndenter::handleEndOfLine(const FormatToken &Current,
2290 LineState &State, bool DryRun,
2291 bool AllowBreak, bool Newline) {
2292 unsigned Penalty = 0;
2293 // Compute the raw string style to use in case this is a raw string literal
2294 // that can be reformatted.
2295 auto RawStringStyle = getRawStringStyle(Current, State);
2296 if (RawStringStyle && !Current.Finalized) {
2297 Penalty = reformatRawStringLiteral(Current, State, *RawStringStyle, DryRun,
2298 Newline);
2299 } else if (Current.IsMultiline && Current.isNot(TT_BlockComment)) {
2300 // Don't break multi-line tokens other than block comments and raw string
2301 // literals. Instead, just update the state.
2302 Penalty = addMultilineToken(Current, State);
2303 } else if (State.Line->Type != LT_ImportStatement) {
2304 // We generally don't break import statements.
2305 LineState OriginalState = State;
2306
2307 // Whether we force the reflowing algorithm to stay strictly within the
2308 // column limit.
2309 bool Strict = false;
2310 // Whether the first non-strict attempt at reflowing did intentionally
2311 // exceed the column limit.
2312 bool Exceeded = false;
2313 std::tie(Penalty, Exceeded) = breakProtrudingToken(
2314 Current, State, AllowBreak, /*DryRun=*/true, Strict);
2315 if (Exceeded) {
2316 // If non-strict reflowing exceeds the column limit, try whether strict
2317 // reflowing leads to an overall lower penalty.
2318 LineState StrictState = OriginalState;
2319 unsigned StrictPenalty =
2320 breakProtrudingToken(Current, StrictState, AllowBreak,
2321 /*DryRun=*/true, /*Strict=*/true)
2322 .first;
2323 Strict = StrictPenalty <= Penalty;
2324 if (Strict) {
2325 Penalty = StrictPenalty;
2326 State = StrictState;
2327 }
2328 }
2329 if (!DryRun) {
2330 // If we're not in dry-run mode, apply the changes with the decision on
2331 // strictness made above.
2332 breakProtrudingToken(Current, OriginalState, AllowBreak, /*DryRun=*/false,
2333 Strict);
2334 }
2335 }
2336 if (State.Column > getColumnLimit(State)) {
2337 unsigned ExcessCharacters = State.Column - getColumnLimit(State);
2338 Penalty += Style.PenaltyExcessCharacter * ExcessCharacters;
2339 }
2340 return Penalty;
2341}
2342
2343// Returns the enclosing function name of a token, or the empty string if not
2344// found.
2345static StringRef getEnclosingFunctionName(const FormatToken &Current) {
2346 // Look for: 'function(' or 'function<templates>(' before Current.
2347 auto Tok = Current.getPreviousNonComment();
2348 if (!Tok || Tok->isNot(tok::l_paren))
2349 return "";
2350 Tok = Tok->getPreviousNonComment();
2351 if (!Tok)
2352 return "";
2353 if (Tok->is(TT_TemplateCloser)) {
2354 Tok = Tok->MatchingParen;
2355 if (Tok)
2356 Tok = Tok->getPreviousNonComment();
2357 }
2358 if (!Tok || Tok->isNot(tok::identifier))
2359 return "";
2360 return Tok->TokenText;
2361}
2362
2363std::optional<FormatStyle>
2364ContinuationIndenter::getRawStringStyle(const FormatToken &Current,
2365 const LineState &State) {
2366 if (!Current.isStringLiteral())
2367 return std::nullopt;
2368 auto Delimiter = getRawStringDelimiter(Current.TokenText);
2369 if (!Delimiter)
2370 return std::nullopt;
2371 auto RawStringStyle = RawStringFormats.getDelimiterStyle(*Delimiter);
2372 if (!RawStringStyle && Delimiter->empty()) {
2373 RawStringStyle = RawStringFormats.getEnclosingFunctionStyle(
2374 getEnclosingFunctionName(Current));
2375 }
2376 if (!RawStringStyle)
2377 return std::nullopt;
2378 RawStringStyle->ColumnLimit = getColumnLimit(State);
2379 return RawStringStyle;
2380}
2381
2382std::unique_ptr<BreakableToken>
2383ContinuationIndenter::createBreakableToken(const FormatToken &Current,
2384 LineState &State, bool AllowBreak) {
2385 unsigned StartColumn = State.Column - Current.ColumnWidth;
2386 if (Current.isStringLiteral()) {
2387 // Strings in JSON cannot be broken. Breaking strings in JavaScript is
2388 // disabled for now.
2389 if (Style.isJson() || Style.isJavaScript() || !Style.BreakStringLiterals ||
2390 !AllowBreak) {
2391 return nullptr;
2392 }
2393
2394 // Don't break string literals inside preprocessor directives (except for
2395 // #define directives, as their contents are stored in separate lines and
2396 // are not affected by this check).
2397 // This way we avoid breaking code with line directives and unknown
2398 // preprocessor directives that contain long string literals.
2399 if (State.Line->Type == LT_PreprocessorDirective)
2400 return nullptr;
2401 // Exempts unterminated string literals from line breaking. The user will
2402 // likely want to terminate the string before any line breaking is done.
2403 if (Current.IsUnterminatedLiteral)
2404 return nullptr;
2405 // Don't break string literals inside Objective-C array literals (doing so
2406 // raises the warning -Wobjc-string-concatenation).
2407 if (State.Stack.back().IsInsideObjCArrayLiteral)
2408 return nullptr;
2409
2410 // The "DPI"/"DPI-C" in SystemVerilog direct programming interface
2411 // imports/exports cannot be split, e.g.
2412 // `import "DPI" function foo();`
2413 // FIXME: make this use same infra as C++ import checks
2414 if (Style.isVerilog() && Current.Previous &&
2415 Current.Previous->isOneOf(tok::kw_export, Keywords.kw_import)) {
2416 return nullptr;
2417 }
2418 StringRef Text = Current.TokenText;
2419
2420 // We need this to address the case where there is an unbreakable tail only
2421 // if certain other formatting decisions have been taken. The
2422 // UnbreakableTailLength of Current is an overapproximation in that case and
2423 // we need to be correct here.
2424 unsigned UnbreakableTailLength = (State.NextToken && canBreak(State))
2425 ? 0
2426 : Current.UnbreakableTailLength;
2427
2428 if (Style.isVerilog() || Style.Language == FormatStyle::LK_Java ||
2429 Style.isJavaScript() || Style.isCSharp()) {
2431 if (Style.isJavaScript() && Text.starts_with("'") &&
2432 Text.ends_with("'")) {
2434 } else if (Style.isCSharp() && Text.starts_with("@\"") &&
2435 Text.ends_with("\"")) {
2437 } else if (Text.starts_with("\"") && Text.ends_with("\"")) {
2439 } else {
2440 return nullptr;
2441 }
2442 return std::make_unique<BreakableStringLiteralUsingOperators>(
2443 Current, QuoteStyle,
2444 /*UnindentPlus=*/shouldUnindentNextOperator(Current), StartColumn,
2445 UnbreakableTailLength, State.Line->InPPDirective, Encoding, Style);
2446 }
2447
2448 StringRef Prefix;
2449 StringRef Postfix;
2450 // FIXME: Handle whitespace between '_T', '(', '"..."', and ')'.
2451 // FIXME: Store Prefix and Suffix (or PrefixLength and SuffixLength to
2452 // reduce the overhead) for each FormatToken, which is a string, so that we
2453 // don't run multiple checks here on the hot path.
2454 if ((Text.ends_with(Postfix = "\"") &&
2455 (Text.starts_with(Prefix = "@\"") || Text.starts_with(Prefix = "\"") ||
2456 Text.starts_with(Prefix = "u\"") ||
2457 Text.starts_with(Prefix = "U\"") ||
2458 Text.starts_with(Prefix = "u8\"") ||
2459 Text.starts_with(Prefix = "L\""))) ||
2460 (Text.starts_with(Prefix = "_T(\"") &&
2461 Text.ends_with(Postfix = "\")"))) {
2462 return std::make_unique<BreakableStringLiteral>(
2463 Current, StartColumn, Prefix, Postfix, UnbreakableTailLength,
2464 State.Line->InPPDirective, Encoding, Style);
2465 }
2466 } else if (Current.is(TT_BlockComment)) {
2467 if (!Style.ReflowComments ||
2468 // If a comment token switches formatting, like
2469 // /* clang-format on */, we don't want to break it further,
2470 // but we may still want to adjust its indentation.
2471 switchesFormatting(Current)) {
2472 return nullptr;
2473 }
2474 return std::make_unique<BreakableBlockComment>(
2475 Current, StartColumn, Current.OriginalColumn, !Current.Previous,
2476 State.Line->InPPDirective, Encoding, Style, Whitespaces.useCRLF());
2477 } else if (Current.is(TT_LineComment) &&
2478 (!Current.Previous ||
2479 Current.Previous->isNot(TT_ImplicitStringLiteral))) {
2480 bool RegularComments = [&]() {
2481 for (const FormatToken *T = &Current; T && T->is(TT_LineComment);
2482 T = T->Next) {
2483 if (!(T->TokenText.starts_with("//") || T->TokenText.starts_with("#")))
2484 return false;
2485 }
2486 return true;
2487 }();
2488 if (!Style.ReflowComments ||
2489 CommentPragmasRegex.match(Current.TokenText.substr(2)) ||
2490 switchesFormatting(Current) || !RegularComments) {
2491 return nullptr;
2492 }
2493 return std::make_unique<BreakableLineCommentSection>(
2494 Current, StartColumn, /*InPPDirective=*/false, Encoding, Style);
2495 }
2496 return nullptr;
2497}
2498
2499std::pair<unsigned, bool>
2500ContinuationIndenter::breakProtrudingToken(const FormatToken &Current,
2501 LineState &State, bool AllowBreak,
2502 bool DryRun, bool Strict) {
2503 std::unique_ptr<const BreakableToken> Token =
2504 createBreakableToken(Current, State, AllowBreak);
2505 if (!Token)
2506 return {0, false};
2507 assert(Token->getLineCount() > 0);
2508 unsigned ColumnLimit = getColumnLimit(State);
2509 if (Current.is(TT_LineComment)) {
2510 // We don't insert backslashes when breaking line comments.
2511 ColumnLimit = Style.ColumnLimit;
2512 }
2513 if (ColumnLimit == 0) {
2514 // To make the rest of the function easier set the column limit to the
2515 // maximum, if there should be no limit.
2516 ColumnLimit = std::numeric_limits<decltype(ColumnLimit)>::max();
2517 }
2518 if (Current.UnbreakableTailLength >= ColumnLimit)
2519 return {0, false};
2520 // ColumnWidth was already accounted into State.Column before calling
2521 // breakProtrudingToken.
2522 unsigned StartColumn = State.Column - Current.ColumnWidth;
2523 unsigned NewBreakPenalty = Current.isStringLiteral()
2524 ? Style.PenaltyBreakString
2525 : Style.PenaltyBreakComment;
2526 // Stores whether we intentionally decide to let a line exceed the column
2527 // limit.
2528 bool Exceeded = false;
2529 // Stores whether we introduce a break anywhere in the token.
2530 bool BreakInserted = Token->introducesBreakBeforeToken();
2531 // Store whether we inserted a new line break at the end of the previous
2532 // logical line.
2533 bool NewBreakBefore = false;
2534 // We use a conservative reflowing strategy. Reflow starts after a line is
2535 // broken or the corresponding whitespace compressed. Reflow ends as soon as a
2536 // line that doesn't get reflown with the previous line is reached.
2537 bool Reflow = false;
2538 // Keep track of where we are in the token:
2539 // Where we are in the content of the current logical line.
2540 unsigned TailOffset = 0;
2541 // The column number we're currently at.
2542 unsigned ContentStartColumn =
2543 Token->getContentStartColumn(0, /*Break=*/false);
2544 // The number of columns left in the current logical line after TailOffset.
2545 unsigned RemainingTokenColumns =
2546 Token->getRemainingLength(0, TailOffset, ContentStartColumn);
2547 // Adapt the start of the token, for example indent.
2548 if (!DryRun)
2549 Token->adaptStartOfLine(0, Whitespaces);
2550
2551 unsigned ContentIndent = 0;
2552 unsigned Penalty = 0;
2553 LLVM_DEBUG(llvm::dbgs() << "Breaking protruding token at column "
2554 << StartColumn << ".\n");
2555 for (unsigned LineIndex = 0, EndIndex = Token->getLineCount();
2556 LineIndex != EndIndex; ++LineIndex) {
2557 LLVM_DEBUG(llvm::dbgs()
2558 << " Line: " << LineIndex << " (Reflow: " << Reflow << ")\n");
2559 NewBreakBefore = false;
2560 // If we did reflow the previous line, we'll try reflowing again. Otherwise
2561 // we'll start reflowing if the current line is broken or whitespace is
2562 // compressed.
2563 bool TryReflow = Reflow;
2564 // Break the current token until we can fit the rest of the line.
2565 while (ContentStartColumn + RemainingTokenColumns > ColumnLimit) {
2566 LLVM_DEBUG(llvm::dbgs() << " Over limit, need: "
2567 << (ContentStartColumn + RemainingTokenColumns)
2568 << ", space: " << ColumnLimit
2569 << ", reflown prefix: " << ContentStartColumn
2570 << ", offset in line: " << TailOffset << "\n");
2571 // If the current token doesn't fit, find the latest possible split in the
2572 // current line so that breaking at it will be under the column limit.
2573 // FIXME: Use the earliest possible split while reflowing to correctly
2574 // compress whitespace within a line.
2576 Token->getSplit(LineIndex, TailOffset, ColumnLimit,
2577 ContentStartColumn, CommentPragmasRegex);
2578 if (Split.first == StringRef::npos) {
2579 // No break opportunity - update the penalty and continue with the next
2580 // logical line.
2581 if (LineIndex < EndIndex - 1) {
2582 // The last line's penalty is handled in addNextStateToQueue() or when
2583 // calling replaceWhitespaceAfterLastLine below.
2584 Penalty += Style.PenaltyExcessCharacter *
2585 (ContentStartColumn + RemainingTokenColumns - ColumnLimit);
2586 }
2587 LLVM_DEBUG(llvm::dbgs() << " No break opportunity.\n");
2588 break;
2589 }
2590 assert(Split.first != 0);
2591
2592 if (Token->supportsReflow()) {
2593 // Check whether the next natural split point after the current one can
2594 // still fit the line, either because we can compress away whitespace,
2595 // or because the penalty the excess characters introduce is lower than
2596 // the break penalty.
2597 // We only do this for tokens that support reflowing, and thus allow us
2598 // to change the whitespace arbitrarily (e.g. comments).
2599 // Other tokens, like string literals, can be broken on arbitrary
2600 // positions.
2601
2602 // First, compute the columns from TailOffset to the next possible split
2603 // position.
2604 // For example:
2605 // ColumnLimit: |
2606 // // Some text that breaks
2607 // ^ tail offset
2608 // ^-- split
2609 // ^-------- to split columns
2610 // ^--- next split
2611 // ^--------------- to next split columns
2612 unsigned ToSplitColumns = Token->getRangeLength(
2613 LineIndex, TailOffset, Split.first, ContentStartColumn);
2614 LLVM_DEBUG(llvm::dbgs() << " ToSplit: " << ToSplitColumns << "\n");
2615
2616 BreakableToken::Split NextSplit = Token->getSplit(
2617 LineIndex, TailOffset + Split.first + Split.second, ColumnLimit,
2618 ContentStartColumn + ToSplitColumns + 1, CommentPragmasRegex);
2619 // Compute the columns necessary to fit the next non-breakable sequence
2620 // into the current line.
2621 unsigned ToNextSplitColumns = 0;
2622 if (NextSplit.first == StringRef::npos) {
2623 ToNextSplitColumns = Token->getRemainingLength(LineIndex, TailOffset,
2624 ContentStartColumn);
2625 } else {
2626 ToNextSplitColumns = Token->getRangeLength(
2627 LineIndex, TailOffset,
2628 Split.first + Split.second + NextSplit.first, ContentStartColumn);
2629 }
2630 // Compress the whitespace between the break and the start of the next
2631 // unbreakable sequence.
2632 ToNextSplitColumns =
2633 Token->getLengthAfterCompression(ToNextSplitColumns, Split);
2634 LLVM_DEBUG(llvm::dbgs()
2635 << " ContentStartColumn: " << ContentStartColumn << "\n");
2636 LLVM_DEBUG(llvm::dbgs()
2637 << " ToNextSplit: " << ToNextSplitColumns << "\n");
2638 // If the whitespace compression makes us fit, continue on the current
2639 // line.
2640 bool ContinueOnLine =
2641 ContentStartColumn + ToNextSplitColumns <= ColumnLimit;
2642 unsigned ExcessCharactersPenalty = 0;
2643 if (!ContinueOnLine && !Strict) {
2644 // Similarly, if the excess characters' penalty is lower than the
2645 // penalty of introducing a new break, continue on the current line.
2646 ExcessCharactersPenalty =
2647 (ContentStartColumn + ToNextSplitColumns - ColumnLimit) *
2649 LLVM_DEBUG(llvm::dbgs()
2650 << " Penalty excess: " << ExcessCharactersPenalty
2651 << "\n break : " << NewBreakPenalty << "\n");
2652 if (ExcessCharactersPenalty < NewBreakPenalty) {
2653 Exceeded = true;
2654 ContinueOnLine = true;
2655 }
2656 }
2657 if (ContinueOnLine) {
2658 LLVM_DEBUG(llvm::dbgs() << " Continuing on line...\n");
2659 // The current line fits after compressing the whitespace - reflow
2660 // the next line into it if possible.
2661 TryReflow = true;
2662 if (!DryRun) {
2663 Token->compressWhitespace(LineIndex, TailOffset, Split,
2664 Whitespaces);
2665 }
2666 // When we continue on the same line, leave one space between content.
2667 ContentStartColumn += ToSplitColumns + 1;
2668 Penalty += ExcessCharactersPenalty;
2669 TailOffset += Split.first + Split.second;
2670 RemainingTokenColumns = Token->getRemainingLength(
2671 LineIndex, TailOffset, ContentStartColumn);
2672 continue;
2673 }
2674 }
2675 LLVM_DEBUG(llvm::dbgs() << " Breaking...\n");
2676 // Update the ContentIndent only if the current line was not reflown with
2677 // the previous line, since in that case the previous line should still
2678 // determine the ContentIndent. Also never intent the last line.
2679 if (!Reflow)
2680 ContentIndent = Token->getContentIndent(LineIndex);
2681 LLVM_DEBUG(llvm::dbgs()
2682 << " ContentIndent: " << ContentIndent << "\n");
2683 ContentStartColumn = ContentIndent + Token->getContentStartColumn(
2684 LineIndex, /*Break=*/true);
2685
2686 unsigned NewRemainingTokenColumns = Token->getRemainingLength(
2687 LineIndex, TailOffset + Split.first + Split.second,
2688 ContentStartColumn);
2689 if (NewRemainingTokenColumns == 0) {
2690 // No content to indent.
2691 ContentIndent = 0;
2692 ContentStartColumn =
2693 Token->getContentStartColumn(LineIndex, /*Break=*/true);
2694 NewRemainingTokenColumns = Token->getRemainingLength(
2695 LineIndex, TailOffset + Split.first + Split.second,
2696 ContentStartColumn);
2697 }
2698
2699 // When breaking before a tab character, it may be moved by a few columns,
2700 // but will still be expanded to the next tab stop, so we don't save any
2701 // columns.
2702 if (NewRemainingTokenColumns >= RemainingTokenColumns) {
2703 // FIXME: Do we need to adjust the penalty?
2704 break;
2705 }
2706
2707 LLVM_DEBUG(llvm::dbgs() << " Breaking at: " << TailOffset + Split.first
2708 << ", " << Split.second << "\n");
2709 if (!DryRun) {
2710 Token->insertBreak(LineIndex, TailOffset, Split, ContentIndent,
2711 Whitespaces);
2712 }
2713
2714 Penalty += NewBreakPenalty;
2715 TailOffset += Split.first + Split.second;
2716 RemainingTokenColumns = NewRemainingTokenColumns;
2717 BreakInserted = true;
2718 NewBreakBefore = true;
2719 }
2720 // In case there's another line, prepare the state for the start of the next
2721 // line.
2722 if (LineIndex + 1 != EndIndex) {
2723 unsigned NextLineIndex = LineIndex + 1;
2724 if (NewBreakBefore) {
2725 // After breaking a line, try to reflow the next line into the current
2726 // one once RemainingTokenColumns fits.
2727 TryReflow = true;
2728 }
2729 if (TryReflow) {
2730 // We decided that we want to try reflowing the next line into the
2731 // current one.
2732 // We will now adjust the state as if the reflow is successful (in
2733 // preparation for the next line), and see whether that works. If we
2734 // decide that we cannot reflow, we will later reset the state to the
2735 // start of the next line.
2736 Reflow = false;
2737 // As we did not continue breaking the line, RemainingTokenColumns is
2738 // known to fit after ContentStartColumn. Adapt ContentStartColumn to
2739 // the position at which we want to format the next line if we do
2740 // actually reflow.
2741 // When we reflow, we need to add a space between the end of the current
2742 // line and the next line's start column.
2743 ContentStartColumn += RemainingTokenColumns + 1;
2744 // Get the split that we need to reflow next logical line into the end
2745 // of the current one; the split will include any leading whitespace of
2746 // the next logical line.
2747 BreakableToken::Split SplitBeforeNext =
2748 Token->getReflowSplit(NextLineIndex, CommentPragmasRegex);
2749 LLVM_DEBUG(llvm::dbgs()
2750 << " Size of reflown text: " << ContentStartColumn
2751 << "\n Potential reflow split: ");
2752 if (SplitBeforeNext.first != StringRef::npos) {
2753 LLVM_DEBUG(llvm::dbgs() << SplitBeforeNext.first << ", "
2754 << SplitBeforeNext.second << "\n");
2755 TailOffset = SplitBeforeNext.first + SplitBeforeNext.second;
2756 // If the rest of the next line fits into the current line below the
2757 // column limit, we can safely reflow.
2758 RemainingTokenColumns = Token->getRemainingLength(
2759 NextLineIndex, TailOffset, ContentStartColumn);
2760 Reflow = true;
2761 if (ContentStartColumn + RemainingTokenColumns > ColumnLimit) {
2762 LLVM_DEBUG(llvm::dbgs()
2763 << " Over limit after reflow, need: "
2764 << (ContentStartColumn + RemainingTokenColumns)
2765 << ", space: " << ColumnLimit
2766 << ", reflown prefix: " << ContentStartColumn
2767 << ", offset in line: " << TailOffset << "\n");
2768 // If the whole next line does not fit, try to find a point in
2769 // the next line at which we can break so that attaching the part
2770 // of the next line to that break point onto the current line is
2771 // below the column limit.
2773 Token->getSplit(NextLineIndex, TailOffset, ColumnLimit,
2774 ContentStartColumn, CommentPragmasRegex);
2775 if (Split.first == StringRef::npos) {
2776 LLVM_DEBUG(llvm::dbgs() << " Did not find later break\n");
2777 Reflow = false;
2778 } else {
2779 // Check whether the first split point gets us below the column
2780 // limit. Note that we will execute this split below as part of
2781 // the normal token breaking and reflow logic within the line.
2782 unsigned ToSplitColumns = Token->getRangeLength(
2783 NextLineIndex, TailOffset, Split.first, ContentStartColumn);
2784 if (ContentStartColumn + ToSplitColumns > ColumnLimit) {
2785 LLVM_DEBUG(llvm::dbgs() << " Next split protrudes, need: "
2786 << (ContentStartColumn + ToSplitColumns)
2787 << ", space: " << ColumnLimit);
2788 unsigned ExcessCharactersPenalty =
2789 (ContentStartColumn + ToSplitColumns - ColumnLimit) *
2791 if (NewBreakPenalty < ExcessCharactersPenalty)
2792 Reflow = false;
2793 }
2794 }
2795 }
2796 } else {
2797 LLVM_DEBUG(llvm::dbgs() << "not found.\n");
2798 }
2799 }
2800 if (!Reflow) {
2801 // If we didn't reflow into the next line, the only space to consider is
2802 // the next logical line. Reset our state to match the start of the next
2803 // line.
2804 TailOffset = 0;
2805 ContentStartColumn =
2806 Token->getContentStartColumn(NextLineIndex, /*Break=*/false);
2807 RemainingTokenColumns = Token->getRemainingLength(
2808 NextLineIndex, TailOffset, ContentStartColumn);
2809 // Adapt the start of the token, for example indent.
2810 if (!DryRun)
2811 Token->adaptStartOfLine(NextLineIndex, Whitespaces);
2812 } else {
2813 // If we found a reflow split and have added a new break before the next
2814 // line, we are going to remove the line break at the start of the next
2815 // logical line. For example, here we'll add a new line break after
2816 // 'text', and subsequently delete the line break between 'that' and
2817 // 'reflows'.
2818 // // some text that
2819 // // reflows
2820 // ->
2821 // // some text
2822 // // that reflows
2823 // When adding the line break, we also added the penalty for it, so we
2824 // need to subtract that penalty again when we remove the line break due
2825 // to reflowing.
2826 if (NewBreakBefore) {
2827 assert(Penalty >= NewBreakPenalty);
2828 Penalty -= NewBreakPenalty;
2829 }
2830 if (!DryRun)
2831 Token->reflow(NextLineIndex, Whitespaces);
2832 }
2833 }
2834 }
2835
2836 BreakableToken::Split SplitAfterLastLine =
2837 Token->getSplitAfterLastLine(TailOffset);
2838 if (SplitAfterLastLine.first != StringRef::npos) {
2839 LLVM_DEBUG(llvm::dbgs() << "Replacing whitespace after last line.\n");
2840
2841 // We add the last line's penalty here, since that line is going to be split
2842 // now.
2843 Penalty += Style.PenaltyExcessCharacter *
2844 (ContentStartColumn + RemainingTokenColumns - ColumnLimit);
2845
2846 if (!DryRun) {
2847 Token->replaceWhitespaceAfterLastLine(TailOffset, SplitAfterLastLine,
2848 Whitespaces);
2849 }
2850 ContentStartColumn =
2851 Token->getContentStartColumn(Token->getLineCount() - 1, /*Break=*/true);
2852 RemainingTokenColumns = Token->getRemainingLength(
2853 Token->getLineCount() - 1,
2854 TailOffset + SplitAfterLastLine.first + SplitAfterLastLine.second,
2855 ContentStartColumn);
2856 }
2857
2858 State.Column = ContentStartColumn + RemainingTokenColumns -
2859 Current.UnbreakableTailLength;
2860
2861 if (BreakInserted) {
2862 if (!DryRun)
2863 Token->updateAfterBroken(Whitespaces);
2864
2865 // If we break the token inside a parameter list, we need to break before
2866 // the next parameter on all levels, so that the next parameter is clearly
2867 // visible. Line comments already introduce a break.
2868 if (Current.isNot(TT_LineComment))
2869 for (ParenState &Paren : State.Stack)
2870 Paren.BreakBeforeParameter = true;
2871
2872 if (Current.is(TT_BlockComment))
2873 State.NoContinuation = true;
2874
2875 State.Stack.back().LastSpace = StartColumn;
2876 }
2877
2878 Token->updateNextToken(State);
2879
2880 return {Penalty, Exceeded};
2881}
2882
2884 // In preprocessor directives reserve two chars for trailing " \".
2885 return Style.ColumnLimit - (State.Line->InPPDirective ? 2 : 0);
2886}
2887
2888bool ContinuationIndenter::nextIsMultilineString(const LineState &State) {
2889 const FormatToken &Current = *State.NextToken;
2890 if (!Current.isStringLiteral() || Current.is(TT_ImplicitStringLiteral))
2891 return false;
2892 // We never consider raw string literals "multiline" for the purpose of
2893 // AlwaysBreakBeforeMultilineStrings implementation as they are special-cased
2894 // (see TokenAnnotator::mustBreakBefore().
2895 if (Current.TokenText.starts_with("R\""))
2896 return false;
2897 if (Current.IsMultiline)
2898 return true;
2899 if (Current.getNextNonComment() &&
2900 Current.getNextNonComment()->isStringLiteral()) {
2901 return true; // Implicit concatenation.
2902 }
2903 if (Style.ColumnLimit != 0 && Style.BreakStringLiterals &&
2904 State.Column + Current.ColumnWidth + Current.UnbreakableTailLength >
2905 Style.ColumnLimit) {
2906 return true; // String will be split.
2907 }
2908 return false;
2909}
2910
2911} // namespace format
2912} // namespace clang
StringRef P
Declares BreakableToken, BreakableStringLiteral, BreakableComment, BreakableBlockComment and Breakabl...
Expr * E
This file implements an indenter that manages the indentation of continuations.
This file declares Format APIs to be used internally by the formatting library implementation.
This file contains the declaration of the FormatToken, a wrapper around Token with additional informa...
StringRef Text
Definition: Format.cpp:3002
Various functions to configurably format source code.
Defines and computes precedence levels for binary/ternary operators.
Defines the SourceManager interface.
unsigned LongestObjCSelectorName
Defines the clang::TokenKind enum and support functions.
StateNode * Previous
WhitespaceManager class manages whitespace around tokens and their replacements.
__DEVICE__ int max(int __a, int __b)
This class handles loading and caching of source files into memory.
unsigned getSpellingColumnNumber(SourceLocation Loc, bool *Invalid=nullptr) const
Token - This structure provides full information about a lexed token.
Definition: Token.h:36
bool is(tok::TokenKind K) const
is/isNot - Predicates to check if this token is a specific kind, as in "if (Tok.is(tok::l_brace)) {....
Definition: Token.h:99
std::pair< StringRef::size_type, unsigned > Split
Contains starting character index and length of split.
bool canBreak(const LineState &State)
Returns true, if a line break after State is allowed.
unsigned addTokenToState(LineState &State, bool Newline, bool DryRun, unsigned ExtraSpaces=0)
Appends the next token to State and updates information necessary for indentation.
unsigned getColumnLimit(const LineState &State) const
Get the column limit for this line.
LineState getInitialState(unsigned FirstIndent, unsigned FirstStartColumn, const AnnotatedLine *Line, bool DryRun)
Get the initial state, i.e.
ContinuationIndenter(const FormatStyle &Style, const AdditionalKeywords &Keywords, const SourceManager &SourceMgr, WhitespaceManager &Whitespaces, encoding::Encoding Encoding, bool BinPackInconclusiveFunctions)
Constructs a ContinuationIndenter to format Line starting in column FirstIndent.
bool mustBreak(const LineState &State)
Returns true, if a line break after State is mandatory.
Manages the whitespaces around tokens and their replacements.
llvm::Error addReplacement(const tooling::Replacement &Replacement)
void replaceWhitespace(FormatToken &Tok, unsigned Newlines, unsigned Spaces, unsigned StartOfTokenColumn, bool IsAligned=false, bool InPPDirective=false)
Replaces the whitespace in front of Tok.
unsigned columnWidthWithTabs(StringRef Text, unsigned StartColumn, unsigned TabWidth, Encoding Encoding)
Returns the number of columns required to display the Text, starting from the StartColumn on a termin...
Definition: Encoding.h:60
std::pair< tooling::Replacements, unsigned > reformat(const FormatStyle &Style, StringRef Code, ArrayRef< tooling::Range > Ranges, unsigned FirstStartColumn, unsigned NextStartColumn, unsigned LastStartColumn, StringRef FileName, FormattingAttemptStatus *Status)
Reformats the given Ranges in the code fragment Code.
Definition: Format.cpp:3634
static bool mustBreakBinaryOperation(const FormatToken &Current, const FormatStyle &Style)
static unsigned getLastLineEndColumn(StringRef Text, unsigned StartColumn, unsigned TabWidth, encoding::Encoding Encoding)
static bool shouldUnindentNextOperator(const FormatToken &Tok)
FormatStyle getLLVMStyle(FormatStyle::LanguageKind Language=FormatStyle::LanguageKind::LK_Cpp)
Returns a format style complying with the LLVM coding standards: http://llvm.org/docs/CodingStandards...
Definition: Format.cpp:1423
bool switchesFormatting(const FormatToken &Token)
Checks if Token switches formatting, like /* clang-format off *‍/.
static bool hasNestedBlockInlined(const FormatToken *Previous, const FormatToken &Current, const FormatStyle &Style)
static bool startsSegmentOfBuilderTypeCall(const FormatToken &Tok)
static unsigned getLengthToNextOperator(const FormatToken &Tok)
static bool startsNextParameter(const FormatToken &Current, const FormatStyle &Style)
static bool isAlignableBinaryOperator(const FormatToken &Token)
static unsigned getLengthToMatchingParen(const FormatToken &Tok, ArrayRef< ParenState > Stack)
static bool shouldIndentWrappedSelectorName(const FormatStyle &Style, LineType LineType)
bool getPredefinedStyle(StringRef Name, FormatStyle::LanguageKind Language, FormatStyle *Style)
Gets a predefined style for the specified language by name.
Definition: Format.cpp:1961
static std::optional< StringRef > getRawStringDelimiter(StringRef TokenText)
static StringRef getCanonicalRawStringDelimiter(const FormatStyle &Style, FormatStyle::LanguageKind Language)
static bool startsNextOperand(const FormatToken &Current)
static bool opensProtoMessageField(const FormatToken &LessTok, const FormatStyle &Style)
static StringRef getEnclosingFunctionName(const FormatToken &Current)
bool applyAllReplacements(const Replacements &Replaces, Rewriter &Rewrite)
Apply all replacements in Replaces to the Rewriter Rewrite.
The JSON file list parser is used to communicate input to InstallAPI.
if(T->getSizeExpr()) TRY_TO(TraverseStmt(const_cast< Expr * >(T -> getSizeExpr())))
Language
The language for the input, used to select and validate the language standard and possible actions.
Definition: LangStandard.h:23
const FunctionProtoType * T
Encapsulates keywords that are context sensitive or for languages not properly supported by Clang's l...
Definition: FormatToken.h:1024
bool isVerilogBegin(const FormatToken &Tok) const
Returns whether Tok is a Verilog keyword that opens a block.
Definition: FormatToken.h:1850
bool isVerilogEndOfLabel(const FormatToken &Tok) const
Definition: FormatToken.h:1884
The FormatStyle is used to configure the formatting to follow specific guidelines.
Definition: Format.h:55
@ UT_Never
Never use tab.
Definition: Format.h:4971
unsigned ContinuationIndentWidth
Indent width for line continuations.
Definition: Format.h:2471
bool AlwaysBreakBeforeMultilineStrings
This option is renamed to BreakAfterReturnType.
Definition: Format.h:1104
ReturnTypeBreakingStyle BreakAfterReturnType
The function declaration return type breaking style to use.
Definition: Format.h:1655
bool isTableGen() const
Definition: Format.h:3252
LanguageKind
Supported languages.
Definition: Format.h:3216
@ LK_Java
Should be used for Java.
Definition: Format.h:3224
@ LK_ObjC
Should be used for Objective-C, Objective-C++.
Definition: Format.h:3230
@ LK_Proto
Should be used for Protocol Buffers (https://developers.google.com/protocol-buffers/).
Definition: Format.h:3233
@ LK_TextProto
Should be used for Protocol Buffer messages in text format (https://developers.google....
Definition: Format.h:3238
bool Cpp11BracedListStyle
If true, format braced lists as best suited for C++11 braced lists.
Definition: Format.h:2494
BreakInheritanceListStyle BreakInheritanceList
The inheritance list style to use.
Definition: Format.h:2422
unsigned IndentWidth
The number of columns to use for indentation.
Definition: Format.h:2894
bool IndentRequiresClause
Indent the requires clause in a template.
Definition: Format.h:2880
std::vector< RawStringFormat > RawStringFormats
Defines hints for detecting supported languages code blocks in raw strings.
Definition: Format.h:3788
PPDirectiveIndentStyle IndentPPDirectives
The preprocessor directive indenting style to use.
Definition: Format.h:2858
BinaryOperatorStyle BreakBeforeBinaryOperators
The way to wrap binary operators.
Definition: Format.h:1729
@ BPS_Auto
Automatically determine parameter bin-packing behavior.
Definition: Format.h:1680
@ BPS_Always
Always bin-pack parameters.
Definition: Format.h:1682
@ BCIS_AfterColon
Break constructor initializers after the colon and commas.
Definition: Format.h:2292
@ BCIS_BeforeColon
Break constructor initializers before the colon and after the commas.
Definition: Format.h:2277
@ BCIS_BeforeComma
Break constructor initializers before the colon and commas, and align the commas with the colon.
Definition: Format.h:2285
BreakBeforeConceptDeclarationsStyle BreakBeforeConceptDeclarations
The concept declaration style to use.
Definition: Format.h:2188
BreakTemplateDeclarationsStyle BreakTemplateDeclarations
The template declaration breaking style to use.
Definition: Format.h:2426
@ BOS_None
Break after operators.
Definition: Format.h:1700
bool IndentWrappedFunctionNames
Indent if a function definition or declaration is wrapped after the type.
Definition: Format.h:2908
LanguageKind Language
Language, this format style is targeted at.
Definition: Format.h:3256
@ BAS_DontAlign
Don't align, instead use ContinuationIndentWidth, e.g.:
Definition: Format.h:78
@ BAS_AlwaysBreak
Always break after an open bracket, if the parameters don't fit on a single line, e....
Definition: Format.h:85
@ BAS_BlockIndent
Always break after an open bracket, if the parameters don't fit on a single line.
Definition: Format.h:99
@ BBIAS_Always
Always break before inline ASM colon.
Definition: Format.h:2212
@ BBIAS_OnlyMultiline
Break before inline ASM colon if the line length is longer than column limit.
Definition: Format.h:2205
unsigned TabWidth
The number of columns used for tab stops.
Definition: Format.h:4935
@ PPDIS_AfterHash
Indents directives after the hash.
Definition: Format.h:2844
@ LBI_OuterScope
For statements within block scope, align lambda body relative to the indentation level of the outer s...
Definition: Format.h:3200
@ LBI_Signature
Align lambda body relative to the lambda signature.
Definition: Format.h:3186
unsigned PenaltyBreakFirstLessLess
The penalty for breaking before the first <<.
Definition: Format.h:3589
unsigned ObjCBlockIndentWidth
The number of characters to use for indentation of ObjC blocks.
Definition: Format.h:3454
std::optional< FormatStyle > GetLanguageStyle(LanguageKind Language) const
Definition: Format.cpp:2129
std::optional< unsigned > BracedInitializerIndentWidth
The number of columns to use to indent the contents of braced init lists.
Definition: Format.h:1270
bool ExperimentalAutoDetectBinPacking
If true, clang-format detects whether function calls and definitions are formatted with one parameter...
Definition: Format.h:2640
bool ObjCBreakBeforeNestedBlockParam
Break parameters list into lines when there is nested block parameters in a function call.
Definition: Format.h:3478
OperandAlignmentStyle AlignOperands
If true, horizontally align operands of binary and ternary expressions.
Definition: Format.h:549
@ BTDS_No
Do not force break before declaration.
Definition: Format.h:1127
@ BTDS_Leave
Do not change the line breaking before the declaration.
Definition: Format.h:1117
BreakBinaryOperationsStyle BreakBinaryOperations
The break constructor initializers style to use.
Definition: Format.h:2267
BreakConstructorInitializersStyle BreakConstructorInitializers
The break constructor initializers style to use.
Definition: Format.h:2297
bool BreakStringLiterals
Allow breaking string literals when formatting.
Definition: Format.h:2364
@ PCIS_NextLineOnly
Put all constructor initializers on the next line if they fit.
Definition: Format.h:3568
@ PCIS_BinPack
Bin-pack constructor initializers.
Definition: Format.h:3528
@ PCIS_NextLine
Same as PCIS_CurrentLine except that if all constructor initializers do not fit on the current line,...
Definition: Format.h:3553
BraceBreakingStyle BreakBeforeBraces
The brace breaking style to use.
Definition: Format.h:2164
@ BILS_AfterColon
Break inheritance list after the colon and commas.
Definition: Format.h:2410
@ BILS_BeforeComma
Break inheritance list before the colon and commas, and align the commas with the colon.
Definition: Format.h:2402
bool isCSharp() const
Definition: Format.h:3245
unsigned PenaltyExcessCharacter
The penalty for each character outside of the column limit.
Definition: Format.h:3609
bool BinPackParameters
If false, a function declaration's or function definition's parameters will either all be on the same...
Definition: Format.h:1208
@ DAS_BreakElements
Break inside DAGArg after each list element but for the last.
Definition: Format.h:4918
unsigned ConstructorInitializerIndentWidth
This option is deprecated.
Definition: Format.h:2460
@ RCPS_OwnLine
Always put the requires clause on its own line.
Definition: Format.h:3962
@ RCPS_WithPreceding
Try to put the clause together with the preceding part of a declaration.
Definition: Format.h:3979
@ RCPS_SingleLine
Try to put everything in the same line if possible.
Definition: Format.h:4017
@ RCPS_WithFollowing
Try to put the requires clause together with the class or function declaration.
Definition: Format.h:3993
RequiresClausePositionStyle RequiresClausePosition
The position of the requires clause.
Definition: Format.h:4022
BreakBeforeInlineASMColonStyle BreakBeforeInlineASMColon
The inline ASM colon style to use.
Definition: Format.h:2217
@ BS_Whitesmiths
Like Allman but always indent braces and line up code with braces.
Definition: Format.h:2047
bool BinPackArguments
If false, a function call's arguments will either be all on the same line or will have one line each.
Definition: Format.h:1193
@ SFS_All
Merge all functions fitting on a single line.
Definition: Format.h:857
@ REI_Keyword
Align requires expression body relative to the requires keyword.
Definition: Format.h:4043
PackConstructorInitializersStyle PackConstructorInitializers
The pack constructor initializers style to use.
Definition: Format.h:3573
@ BBCDS_Allowed
Breaking between template declaration and concept is allowed.
Definition: Format.h:2176
@ BBCDS_Never
Keep the template declaration line together with concept.
Definition: Format.h:2172
@ BBCDS_Always
Always break before concept, putting it in the line after the template declaration.
Definition: Format.h:2183
bool AllowAllParametersOfDeclarationOnNextLine
This option is deprecated.
Definition: Format.h:676
BracketAlignmentStyle AlignAfterOpenBracket
If true, horizontally aligns arguments after an open bracket.
Definition: Format.h:107
bool isProto() const
Definition: Format.h:3249
bool ReflowComments
If true, clang-format will attempt to re-flow comments.
Definition: Format.h:3832
unsigned MaxEmptyLinesToKeep
The maximum number of consecutive empty lines to keep.
Definition: Format.h:3359
BinPackStyle ObjCBinPackProtocolList
Controls bin-packing Objective-C protocol conformance list items into as few lines as possible when t...
Definition: Format.h:3443
bool isVerilog() const
Definition: Format.h:3248
bool isJavaScript() const
Definition: Format.h:3247
DAGArgStyle TableGenBreakInsideDAGArg
The styles of the line break inside the DAGArg in TableGen.
Definition: Format.h:4931
LambdaBodyIndentationKind LambdaBodyIndentation
The indentation style of lambda bodies.
Definition: Format.h:3209
@ BBO_Never
Don't break binary operations.
Definition: Format.h:2241
BraceWrappingFlags BraceWrapping
Control of individual brace wrapping cases.
Definition: Format.h:1551
unsigned PenaltyBreakString
The penalty for each line break introduced inside a string literal.
Definition: Format.h:3601
RequiresExpressionIndentationKind RequiresExpressionIndentation
The indentation used for requires expression bodies.
Definition: Format.h:4048
unsigned PenaltyIndentedWhitespace
Penalty for each character of whitespace indentation (counted relative to leading non-whitespace colu...
Definition: Format.h:3614
ShortFunctionStyle AllowShortFunctionsOnASingleLine
Dependent on the value, int f() { return 0; } can be put on a single line.
Definition: Format.h:863
bool AllowAllArgumentsOnNextLine
If a function call or braced initializer list doesn't fit on a line, allow putting all arguments onto...
Definition: Format.h:653
unsigned PenaltyBreakComment
The penalty for each line break introduced inside a comment.
Definition: Format.h:3585
@ RTBS_ExceptShortType
Same as Automatic above, except that there is no break after short return types.
Definition: Format.h:1014
@ RTBS_None
This is deprecated. See Automatic below.
Definition: Format.h:991
UseTabStyle UseTab
The way to use tab characters in the resulting file.
Definition: Format.h:4987
@ OAS_AlignAfterOperator
Horizontally align operands of binary and ternary expressions.
Definition: Format.h:543
@ OAS_DontAlign
Do not align operands of binary and ternary expressions.
Definition: Format.h:517
bool BreakBeforeTernaryOperators
If true, ternary operators will be placed after line breaks.
Definition: Format.h:2232
unsigned ColumnLimit
The column limit.
Definition: Format.h:2372
A wrapper around a Token storing information about the whitespace characters preceding it.
Definition: FormatToken.h:292
unsigned NestingLevel
The nesting level of this token, i.e.
Definition: FormatToken.h:515
bool isMemberAccess() const
Returns true if this is a "." or "->" accessing a member.
Definition: FormatToken.h:720
bool isNot(T Kind) const
Definition: FormatToken.h:623
StringRef TokenText
The raw text of the token.
Definition: FormatToken.h:312
FormatToken * getPreviousNonComment() const
Returns the previous token ignoring comments.
Definition: FormatToken.h:832
bool closesScope() const
Returns whether Tok is )]} or a closing > of a template or in protos.
Definition: FormatToken.h:710
bool is(tok::TokenKind Kind) const
Definition: FormatToken.h:604
unsigned TotalLength
The total length of the unwrapped line up to and including this token.
Definition: FormatToken.h:498
bool isTrailingComment() const
Definition: FormatToken.h:774
FormatToken * NextOperator
If this is an operator (or "."/"->") in a sequence of operators with the same precedence,...
Definition: FormatToken.h:555
FormatToken * MatchingParen
If this is a bracket, this points to the matching one.
Definition: FormatToken.h:558
FormatToken * Previous
The previous token in the unwrapped line.
Definition: FormatToken.h:561
The current state when indenting a unwrapped line.
llvm::StringMap< FormatStyle > EnclosingFunctionStyle
std::optional< FormatStyle > getDelimiterStyle(StringRef Delimiter) const
std::optional< FormatStyle > getEnclosingFunctionStyle(StringRef EnclosingFunction) const
RawStringFormatStyleManager(const FormatStyle &CodeStyle)
llvm::StringMap< FormatStyle > DelimiterStyle