Path: blob/main/contrib/llvm-project/clang/lib/Format/ContinuationIndenter.cpp
35234 views
//===--- ContinuationIndenter.cpp - Format C++ code -----------------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//7///8/// \file9/// This file implements the continuation indenter.10///11//===----------------------------------------------------------------------===//1213#include "ContinuationIndenter.h"14#include "BreakableToken.h"15#include "FormatInternal.h"16#include "FormatToken.h"17#include "WhitespaceManager.h"18#include "clang/Basic/OperatorPrecedence.h"19#include "clang/Basic/SourceManager.h"20#include "clang/Basic/TokenKinds.h"21#include "clang/Format/Format.h"22#include "llvm/ADT/StringSet.h"23#include "llvm/Support/Debug.h"24#include <optional>2526#define DEBUG_TYPE "format-indenter"2728namespace clang {29namespace format {3031// Returns true if a TT_SelectorName should be indented when wrapped,32// false otherwise.33static bool shouldIndentWrappedSelectorName(const FormatStyle &Style,34LineType LineType) {35return Style.IndentWrappedFunctionNames || LineType == LT_ObjCMethodDecl;36}3738// Returns true if a binary operator following \p Tok should be unindented when39// the style permits it.40static bool shouldUnindentNextOperator(const FormatToken &Tok) {41const FormatToken *Previous = Tok.getPreviousNonComment();42return Previous && (Previous->getPrecedence() == prec::Assignment ||43Previous->isOneOf(tok::kw_return, TT_RequiresClause));44}4546// Returns the length of everything up to the first possible line break after47// the ), ], } or > matching \c Tok.48static unsigned getLengthToMatchingParen(const FormatToken &Tok,49ArrayRef<ParenState> Stack) {50// Normally whether or not a break before T is possible is calculated and51// stored in T.CanBreakBefore. Braces, array initializers and text proto52// messages like `key: < ... >` are an exception: a break is possible53// before a closing brace R if a break was inserted after the corresponding54// opening brace. The information about whether or not a break is needed55// before a closing brace R is stored in the ParenState field56// S.BreakBeforeClosingBrace where S is the state that R closes.57//58// In order to decide whether there can be a break before encountered right59// braces, this implementation iterates over the sequence of tokens and over60// the paren stack in lockstep, keeping track of the stack level which visited61// right braces correspond to in MatchingStackIndex.62//63// For example, consider:64// L. <- line number65// 1. {66// 2. {1},67// 3. {2},68// 4. {{3}}}69// ^ where we call this method with this token.70// The paren stack at this point contains 3 brace levels:71// 0. { at line 1, BreakBeforeClosingBrace: true72// 1. first { at line 4, BreakBeforeClosingBrace: false73// 2. second { at line 4, BreakBeforeClosingBrace: false,74// where there might be fake parens levels in-between these levels.75// The algorithm will start at the first } on line 4, which is the matching76// brace of the initial left brace and at level 2 of the stack. Then,77// examining BreakBeforeClosingBrace: false at level 2, it will continue to78// the second } on line 4, and will traverse the stack downwards until it79// finds the matching { on level 1. Then, examining BreakBeforeClosingBrace:80// false at level 1, it will continue to the third } on line 4 and will81// traverse the stack downwards until it finds the matching { on level 0.82// Then, examining BreakBeforeClosingBrace: true at level 0, the algorithm83// will stop and will use the second } on line 4 to determine the length to84// return, as in this example the range will include the tokens: {3}}85//86// The algorithm will only traverse the stack if it encounters braces, array87// initializer squares or text proto angle brackets.88if (!Tok.MatchingParen)89return 0;90FormatToken *End = Tok.MatchingParen;91// Maintains a stack level corresponding to the current End token.92int MatchingStackIndex = Stack.size() - 1;93// Traverses the stack downwards, looking for the level to which LBrace94// corresponds. Returns either a pointer to the matching level or nullptr if95// LParen is not found in the initial portion of the stack up to96// MatchingStackIndex.97auto FindParenState = [&](const FormatToken *LBrace) -> const ParenState * {98while (MatchingStackIndex >= 0 && Stack[MatchingStackIndex].Tok != LBrace)99--MatchingStackIndex;100return MatchingStackIndex >= 0 ? &Stack[MatchingStackIndex] : nullptr;101};102for (; End->Next; End = End->Next) {103if (End->Next->CanBreakBefore)104break;105if (!End->Next->closesScope())106continue;107if (End->Next->MatchingParen &&108End->Next->MatchingParen->isOneOf(109tok::l_brace, TT_ArrayInitializerLSquare, tok::less)) {110const ParenState *State = FindParenState(End->Next->MatchingParen);111if (State && State->BreakBeforeClosingBrace)112break;113}114}115return End->TotalLength - Tok.TotalLength + 1;116}117118static unsigned getLengthToNextOperator(const FormatToken &Tok) {119if (!Tok.NextOperator)120return 0;121return Tok.NextOperator->TotalLength - Tok.TotalLength;122}123124// Returns \c true if \c Tok is the "." or "->" of a call and starts the next125// segment of a builder type call.126static bool startsSegmentOfBuilderTypeCall(const FormatToken &Tok) {127return Tok.isMemberAccess() && Tok.Previous && Tok.Previous->closesScope();128}129130// Returns \c true if \c Current starts a new parameter.131static bool startsNextParameter(const FormatToken &Current,132const FormatStyle &Style) {133const FormatToken &Previous = *Current.Previous;134if (Current.is(TT_CtorInitializerComma) &&135Style.BreakConstructorInitializers == FormatStyle::BCIS_BeforeComma) {136return true;137}138if (Style.Language == FormatStyle::LK_Proto && Current.is(TT_SelectorName))139return true;140return Previous.is(tok::comma) && !Current.isTrailingComment() &&141((Previous.isNot(TT_CtorInitializerComma) ||142Style.BreakConstructorInitializers !=143FormatStyle::BCIS_BeforeComma) &&144(Previous.isNot(TT_InheritanceComma) ||145Style.BreakInheritanceList != FormatStyle::BILS_BeforeComma));146}147148static bool opensProtoMessageField(const FormatToken &LessTok,149const FormatStyle &Style) {150if (LessTok.isNot(tok::less))151return false;152return Style.Language == FormatStyle::LK_TextProto ||153(Style.Language == FormatStyle::LK_Proto &&154(LessTok.NestingLevel > 0 ||155(LessTok.Previous && LessTok.Previous->is(tok::equal))));156}157158// Returns the delimiter of a raw string literal, or std::nullopt if TokenText159// is not the text of a raw string literal. The delimiter could be the empty160// string. For example, the delimiter of R"deli(cont)deli" is deli.161static std::optional<StringRef> getRawStringDelimiter(StringRef TokenText) {162if (TokenText.size() < 5 // The smallest raw string possible is 'R"()"'.163|| !TokenText.starts_with("R\"") || !TokenText.ends_with("\"")) {164return std::nullopt;165}166167// A raw string starts with 'R"<delimiter>(' and delimiter is ascii and has168// size at most 16 by the standard, so the first '(' must be among the first169// 19 bytes.170size_t LParenPos = TokenText.substr(0, 19).find_first_of('(');171if (LParenPos == StringRef::npos)172return std::nullopt;173StringRef Delimiter = TokenText.substr(2, LParenPos - 2);174175// Check that the string ends in ')Delimiter"'.176size_t RParenPos = TokenText.size() - Delimiter.size() - 2;177if (TokenText[RParenPos] != ')')178return std::nullopt;179if (!TokenText.substr(RParenPos + 1).starts_with(Delimiter))180return std::nullopt;181return Delimiter;182}183184// Returns the canonical delimiter for \p Language, or the empty string if no185// canonical delimiter is specified.186static StringRef187getCanonicalRawStringDelimiter(const FormatStyle &Style,188FormatStyle::LanguageKind Language) {189for (const auto &Format : Style.RawStringFormats)190if (Format.Language == Language)191return StringRef(Format.CanonicalDelimiter);192return "";193}194195RawStringFormatStyleManager::RawStringFormatStyleManager(196const FormatStyle &CodeStyle) {197for (const auto &RawStringFormat : CodeStyle.RawStringFormats) {198std::optional<FormatStyle> LanguageStyle =199CodeStyle.GetLanguageStyle(RawStringFormat.Language);200if (!LanguageStyle) {201FormatStyle PredefinedStyle;202if (!getPredefinedStyle(RawStringFormat.BasedOnStyle,203RawStringFormat.Language, &PredefinedStyle)) {204PredefinedStyle = getLLVMStyle();205PredefinedStyle.Language = RawStringFormat.Language;206}207LanguageStyle = PredefinedStyle;208}209LanguageStyle->ColumnLimit = CodeStyle.ColumnLimit;210for (StringRef Delimiter : RawStringFormat.Delimiters)211DelimiterStyle.insert({Delimiter, *LanguageStyle});212for (StringRef EnclosingFunction : RawStringFormat.EnclosingFunctions)213EnclosingFunctionStyle.insert({EnclosingFunction, *LanguageStyle});214}215}216217std::optional<FormatStyle>218RawStringFormatStyleManager::getDelimiterStyle(StringRef Delimiter) const {219auto It = DelimiterStyle.find(Delimiter);220if (It == DelimiterStyle.end())221return std::nullopt;222return It->second;223}224225std::optional<FormatStyle>226RawStringFormatStyleManager::getEnclosingFunctionStyle(227StringRef EnclosingFunction) const {228auto It = EnclosingFunctionStyle.find(EnclosingFunction);229if (It == EnclosingFunctionStyle.end())230return std::nullopt;231return It->second;232}233234ContinuationIndenter::ContinuationIndenter(const FormatStyle &Style,235const AdditionalKeywords &Keywords,236const SourceManager &SourceMgr,237WhitespaceManager &Whitespaces,238encoding::Encoding Encoding,239bool BinPackInconclusiveFunctions)240: Style(Style), Keywords(Keywords), SourceMgr(SourceMgr),241Whitespaces(Whitespaces), Encoding(Encoding),242BinPackInconclusiveFunctions(BinPackInconclusiveFunctions),243CommentPragmasRegex(Style.CommentPragmas), RawStringFormats(Style) {}244245LineState ContinuationIndenter::getInitialState(unsigned FirstIndent,246unsigned FirstStartColumn,247const AnnotatedLine *Line,248bool DryRun) {249LineState State;250State.FirstIndent = FirstIndent;251if (FirstStartColumn && Line->First->NewlinesBefore == 0)252State.Column = FirstStartColumn;253else254State.Column = FirstIndent;255// With preprocessor directive indentation, the line starts on column 0256// since it's indented after the hash, but FirstIndent is set to the257// preprocessor indent.258if (Style.IndentPPDirectives == FormatStyle::PPDIS_AfterHash &&259(Line->Type == LT_PreprocessorDirective ||260Line->Type == LT_ImportStatement)) {261State.Column = 0;262}263State.Line = Line;264State.NextToken = Line->First;265State.Stack.push_back(ParenState(/*Tok=*/nullptr, FirstIndent, FirstIndent,266/*AvoidBinPacking=*/false,267/*NoLineBreak=*/false));268State.NoContinuation = false;269State.StartOfStringLiteral = 0;270State.NoLineBreak = false;271State.StartOfLineLevel = 0;272State.LowestLevelOnLine = 0;273State.IgnoreStackForComparison = false;274275if (Style.Language == FormatStyle::LK_TextProto) {276// We need this in order to deal with the bin packing of text fields at277// global scope.278auto &CurrentState = State.Stack.back();279CurrentState.AvoidBinPacking = true;280CurrentState.BreakBeforeParameter = true;281CurrentState.AlignColons = false;282}283284// The first token has already been indented and thus consumed.285moveStateToNextToken(State, DryRun, /*Newline=*/false);286return State;287}288289bool ContinuationIndenter::canBreak(const LineState &State) {290const FormatToken &Current = *State.NextToken;291const FormatToken &Previous = *Current.Previous;292const auto &CurrentState = State.Stack.back();293assert(&Previous == Current.Previous);294if (!Current.CanBreakBefore && !(CurrentState.BreakBeforeClosingBrace &&295Current.closesBlockOrBlockTypeList(Style))) {296return false;297}298// The opening "{" of a braced list has to be on the same line as the first299// element if it is nested in another braced init list or function call.300if (!Current.MustBreakBefore && Previous.is(tok::l_brace) &&301Previous.isNot(TT_DictLiteral) && Previous.is(BK_BracedInit) &&302Previous.Previous &&303Previous.Previous->isOneOf(tok::l_brace, tok::l_paren, tok::comma)) {304return false;305}306// This prevents breaks like:307// ...308// SomeParameter, OtherParameter).DoSomething(309// ...310// As they hide "DoSomething" and are generally bad for readability.311if (Previous.opensScope() && Previous.isNot(tok::l_brace) &&312State.LowestLevelOnLine < State.StartOfLineLevel &&313State.LowestLevelOnLine < Current.NestingLevel) {314return false;315}316if (Current.isMemberAccess() && CurrentState.ContainsUnwrappedBuilder)317return false;318319// Don't create a 'hanging' indent if there are multiple blocks in a single320// statement and we are aligning lambda blocks to their signatures.321if (Previous.is(tok::l_brace) && State.Stack.size() > 1 &&322State.Stack[State.Stack.size() - 2].NestedBlockInlined &&323State.Stack[State.Stack.size() - 2].HasMultipleNestedBlocks &&324Style.LambdaBodyIndentation == FormatStyle::LBI_Signature) {325return false;326}327328// Don't break after very short return types (e.g. "void") as that is often329// unexpected.330if (Current.is(TT_FunctionDeclarationName)) {331if (Style.BreakAfterReturnType == FormatStyle::RTBS_None &&332State.Column < 6) {333return false;334}335336if (Style.BreakAfterReturnType == FormatStyle::RTBS_ExceptShortType) {337assert(State.Column >= State.FirstIndent);338if (State.Column - State.FirstIndent < 6)339return false;340}341}342343// If binary operators are moved to the next line (including commas for some344// styles of constructor initializers), that's always ok.345if (!Current.isOneOf(TT_BinaryOperator, tok::comma) &&346// Allow breaking opening brace of lambdas (when passed as function347// arguments) to a new line when BeforeLambdaBody brace wrapping is348// enabled.349(!Style.BraceWrapping.BeforeLambdaBody ||350Current.isNot(TT_LambdaLBrace)) &&351CurrentState.NoLineBreakInOperand) {352return false;353}354355if (Previous.is(tok::l_square) && Previous.is(TT_ObjCMethodExpr))356return false;357358if (Current.is(TT_ConditionalExpr) && Previous.is(tok::r_paren) &&359Previous.MatchingParen && Previous.MatchingParen->Previous &&360Previous.MatchingParen->Previous->MatchingParen &&361Previous.MatchingParen->Previous->MatchingParen->is(TT_LambdaLBrace)) {362// We have a lambda within a conditional expression, allow breaking here.363assert(Previous.MatchingParen->Previous->is(tok::r_brace));364return true;365}366367return !State.NoLineBreak && !CurrentState.NoLineBreak;368}369370bool ContinuationIndenter::mustBreak(const LineState &State) {371const FormatToken &Current = *State.NextToken;372const FormatToken &Previous = *Current.Previous;373const auto &CurrentState = State.Stack.back();374if (Style.BraceWrapping.BeforeLambdaBody && Current.CanBreakBefore &&375Current.is(TT_LambdaLBrace) && Previous.isNot(TT_LineComment)) {376auto LambdaBodyLength = getLengthToMatchingParen(Current, State.Stack);377return LambdaBodyLength > getColumnLimit(State);378}379if (Current.MustBreakBefore ||380(Current.is(TT_InlineASMColon) &&381(Style.BreakBeforeInlineASMColon == FormatStyle::BBIAS_Always ||382(Style.BreakBeforeInlineASMColon == FormatStyle::BBIAS_OnlyMultiline &&383Style.ColumnLimit > 0)))) {384return true;385}386if (CurrentState.BreakBeforeClosingBrace &&387(Current.closesBlockOrBlockTypeList(Style) ||388(Current.is(tok::r_brace) &&389Current.isBlockIndentedInitRBrace(Style)))) {390return true;391}392if (CurrentState.BreakBeforeClosingParen && Current.is(tok::r_paren))393return true;394if (Style.Language == FormatStyle::LK_ObjC &&395Style.ObjCBreakBeforeNestedBlockParam &&396Current.ObjCSelectorNameParts > 1 &&397Current.startsSequence(TT_SelectorName, tok::colon, tok::caret)) {398return true;399}400// Avoid producing inconsistent states by requiring breaks where they are not401// permitted for C# generic type constraints.402if (CurrentState.IsCSharpGenericTypeConstraint &&403Previous.isNot(TT_CSharpGenericTypeConstraintComma)) {404return false;405}406if ((startsNextParameter(Current, Style) || Previous.is(tok::semi) ||407(Previous.is(TT_TemplateCloser) && Current.is(TT_StartOfName) &&408State.Line->First->isNot(TT_AttributeSquare) && Style.isCpp() &&409// FIXME: This is a temporary workaround for the case where clang-format410// sets BreakBeforeParameter to avoid bin packing and this creates a411// completely unnecessary line break after a template type that isn't412// line-wrapped.413(Previous.NestingLevel == 1 || Style.BinPackParameters)) ||414(Style.BreakBeforeTernaryOperators && Current.is(TT_ConditionalExpr) &&415Previous.isNot(tok::question)) ||416(!Style.BreakBeforeTernaryOperators &&417Previous.is(TT_ConditionalExpr))) &&418CurrentState.BreakBeforeParameter && !Current.isTrailingComment() &&419!Current.isOneOf(tok::r_paren, tok::r_brace)) {420return true;421}422if (CurrentState.IsChainedConditional &&423((Style.BreakBeforeTernaryOperators && Current.is(TT_ConditionalExpr) &&424Current.is(tok::colon)) ||425(!Style.BreakBeforeTernaryOperators && Previous.is(TT_ConditionalExpr) &&426Previous.is(tok::colon)))) {427return true;428}429if (((Previous.is(TT_DictLiteral) && Previous.is(tok::l_brace)) ||430(Previous.is(TT_ArrayInitializerLSquare) &&431Previous.ParameterCount > 1) ||432opensProtoMessageField(Previous, Style)) &&433Style.ColumnLimit > 0 &&434getLengthToMatchingParen(Previous, State.Stack) + State.Column - 1 >435getColumnLimit(State)) {436return true;437}438439const FormatToken &BreakConstructorInitializersToken =440Style.BreakConstructorInitializers == FormatStyle::BCIS_AfterColon441? Previous442: Current;443if (BreakConstructorInitializersToken.is(TT_CtorInitializerColon) &&444(State.Column + State.Line->Last->TotalLength - Previous.TotalLength >445getColumnLimit(State) ||446CurrentState.BreakBeforeParameter) &&447(!Current.isTrailingComment() || Current.NewlinesBefore > 0) &&448(Style.AllowShortFunctionsOnASingleLine != FormatStyle::SFS_All ||449Style.BreakConstructorInitializers != FormatStyle::BCIS_BeforeColon ||450Style.ColumnLimit != 0)) {451return true;452}453454if (Current.is(TT_ObjCMethodExpr) && Previous.isNot(TT_SelectorName) &&455State.Line->startsWith(TT_ObjCMethodSpecifier)) {456return true;457}458if (Current.is(TT_SelectorName) && Previous.isNot(tok::at) &&459CurrentState.ObjCSelectorNameFound && CurrentState.BreakBeforeParameter &&460(Style.ObjCBreakBeforeNestedBlockParam ||461!Current.startsSequence(TT_SelectorName, tok::colon, tok::caret))) {462return true;463}464465unsigned NewLineColumn = getNewLineColumn(State);466if (Current.isMemberAccess() && Style.ColumnLimit != 0 &&467State.Column + getLengthToNextOperator(Current) > Style.ColumnLimit &&468(State.Column > NewLineColumn ||469Current.NestingLevel < State.StartOfLineLevel)) {470return true;471}472473if (startsSegmentOfBuilderTypeCall(Current) &&474(CurrentState.CallContinuation != 0 ||475CurrentState.BreakBeforeParameter) &&476// JavaScript is treated different here as there is a frequent pattern:477// SomeFunction(function() {478// ...479// }.bind(...));480// FIXME: We should find a more generic solution to this problem.481!(State.Column <= NewLineColumn && Style.isJavaScript()) &&482!(Previous.closesScopeAfterBlock() && State.Column <= NewLineColumn)) {483return true;484}485486// If the template declaration spans multiple lines, force wrap before the487// function/class declaration.488if (Previous.ClosesTemplateDeclaration && CurrentState.BreakBeforeParameter &&489Current.CanBreakBefore) {490return true;491}492493if (State.Line->First->isNot(tok::kw_enum) && State.Column <= NewLineColumn)494return false;495496if (Style.AlwaysBreakBeforeMultilineStrings &&497(NewLineColumn == State.FirstIndent + Style.ContinuationIndentWidth ||498Previous.is(tok::comma) || Current.NestingLevel < 2) &&499!Previous.isOneOf(tok::kw_return, tok::lessless, tok::at,500Keywords.kw_dollar) &&501!Previous.isOneOf(TT_InlineASMColon, TT_ConditionalExpr) &&502nextIsMultilineString(State)) {503return true;504}505506// Using CanBreakBefore here and below takes care of the decision whether the507// current style uses wrapping before or after operators for the given508// operator.509if (Previous.is(TT_BinaryOperator) && Current.CanBreakBefore) {510const auto PreviousPrecedence = Previous.getPrecedence();511if (PreviousPrecedence != prec::Assignment &&512CurrentState.BreakBeforeParameter && !Current.isTrailingComment()) {513const bool LHSIsBinaryExpr =514Previous.Previous && Previous.Previous->EndsBinaryExpression;515if (LHSIsBinaryExpr)516return true;517// If we need to break somewhere inside the LHS of a binary expression, we518// should also break after the operator. Otherwise, the formatting would519// hide the operator precedence, e.g. in:520// if (aaaaaaaaaaaaaa ==521// bbbbbbbbbbbbbb && c) {..522// For comparisons, we only apply this rule, if the LHS is a binary523// expression itself as otherwise, the line breaks seem superfluous.524// We need special cases for ">>" which we have split into two ">" while525// lexing in order to make template parsing easier.526const bool IsComparison =527(PreviousPrecedence == prec::Relational ||528PreviousPrecedence == prec::Equality ||529PreviousPrecedence == prec::Spaceship) &&530Previous.Previous &&531Previous.Previous->isNot(TT_BinaryOperator); // For >>.532if (!IsComparison)533return true;534}535} else if (Current.is(TT_BinaryOperator) && Current.CanBreakBefore &&536CurrentState.BreakBeforeParameter) {537return true;538}539540// Same as above, but for the first "<<" operator.541if (Current.is(tok::lessless) && Current.isNot(TT_OverloadedOperator) &&542CurrentState.BreakBeforeParameter && CurrentState.FirstLessLess == 0) {543return true;544}545546if (Current.NestingLevel == 0 && !Current.isTrailingComment()) {547// Always break after "template <...>"(*) and leading annotations. This is548// only for cases where the entire line does not fit on a single line as a549// different LineFormatter would be used otherwise.550// *: Except when another option interferes with that, like concepts.551if (Previous.ClosesTemplateDeclaration) {552if (Current.is(tok::kw_concept)) {553switch (Style.BreakBeforeConceptDeclarations) {554case FormatStyle::BBCDS_Allowed:555break;556case FormatStyle::BBCDS_Always:557return true;558case FormatStyle::BBCDS_Never:559return false;560}561}562if (Current.is(TT_RequiresClause)) {563switch (Style.RequiresClausePosition) {564case FormatStyle::RCPS_SingleLine:565case FormatStyle::RCPS_WithPreceding:566return false;567default:568return true;569}570}571return Style.BreakTemplateDeclarations != FormatStyle::BTDS_No &&572(Style.BreakTemplateDeclarations != FormatStyle::BTDS_Leave ||573Current.NewlinesBefore > 0);574}575if (Previous.is(TT_FunctionAnnotationRParen) &&576State.Line->Type != LT_PreprocessorDirective) {577return true;578}579if (Previous.is(TT_LeadingJavaAnnotation) && Current.isNot(tok::l_paren) &&580Current.isNot(TT_LeadingJavaAnnotation)) {581return true;582}583}584585if (Style.isJavaScript() && Previous.is(tok::r_paren) &&586Previous.is(TT_JavaAnnotation)) {587// Break after the closing parenthesis of TypeScript decorators before588// functions, getters and setters.589static const llvm::StringSet<> BreakBeforeDecoratedTokens = {"get", "set",590"function"};591if (BreakBeforeDecoratedTokens.contains(Current.TokenText))592return true;593}594595if (Current.is(TT_FunctionDeclarationName) &&596!State.Line->ReturnTypeWrapped &&597// Don't break before a C# function when no break after return type.598(!Style.isCSharp() ||599Style.BreakAfterReturnType > FormatStyle::RTBS_ExceptShortType) &&600// Don't always break between a JavaScript `function` and the function601// name.602!Style.isJavaScript() && Previous.isNot(tok::kw_template) &&603CurrentState.BreakBeforeParameter) {604return true;605}606607// The following could be precomputed as they do not depend on the state.608// However, as they should take effect only if the UnwrappedLine does not fit609// into the ColumnLimit, they are checked here in the ContinuationIndenter.610if (Style.ColumnLimit != 0 && Previous.is(BK_Block) &&611Previous.is(tok::l_brace) &&612!Current.isOneOf(tok::r_brace, tok::comment)) {613return true;614}615616if (Current.is(tok::lessless) &&617((Previous.is(tok::identifier) && Previous.TokenText == "endl") ||618(Previous.Tok.isLiteral() && (Previous.TokenText.ends_with("\\n\"") ||619Previous.TokenText == "\'\\n\'")))) {620return true;621}622623if (Previous.is(TT_BlockComment) && Previous.IsMultiline)624return true;625626if (State.NoContinuation)627return true;628629return false;630}631632unsigned ContinuationIndenter::addTokenToState(LineState &State, bool Newline,633bool DryRun,634unsigned ExtraSpaces) {635const FormatToken &Current = *State.NextToken;636assert(State.NextToken->Previous);637const FormatToken &Previous = *State.NextToken->Previous;638639assert(!State.Stack.empty());640State.NoContinuation = false;641642if (Current.is(TT_ImplicitStringLiteral) &&643(!Previous.Tok.getIdentifierInfo() ||644Previous.Tok.getIdentifierInfo()->getPPKeywordID() ==645tok::pp_not_keyword)) {646unsigned EndColumn =647SourceMgr.getSpellingColumnNumber(Current.WhitespaceRange.getEnd());648if (Current.LastNewlineOffset != 0) {649// If there is a newline within this token, the final column will solely650// determined by the current end column.651State.Column = EndColumn;652} else {653unsigned StartColumn =654SourceMgr.getSpellingColumnNumber(Current.WhitespaceRange.getBegin());655assert(EndColumn >= StartColumn);656State.Column += EndColumn - StartColumn;657}658moveStateToNextToken(State, DryRun, /*Newline=*/false);659return 0;660}661662unsigned Penalty = 0;663if (Newline)664Penalty = addTokenOnNewLine(State, DryRun);665else666addTokenOnCurrentLine(State, DryRun, ExtraSpaces);667668return moveStateToNextToken(State, DryRun, Newline) + Penalty;669}670671void ContinuationIndenter::addTokenOnCurrentLine(LineState &State, bool DryRun,672unsigned ExtraSpaces) {673FormatToken &Current = *State.NextToken;674assert(State.NextToken->Previous);675const FormatToken &Previous = *State.NextToken->Previous;676auto &CurrentState = State.Stack.back();677678bool DisallowLineBreaksOnThisLine =679Style.LambdaBodyIndentation == FormatStyle::LBI_Signature &&680Style.isCpp() && [&Current] {681// Deal with lambda arguments in C++. The aim here is to ensure that we682// don't over-indent lambda function bodies when lambdas are passed as683// arguments to function calls. We do this by ensuring that either all684// arguments (including any lambdas) go on the same line as the function685// call, or we break before the first argument.686const auto *Prev = Current.Previous;687if (!Prev)688return false;689// For example, `/*Newline=*/false`.690if (Prev->is(TT_BlockComment) && Current.SpacesRequiredBefore == 0)691return false;692const auto *PrevNonComment = Current.getPreviousNonComment();693if (!PrevNonComment || PrevNonComment->isNot(tok::l_paren))694return false;695if (Current.isOneOf(tok::comment, tok::l_paren, TT_LambdaLSquare))696return false;697auto BlockParameterCount = PrevNonComment->BlockParameterCount;698if (BlockParameterCount == 0)699return false;700701// Multiple lambdas in the same function call.702if (BlockParameterCount > 1)703return true;704705// A lambda followed by another arg.706if (!PrevNonComment->Role)707return false;708auto Comma = PrevNonComment->Role->lastComma();709if (!Comma)710return false;711auto Next = Comma->getNextNonComment();712return Next &&713!Next->isOneOf(TT_LambdaLSquare, tok::l_brace, tok::caret);714}();715716if (DisallowLineBreaksOnThisLine)717State.NoLineBreak = true;718719if (Current.is(tok::equal) &&720(State.Line->First->is(tok::kw_for) || Current.NestingLevel == 0) &&721CurrentState.VariablePos == 0 &&722(!Previous.Previous ||723Previous.Previous->isNot(TT_DesignatedInitializerPeriod))) {724CurrentState.VariablePos = State.Column;725// Move over * and & if they are bound to the variable name.726const FormatToken *Tok = &Previous;727while (Tok && CurrentState.VariablePos >= Tok->ColumnWidth) {728CurrentState.VariablePos -= Tok->ColumnWidth;729if (Tok->SpacesRequiredBefore != 0)730break;731Tok = Tok->Previous;732}733if (Previous.PartOfMultiVariableDeclStmt)734CurrentState.LastSpace = CurrentState.VariablePos;735}736737unsigned Spaces = Current.SpacesRequiredBefore + ExtraSpaces;738739// Indent preprocessor directives after the hash if required.740int PPColumnCorrection = 0;741if (Style.IndentPPDirectives == FormatStyle::PPDIS_AfterHash &&742Previous.is(tok::hash) && State.FirstIndent > 0 &&743&Previous == State.Line->First &&744(State.Line->Type == LT_PreprocessorDirective ||745State.Line->Type == LT_ImportStatement)) {746Spaces += State.FirstIndent;747748// For preprocessor indent with tabs, State.Column will be 1 because of the749// hash. This causes second-level indents onward to have an extra space750// after the tabs. We avoid this misalignment by subtracting 1 from the751// column value passed to replaceWhitespace().752if (Style.UseTab != FormatStyle::UT_Never)753PPColumnCorrection = -1;754}755756if (!DryRun) {757Whitespaces.replaceWhitespace(Current, /*Newlines=*/0, Spaces,758State.Column + Spaces + PPColumnCorrection,759/*IsAligned=*/false, State.Line->InMacroBody);760}761762// If "BreakBeforeInheritanceComma" mode, don't break within the inheritance763// declaration unless there is multiple inheritance.764if (Style.BreakInheritanceList == FormatStyle::BILS_BeforeComma &&765Current.is(TT_InheritanceColon)) {766CurrentState.NoLineBreak = true;767}768if (Style.BreakInheritanceList == FormatStyle::BILS_AfterColon &&769Previous.is(TT_InheritanceColon)) {770CurrentState.NoLineBreak = true;771}772773if (Current.is(TT_SelectorName) && !CurrentState.ObjCSelectorNameFound) {774unsigned MinIndent = std::max(775State.FirstIndent + Style.ContinuationIndentWidth, CurrentState.Indent);776unsigned FirstColonPos = State.Column + Spaces + Current.ColumnWidth;777if (Current.LongestObjCSelectorName == 0)778CurrentState.AlignColons = false;779else if (MinIndent + Current.LongestObjCSelectorName > FirstColonPos)780CurrentState.ColonPos = MinIndent + Current.LongestObjCSelectorName;781else782CurrentState.ColonPos = FirstColonPos;783}784785// In "AlwaysBreak" or "BlockIndent" mode, enforce wrapping directly after the786// parenthesis by disallowing any further line breaks if there is no line787// break after the opening parenthesis. Don't break if it doesn't conserve788// columns.789auto IsOpeningBracket = [&](const FormatToken &Tok) {790auto IsStartOfBracedList = [&]() {791return Tok.is(tok::l_brace) && Tok.isNot(BK_Block) &&792Style.Cpp11BracedListStyle;793};794if (!Tok.isOneOf(tok::l_paren, TT_TemplateOpener, tok::l_square) &&795!IsStartOfBracedList()) {796return false;797}798if (!Tok.Previous)799return true;800if (Tok.Previous->isIf())801return Style.AlignAfterOpenBracket == FormatStyle::BAS_AlwaysBreak;802return !Tok.Previous->isOneOf(TT_CastRParen, tok::kw_for, tok::kw_while,803tok::kw_switch);804};805if ((Style.AlignAfterOpenBracket == FormatStyle::BAS_AlwaysBreak ||806Style.AlignAfterOpenBracket == FormatStyle::BAS_BlockIndent) &&807IsOpeningBracket(Previous) && State.Column > getNewLineColumn(State) &&808// Don't do this for simple (no expressions) one-argument function calls809// as that feels like needlessly wasting whitespace, e.g.:810//811// caaaaaaaaaaaall(812// caaaaaaaaaaaall(813// caaaaaaaaaaaall(814// caaaaaaaaaaaaaaaaaaaaaaall(aaaaaaaaaaaaaa, aaaaaaaaa))));815Current.FakeLParens.size() > 0 &&816Current.FakeLParens.back() > prec::Unknown) {817CurrentState.NoLineBreak = true;818}819if (Previous.is(TT_TemplateString) && Previous.opensScope())820CurrentState.NoLineBreak = true;821822// Align following lines within parentheses / brackets if configured.823// Note: This doesn't apply to macro expansion lines, which are MACRO( , , )824// with args as children of the '(' and ',' tokens. It does not make sense to825// align the commas with the opening paren.826if (Style.AlignAfterOpenBracket != FormatStyle::BAS_DontAlign &&827!CurrentState.IsCSharpGenericTypeConstraint && Previous.opensScope() &&828Previous.isNot(TT_ObjCMethodExpr) && Previous.isNot(TT_RequiresClause) &&829Previous.isNot(TT_TableGenDAGArgOpener) &&830Previous.isNot(TT_TableGenDAGArgOpenerToBreak) &&831!(Current.MacroParent && Previous.MacroParent) &&832(Current.isNot(TT_LineComment) ||833Previous.isOneOf(BK_BracedInit, TT_VerilogMultiLineListLParen))) {834CurrentState.Indent = State.Column + Spaces;835CurrentState.IsAligned = true;836}837if (CurrentState.AvoidBinPacking && startsNextParameter(Current, Style))838CurrentState.NoLineBreak = true;839if (startsSegmentOfBuilderTypeCall(Current) &&840State.Column > getNewLineColumn(State)) {841CurrentState.ContainsUnwrappedBuilder = true;842}843844if (Current.is(TT_LambdaArrow) && Style.Language == FormatStyle::LK_Java)845CurrentState.NoLineBreak = true;846if (Current.isMemberAccess() && Previous.is(tok::r_paren) &&847(Previous.MatchingParen &&848(Previous.TotalLength - Previous.MatchingParen->TotalLength > 10))) {849// If there is a function call with long parameters, break before trailing850// calls. This prevents things like:851// EXPECT_CALL(SomeLongParameter).Times(852// 2);853// We don't want to do this for short parameters as they can just be854// indexes.855CurrentState.NoLineBreak = true;856}857858// Don't allow the RHS of an operator to be split over multiple lines unless859// there is a line-break right after the operator.860// Exclude relational operators, as there, it is always more desirable to861// have the LHS 'left' of the RHS.862const FormatToken *P = Current.getPreviousNonComment();863if (Current.isNot(tok::comment) && P &&864(P->isOneOf(TT_BinaryOperator, tok::comma) ||865(P->is(TT_ConditionalExpr) && P->is(tok::colon))) &&866!P->isOneOf(TT_OverloadedOperator, TT_CtorInitializerComma) &&867P->getPrecedence() != prec::Assignment &&868P->getPrecedence() != prec::Relational &&869P->getPrecedence() != prec::Spaceship) {870bool BreakBeforeOperator =871P->MustBreakBefore || P->is(tok::lessless) ||872(P->is(TT_BinaryOperator) &&873Style.BreakBeforeBinaryOperators != FormatStyle::BOS_None) ||874(P->is(TT_ConditionalExpr) && Style.BreakBeforeTernaryOperators);875// Don't do this if there are only two operands. In these cases, there is876// always a nice vertical separation between them and the extra line break877// does not help.878bool HasTwoOperands = P->OperatorIndex == 0 && !P->NextOperator &&879P->isNot(TT_ConditionalExpr);880if ((!BreakBeforeOperator &&881!(HasTwoOperands &&882Style.AlignOperands != FormatStyle::OAS_DontAlign)) ||883(!CurrentState.LastOperatorWrapped && BreakBeforeOperator)) {884CurrentState.NoLineBreakInOperand = true;885}886}887888State.Column += Spaces;889if (Current.isNot(tok::comment) && Previous.is(tok::l_paren) &&890Previous.Previous &&891(Previous.Previous->is(tok::kw_for) || Previous.Previous->isIf())) {892// Treat the condition inside an if as if it was a second function893// parameter, i.e. let nested calls have a continuation indent.894CurrentState.LastSpace = State.Column;895CurrentState.NestedBlockIndent = State.Column;896} else if (!Current.isOneOf(tok::comment, tok::caret) &&897((Previous.is(tok::comma) &&898Previous.isNot(TT_OverloadedOperator)) ||899(Previous.is(tok::colon) && Previous.is(TT_ObjCMethodExpr)))) {900CurrentState.LastSpace = State.Column;901} else if (Previous.is(TT_CtorInitializerColon) &&902(!Current.isTrailingComment() || Current.NewlinesBefore > 0) &&903Style.BreakConstructorInitializers ==904FormatStyle::BCIS_AfterColon) {905CurrentState.Indent = State.Column;906CurrentState.LastSpace = State.Column;907} else if (Previous.isOneOf(TT_ConditionalExpr, TT_CtorInitializerColon)) {908CurrentState.LastSpace = State.Column;909} else if (Previous.is(TT_BinaryOperator) &&910((Previous.getPrecedence() != prec::Assignment &&911(Previous.isNot(tok::lessless) || Previous.OperatorIndex != 0 ||912Previous.NextOperator)) ||913Current.StartsBinaryExpression)) {914// Indent relative to the RHS of the expression unless this is a simple915// assignment without binary expression on the RHS.916if (Style.BreakBeforeBinaryOperators == FormatStyle::BOS_None)917CurrentState.LastSpace = State.Column;918} else if (Previous.is(TT_InheritanceColon)) {919CurrentState.Indent = State.Column;920CurrentState.LastSpace = State.Column;921} else if (Current.is(TT_CSharpGenericTypeConstraintColon)) {922CurrentState.ColonPos = State.Column;923} else if (Previous.opensScope()) {924// If a function has a trailing call, indent all parameters from the925// opening parenthesis. This avoids confusing indents like:926// OuterFunction(InnerFunctionCall( // break927// ParameterToInnerFunction)) // break928// .SecondInnerFunctionCall();929if (Previous.MatchingParen) {930const FormatToken *Next = Previous.MatchingParen->getNextNonComment();931if (Next && Next->isMemberAccess() && State.Stack.size() > 1 &&932State.Stack[State.Stack.size() - 2].CallContinuation == 0) {933CurrentState.LastSpace = State.Column;934}935}936}937}938939unsigned ContinuationIndenter::addTokenOnNewLine(LineState &State,940bool DryRun) {941FormatToken &Current = *State.NextToken;942assert(State.NextToken->Previous);943const FormatToken &Previous = *State.NextToken->Previous;944auto &CurrentState = State.Stack.back();945946// Extra penalty that needs to be added because of the way certain line947// breaks are chosen.948unsigned Penalty = 0;949950const FormatToken *PreviousNonComment = Current.getPreviousNonComment();951const FormatToken *NextNonComment = Previous.getNextNonComment();952if (!NextNonComment)953NextNonComment = &Current;954// The first line break on any NestingLevel causes an extra penalty in order955// prefer similar line breaks.956if (!CurrentState.ContainsLineBreak)957Penalty += 15;958CurrentState.ContainsLineBreak = true;959960Penalty += State.NextToken->SplitPenalty;961962// Breaking before the first "<<" is generally not desirable if the LHS is963// short. Also always add the penalty if the LHS is split over multiple lines964// to avoid unnecessary line breaks that just work around this penalty.965if (NextNonComment->is(tok::lessless) && CurrentState.FirstLessLess == 0 &&966(State.Column <= Style.ColumnLimit / 3 ||967CurrentState.BreakBeforeParameter)) {968Penalty += Style.PenaltyBreakFirstLessLess;969}970971State.Column = getNewLineColumn(State);972973// Add Penalty proportional to amount of whitespace away from FirstColumn974// This tends to penalize several lines that are far-right indented,975// and prefers a line-break prior to such a block, e.g:976//977// Constructor() :978// member(value), looooooooooooooooong_member(979// looooooooooong_call(param_1, param_2, param_3))980// would then become981// Constructor() :982// member(value),983// looooooooooooooooong_member(984// looooooooooong_call(param_1, param_2, param_3))985if (State.Column > State.FirstIndent) {986Penalty +=987Style.PenaltyIndentedWhitespace * (State.Column - State.FirstIndent);988}989990// Indent nested blocks relative to this column, unless in a very specific991// JavaScript special case where:992//993// var loooooong_name =994// function() {995// // code996// }997//998// is common and should be formatted like a free-standing function. The same999// goes for wrapping before the lambda return type arrow.1000if (Current.isNot(TT_LambdaArrow) &&1001(!Style.isJavaScript() || Current.NestingLevel != 0 ||1002!PreviousNonComment || PreviousNonComment->isNot(tok::equal) ||1003!Current.isOneOf(Keywords.kw_async, Keywords.kw_function))) {1004CurrentState.NestedBlockIndent = State.Column;1005}10061007if (NextNonComment->isMemberAccess()) {1008if (CurrentState.CallContinuation == 0)1009CurrentState.CallContinuation = State.Column;1010} else if (NextNonComment->is(TT_SelectorName)) {1011if (!CurrentState.ObjCSelectorNameFound) {1012if (NextNonComment->LongestObjCSelectorName == 0) {1013CurrentState.AlignColons = false;1014} else {1015CurrentState.ColonPos =1016(shouldIndentWrappedSelectorName(Style, State.Line->Type)1017? std::max(CurrentState.Indent,1018State.FirstIndent + Style.ContinuationIndentWidth)1019: CurrentState.Indent) +1020std::max(NextNonComment->LongestObjCSelectorName,1021NextNonComment->ColumnWidth);1022}1023} else if (CurrentState.AlignColons &&1024CurrentState.ColonPos <= NextNonComment->ColumnWidth) {1025CurrentState.ColonPos = State.Column + NextNonComment->ColumnWidth;1026}1027} else if (PreviousNonComment && PreviousNonComment->is(tok::colon) &&1028PreviousNonComment->isOneOf(TT_ObjCMethodExpr, TT_DictLiteral)) {1029// FIXME: This is hacky, find a better way. The problem is that in an ObjC1030// method expression, the block should be aligned to the line starting it,1031// e.g.:1032// [aaaaaaaaaaaaaaa aaaaaaaaa: \\ break for some reason1033// ^(int *i) {1034// // ...1035// }];1036// Thus, we set LastSpace of the next higher NestingLevel, to which we move1037// when we consume all of the "}"'s FakeRParens at the "{".1038if (State.Stack.size() > 1) {1039State.Stack[State.Stack.size() - 2].LastSpace =1040std::max(CurrentState.LastSpace, CurrentState.Indent) +1041Style.ContinuationIndentWidth;1042}1043}10441045if ((PreviousNonComment &&1046PreviousNonComment->isOneOf(tok::comma, tok::semi) &&1047!CurrentState.AvoidBinPacking) ||1048Previous.is(TT_BinaryOperator)) {1049CurrentState.BreakBeforeParameter = false;1050}1051if (PreviousNonComment &&1052(PreviousNonComment->isOneOf(TT_TemplateCloser, TT_JavaAnnotation) ||1053PreviousNonComment->ClosesRequiresClause) &&1054Current.NestingLevel == 0) {1055CurrentState.BreakBeforeParameter = false;1056}1057if (NextNonComment->is(tok::question) ||1058(PreviousNonComment && PreviousNonComment->is(tok::question))) {1059CurrentState.BreakBeforeParameter = true;1060}1061if (Current.is(TT_BinaryOperator) && Current.CanBreakBefore)1062CurrentState.BreakBeforeParameter = false;10631064if (!DryRun) {1065unsigned MaxEmptyLinesToKeep = Style.MaxEmptyLinesToKeep + 1;1066if (Current.is(tok::r_brace) && Current.MatchingParen &&1067// Only strip trailing empty lines for l_braces that have children, i.e.1068// for function expressions (lambdas, arrows, etc).1069!Current.MatchingParen->Children.empty()) {1070// lambdas and arrow functions are expressions, thus their r_brace is not1071// on its own line, and thus not covered by UnwrappedLineFormatter's logic1072// about removing empty lines on closing blocks. Special case them here.1073MaxEmptyLinesToKeep = 1;1074}1075unsigned Newlines =1076std::max(1u, std::min(Current.NewlinesBefore, MaxEmptyLinesToKeep));1077bool ContinuePPDirective =1078State.Line->InPPDirective && State.Line->Type != LT_ImportStatement;1079Whitespaces.replaceWhitespace(Current, Newlines, State.Column, State.Column,1080CurrentState.IsAligned, ContinuePPDirective);1081}10821083if (!Current.isTrailingComment())1084CurrentState.LastSpace = State.Column;1085if (Current.is(tok::lessless)) {1086// If we are breaking before a "<<", we always want to indent relative to1087// RHS. This is necessary only for "<<", as we special-case it and don't1088// always indent relative to the RHS.1089CurrentState.LastSpace += 3; // 3 -> width of "<< ".1090}10911092State.StartOfLineLevel = Current.NestingLevel;1093State.LowestLevelOnLine = Current.NestingLevel;10941095// Any break on this level means that the parent level has been broken1096// and we need to avoid bin packing there.1097bool NestedBlockSpecialCase =1098(!Style.isCpp() && Current.is(tok::r_brace) && State.Stack.size() > 1 &&1099State.Stack[State.Stack.size() - 2].NestedBlockInlined) ||1100(Style.Language == FormatStyle::LK_ObjC && Current.is(tok::r_brace) &&1101State.Stack.size() > 1 && !Style.ObjCBreakBeforeNestedBlockParam);1102// Do not force parameter break for statements with requires expressions.1103NestedBlockSpecialCase =1104NestedBlockSpecialCase ||1105(Current.MatchingParen &&1106Current.MatchingParen->is(TT_RequiresExpressionLBrace));1107if (!NestedBlockSpecialCase) {1108auto ParentLevelIt = std::next(State.Stack.rbegin());1109if (Style.LambdaBodyIndentation == FormatStyle::LBI_OuterScope &&1110Current.MatchingParen && Current.MatchingParen->is(TT_LambdaLBrace)) {1111// If the first character on the new line is a lambda's closing brace, the1112// stack still contains that lambda's parenthesis. As such, we need to1113// recurse further down the stack than usual to find the parenthesis level1114// containing the lambda, which is where we want to set1115// BreakBeforeParameter.1116//1117// We specifically special case "OuterScope"-formatted lambdas here1118// because, when using that setting, breaking before the parameter1119// directly following the lambda is particularly unsightly. However, when1120// "OuterScope" is not set, the logic to find the parent parenthesis level1121// still appears to be sometimes incorrect. It has not been fixed yet1122// because it would lead to significant changes in existing behaviour.1123//1124// TODO: fix the non-"OuterScope" case too.1125auto FindCurrentLevel = [&](const auto &It) {1126return std::find_if(It, State.Stack.rend(), [](const auto &PState) {1127return PState.Tok != nullptr; // Ignore fake parens.1128});1129};1130auto MaybeIncrement = [&](const auto &It) {1131return It != State.Stack.rend() ? std::next(It) : It;1132};1133auto LambdaLevelIt = FindCurrentLevel(State.Stack.rbegin());1134auto LevelContainingLambdaIt =1135FindCurrentLevel(MaybeIncrement(LambdaLevelIt));1136ParentLevelIt = MaybeIncrement(LevelContainingLambdaIt);1137}1138for (auto I = ParentLevelIt, E = State.Stack.rend(); I != E; ++I)1139I->BreakBeforeParameter = true;1140}11411142if (PreviousNonComment &&1143!PreviousNonComment->isOneOf(tok::comma, tok::colon, tok::semi) &&1144((PreviousNonComment->isNot(TT_TemplateCloser) &&1145!PreviousNonComment->ClosesRequiresClause) ||1146Current.NestingLevel != 0) &&1147!PreviousNonComment->isOneOf(1148TT_BinaryOperator, TT_FunctionAnnotationRParen, TT_JavaAnnotation,1149TT_LeadingJavaAnnotation) &&1150Current.isNot(TT_BinaryOperator) && !PreviousNonComment->opensScope() &&1151// We don't want to enforce line breaks for subsequent arguments just1152// because we have been forced to break before a lambda body.1153(!Style.BraceWrapping.BeforeLambdaBody ||1154Current.isNot(TT_LambdaLBrace))) {1155CurrentState.BreakBeforeParameter = true;1156}11571158// If we break after { or the [ of an array initializer, we should also break1159// before the corresponding } or ].1160if (PreviousNonComment &&1161(PreviousNonComment->isOneOf(tok::l_brace, TT_ArrayInitializerLSquare) ||1162opensProtoMessageField(*PreviousNonComment, Style))) {1163CurrentState.BreakBeforeClosingBrace = true;1164}11651166if (PreviousNonComment && PreviousNonComment->is(tok::l_paren)) {1167CurrentState.BreakBeforeClosingParen =1168Style.AlignAfterOpenBracket == FormatStyle::BAS_BlockIndent;1169}11701171if (CurrentState.AvoidBinPacking) {1172// If we are breaking after '(', '{', '<', or this is the break after a ':'1173// to start a member initializer list in a constructor, this should not1174// be considered bin packing unless the relevant AllowAll option is false or1175// this is a dict/object literal.1176bool PreviousIsBreakingCtorInitializerColon =1177PreviousNonComment && PreviousNonComment->is(TT_CtorInitializerColon) &&1178Style.BreakConstructorInitializers == FormatStyle::BCIS_AfterColon;1179bool AllowAllConstructorInitializersOnNextLine =1180Style.PackConstructorInitializers == FormatStyle::PCIS_NextLine ||1181Style.PackConstructorInitializers == FormatStyle::PCIS_NextLineOnly;1182if (!(Previous.isOneOf(tok::l_paren, tok::l_brace, TT_BinaryOperator) ||1183PreviousIsBreakingCtorInitializerColon) ||1184(!Style.AllowAllParametersOfDeclarationOnNextLine &&1185State.Line->MustBeDeclaration) ||1186(!Style.AllowAllArgumentsOnNextLine &&1187!State.Line->MustBeDeclaration) ||1188(!AllowAllConstructorInitializersOnNextLine &&1189PreviousIsBreakingCtorInitializerColon) ||1190Previous.is(TT_DictLiteral)) {1191CurrentState.BreakBeforeParameter = true;1192}11931194// If we are breaking after a ':' to start a member initializer list,1195// and we allow all arguments on the next line, we should not break1196// before the next parameter.1197if (PreviousIsBreakingCtorInitializerColon &&1198AllowAllConstructorInitializersOnNextLine) {1199CurrentState.BreakBeforeParameter = false;1200}1201}12021203return Penalty;1204}12051206unsigned ContinuationIndenter::getNewLineColumn(const LineState &State) {1207if (!State.NextToken || !State.NextToken->Previous)1208return 0;12091210FormatToken &Current = *State.NextToken;1211const auto &CurrentState = State.Stack.back();12121213if (CurrentState.IsCSharpGenericTypeConstraint &&1214Current.isNot(TT_CSharpGenericTypeConstraint)) {1215return CurrentState.ColonPos + 2;1216}12171218const FormatToken &Previous = *Current.Previous;1219// If we are continuing an expression, we want to use the continuation indent.1220unsigned ContinuationIndent =1221std::max(CurrentState.LastSpace, CurrentState.Indent) +1222Style.ContinuationIndentWidth;1223const FormatToken *PreviousNonComment = Current.getPreviousNonComment();1224const FormatToken *NextNonComment = Previous.getNextNonComment();1225if (!NextNonComment)1226NextNonComment = &Current;12271228// Java specific bits.1229if (Style.Language == FormatStyle::LK_Java &&1230Current.isOneOf(Keywords.kw_implements, Keywords.kw_extends)) {1231return std::max(CurrentState.LastSpace,1232CurrentState.Indent + Style.ContinuationIndentWidth);1233}12341235// Indentation of the statement following a Verilog case label is taken care1236// of in moveStateToNextToken.1237if (Style.isVerilog() && PreviousNonComment &&1238Keywords.isVerilogEndOfLabel(*PreviousNonComment)) {1239return State.FirstIndent;1240}12411242if (Style.BreakBeforeBraces == FormatStyle::BS_Whitesmiths &&1243State.Line->First->is(tok::kw_enum)) {1244return (Style.IndentWidth * State.Line->First->IndentLevel) +1245Style.IndentWidth;1246}12471248if ((NextNonComment->is(tok::l_brace) && NextNonComment->is(BK_Block)) ||1249(Style.isVerilog() && Keywords.isVerilogBegin(*NextNonComment))) {1250if (Current.NestingLevel == 0 ||1251(Style.LambdaBodyIndentation == FormatStyle::LBI_OuterScope &&1252State.NextToken->is(TT_LambdaLBrace))) {1253return State.FirstIndent;1254}1255return CurrentState.Indent;1256}1257if (Current.is(TT_LambdaArrow) &&1258Previous.isOneOf(tok::kw_noexcept, tok::kw_mutable, tok::kw_constexpr,1259tok::kw_consteval, tok::kw_static, TT_AttributeSquare)) {1260return ContinuationIndent;1261}1262if ((Current.isOneOf(tok::r_brace, tok::r_square) ||1263(Current.is(tok::greater) && (Style.isProto() || Style.isTableGen()))) &&1264State.Stack.size() > 1) {1265if (Current.closesBlockOrBlockTypeList(Style))1266return State.Stack[State.Stack.size() - 2].NestedBlockIndent;1267if (Current.MatchingParen && Current.MatchingParen->is(BK_BracedInit))1268return State.Stack[State.Stack.size() - 2].LastSpace;1269return State.FirstIndent;1270}1271// Indent a closing parenthesis at the previous level if followed by a semi,1272// const, or opening brace. This allows indentations such as:1273// foo(1274// a,1275// );1276// int Foo::getter(1277// //1278// ) const {1279// return foo;1280// }1281// function foo(1282// a,1283// ) {1284// code(); //1285// }1286if (Current.is(tok::r_paren) && State.Stack.size() > 1 &&1287(!Current.Next ||1288Current.Next->isOneOf(tok::semi, tok::kw_const, tok::l_brace))) {1289return State.Stack[State.Stack.size() - 2].LastSpace;1290}1291// When DAGArg closer exists top of line, it should be aligned in the similar1292// way as function call above.1293if (Style.isTableGen() && Current.is(TT_TableGenDAGArgCloser) &&1294State.Stack.size() > 1) {1295return State.Stack[State.Stack.size() - 2].LastSpace;1296}1297if (Style.AlignAfterOpenBracket == FormatStyle::BAS_BlockIndent &&1298(Current.is(tok::r_paren) ||1299(Current.is(tok::r_brace) && Current.MatchingParen &&1300Current.MatchingParen->is(BK_BracedInit))) &&1301State.Stack.size() > 1) {1302return State.Stack[State.Stack.size() - 2].LastSpace;1303}1304if (NextNonComment->is(TT_TemplateString) && NextNonComment->closesScope())1305return State.Stack[State.Stack.size() - 2].LastSpace;1306// Field labels in a nested type should be aligned to the brace. For example1307// in ProtoBuf:1308// optional int32 b = 2 [(foo_options) = {aaaaaaaaaaaaaaaaaaa: 123,1309// bbbbbbbbbbbbbbbbbbbbbbbb:"baz"}];1310// For Verilog, a quote following a brace is treated as an identifier. And1311// Both braces and colons get annotated as TT_DictLiteral. So we have to1312// check.1313if (Current.is(tok::identifier) && Current.Next &&1314(!Style.isVerilog() || Current.Next->is(tok::colon)) &&1315(Current.Next->is(TT_DictLiteral) ||1316(Style.isProto() && Current.Next->isOneOf(tok::less, tok::l_brace)))) {1317return CurrentState.Indent;1318}1319if (NextNonComment->is(TT_ObjCStringLiteral) &&1320State.StartOfStringLiteral != 0) {1321return State.StartOfStringLiteral - 1;1322}1323if (NextNonComment->isStringLiteral() && State.StartOfStringLiteral != 0)1324return State.StartOfStringLiteral;1325if (NextNonComment->is(tok::lessless) && CurrentState.FirstLessLess != 0)1326return CurrentState.FirstLessLess;1327if (NextNonComment->isMemberAccess()) {1328if (CurrentState.CallContinuation == 0)1329return ContinuationIndent;1330return CurrentState.CallContinuation;1331}1332if (CurrentState.QuestionColumn != 0 &&1333((NextNonComment->is(tok::colon) &&1334NextNonComment->is(TT_ConditionalExpr)) ||1335Previous.is(TT_ConditionalExpr))) {1336if (((NextNonComment->is(tok::colon) && NextNonComment->Next &&1337!NextNonComment->Next->FakeLParens.empty() &&1338NextNonComment->Next->FakeLParens.back() == prec::Conditional) ||1339(Previous.is(tok::colon) && !Current.FakeLParens.empty() &&1340Current.FakeLParens.back() == prec::Conditional)) &&1341!CurrentState.IsWrappedConditional) {1342// NOTE: we may tweak this slightly:1343// * not remove the 'lead' ContinuationIndentWidth1344// * always un-indent by the operator when1345// BreakBeforeTernaryOperators=true1346unsigned Indent = CurrentState.Indent;1347if (Style.AlignOperands != FormatStyle::OAS_DontAlign)1348Indent -= Style.ContinuationIndentWidth;1349if (Style.BreakBeforeTernaryOperators && CurrentState.UnindentOperator)1350Indent -= 2;1351return Indent;1352}1353return CurrentState.QuestionColumn;1354}1355if (Previous.is(tok::comma) && CurrentState.VariablePos != 0)1356return CurrentState.VariablePos;1357if (Current.is(TT_RequiresClause)) {1358if (Style.IndentRequiresClause)1359return CurrentState.Indent + Style.IndentWidth;1360switch (Style.RequiresClausePosition) {1361case FormatStyle::RCPS_OwnLine:1362case FormatStyle::RCPS_WithFollowing:1363return CurrentState.Indent;1364default:1365break;1366}1367}1368if (NextNonComment->isOneOf(TT_CtorInitializerColon, TT_InheritanceColon,1369TT_InheritanceComma)) {1370return State.FirstIndent + Style.ConstructorInitializerIndentWidth;1371}1372if ((PreviousNonComment &&1373(PreviousNonComment->ClosesTemplateDeclaration ||1374PreviousNonComment->ClosesRequiresClause ||1375(PreviousNonComment->is(TT_AttributeMacro) &&1376Current.isNot(tok::l_paren)) ||1377PreviousNonComment->isOneOf(1378TT_AttributeRParen, TT_AttributeSquare, TT_FunctionAnnotationRParen,1379TT_JavaAnnotation, TT_LeadingJavaAnnotation))) ||1380(!Style.IndentWrappedFunctionNames &&1381NextNonComment->isOneOf(tok::kw_operator, TT_FunctionDeclarationName))) {1382return std::max(CurrentState.LastSpace, CurrentState.Indent);1383}1384if (NextNonComment->is(TT_SelectorName)) {1385if (!CurrentState.ObjCSelectorNameFound) {1386unsigned MinIndent = CurrentState.Indent;1387if (shouldIndentWrappedSelectorName(Style, State.Line->Type)) {1388MinIndent = std::max(MinIndent,1389State.FirstIndent + Style.ContinuationIndentWidth);1390}1391// If LongestObjCSelectorName is 0, we are indenting the first1392// part of an ObjC selector (or a selector component which is1393// not colon-aligned due to block formatting).1394//1395// Otherwise, we are indenting a subsequent part of an ObjC1396// selector which should be colon-aligned to the longest1397// component of the ObjC selector.1398//1399// In either case, we want to respect Style.IndentWrappedFunctionNames.1400return MinIndent +1401std::max(NextNonComment->LongestObjCSelectorName,1402NextNonComment->ColumnWidth) -1403NextNonComment->ColumnWidth;1404}1405if (!CurrentState.AlignColons)1406return CurrentState.Indent;1407if (CurrentState.ColonPos > NextNonComment->ColumnWidth)1408return CurrentState.ColonPos - NextNonComment->ColumnWidth;1409return CurrentState.Indent;1410}1411if (NextNonComment->is(tok::colon) && NextNonComment->is(TT_ObjCMethodExpr))1412return CurrentState.ColonPos;1413if (NextNonComment->is(TT_ArraySubscriptLSquare)) {1414if (CurrentState.StartOfArraySubscripts != 0) {1415return CurrentState.StartOfArraySubscripts;1416} else if (Style.isCSharp()) { // C# allows `["key"] = value` inside object1417// initializers.1418return CurrentState.Indent;1419}1420return ContinuationIndent;1421}14221423// OpenMP clauses want to get additional indentation when they are pushed onto1424// the next line.1425if (State.Line->InPragmaDirective) {1426FormatToken *PragmaType = State.Line->First->Next->Next;1427if (PragmaType && PragmaType->TokenText == "omp")1428return CurrentState.Indent + Style.ContinuationIndentWidth;1429}14301431// This ensure that we correctly format ObjC methods calls without inputs,1432// i.e. where the last element isn't selector like: [callee method];1433if (NextNonComment->is(tok::identifier) && NextNonComment->FakeRParens == 0 &&1434NextNonComment->Next && NextNonComment->Next->is(TT_ObjCMethodExpr)) {1435return CurrentState.Indent;1436}14371438if (NextNonComment->isOneOf(TT_StartOfName, TT_PointerOrReference) ||1439Previous.isOneOf(tok::coloncolon, tok::equal, TT_JsTypeColon)) {1440return ContinuationIndent;1441}1442if (PreviousNonComment && PreviousNonComment->is(tok::colon) &&1443PreviousNonComment->isOneOf(TT_ObjCMethodExpr, TT_DictLiteral)) {1444return ContinuationIndent;1445}1446if (NextNonComment->is(TT_CtorInitializerComma))1447return CurrentState.Indent;1448if (PreviousNonComment && PreviousNonComment->is(TT_CtorInitializerColon) &&1449Style.BreakConstructorInitializers == FormatStyle::BCIS_AfterColon) {1450return CurrentState.Indent;1451}1452if (PreviousNonComment && PreviousNonComment->is(TT_InheritanceColon) &&1453Style.BreakInheritanceList == FormatStyle::BILS_AfterColon) {1454return CurrentState.Indent;1455}1456if (Previous.is(tok::r_paren) &&1457Previous.isNot(TT_TableGenDAGArgOperatorToBreak) &&1458!Current.isBinaryOperator() &&1459!Current.isOneOf(tok::colon, tok::comment)) {1460return ContinuationIndent;1461}1462if (Current.is(TT_ProtoExtensionLSquare))1463return CurrentState.Indent;1464if (Current.isBinaryOperator() && CurrentState.UnindentOperator) {1465return CurrentState.Indent - Current.Tok.getLength() -1466Current.SpacesRequiredBefore;1467}1468if (Current.is(tok::comment) && NextNonComment->isBinaryOperator() &&1469CurrentState.UnindentOperator) {1470return CurrentState.Indent - NextNonComment->Tok.getLength() -1471NextNonComment->SpacesRequiredBefore;1472}1473if (CurrentState.Indent == State.FirstIndent && PreviousNonComment &&1474!PreviousNonComment->isOneOf(tok::r_brace, TT_CtorInitializerComma)) {1475// Ensure that we fall back to the continuation indent width instead of1476// just flushing continuations left.1477return CurrentState.Indent + Style.ContinuationIndentWidth;1478}1479return CurrentState.Indent;1480}14811482static bool hasNestedBlockInlined(const FormatToken *Previous,1483const FormatToken &Current,1484const FormatStyle &Style) {1485if (Previous->isNot(tok::l_paren))1486return true;1487if (Previous->ParameterCount > 1)1488return true;14891490// Also a nested block if contains a lambda inside function with 1 parameter.1491return Style.BraceWrapping.BeforeLambdaBody && Current.is(TT_LambdaLSquare);1492}14931494unsigned ContinuationIndenter::moveStateToNextToken(LineState &State,1495bool DryRun, bool Newline) {1496assert(State.Stack.size());1497const FormatToken &Current = *State.NextToken;1498auto &CurrentState = State.Stack.back();14991500if (Current.is(TT_CSharpGenericTypeConstraint))1501CurrentState.IsCSharpGenericTypeConstraint = true;1502if (Current.isOneOf(tok::comma, TT_BinaryOperator))1503CurrentState.NoLineBreakInOperand = false;1504if (Current.isOneOf(TT_InheritanceColon, TT_CSharpGenericTypeConstraintColon))1505CurrentState.AvoidBinPacking = true;1506if (Current.is(tok::lessless) && Current.isNot(TT_OverloadedOperator)) {1507if (CurrentState.FirstLessLess == 0)1508CurrentState.FirstLessLess = State.Column;1509else1510CurrentState.LastOperatorWrapped = Newline;1511}1512if (Current.is(TT_BinaryOperator) && Current.isNot(tok::lessless))1513CurrentState.LastOperatorWrapped = Newline;1514if (Current.is(TT_ConditionalExpr) && Current.Previous &&1515Current.Previous->isNot(TT_ConditionalExpr)) {1516CurrentState.LastOperatorWrapped = Newline;1517}1518if (Current.is(TT_ArraySubscriptLSquare) &&1519CurrentState.StartOfArraySubscripts == 0) {1520CurrentState.StartOfArraySubscripts = State.Column;1521}15221523auto IsWrappedConditional = [](const FormatToken &Tok) {1524if (!(Tok.is(TT_ConditionalExpr) && Tok.is(tok::question)))1525return false;1526if (Tok.MustBreakBefore)1527return true;15281529const FormatToken *Next = Tok.getNextNonComment();1530return Next && Next->MustBreakBefore;1531};1532if (IsWrappedConditional(Current))1533CurrentState.IsWrappedConditional = true;1534if (Style.BreakBeforeTernaryOperators && Current.is(tok::question))1535CurrentState.QuestionColumn = State.Column;1536if (!Style.BreakBeforeTernaryOperators && Current.isNot(tok::colon)) {1537const FormatToken *Previous = Current.Previous;1538while (Previous && Previous->isTrailingComment())1539Previous = Previous->Previous;1540if (Previous && Previous->is(tok::question))1541CurrentState.QuestionColumn = State.Column;1542}1543if (!Current.opensScope() && !Current.closesScope() &&1544Current.isNot(TT_PointerOrReference)) {1545State.LowestLevelOnLine =1546std::min(State.LowestLevelOnLine, Current.NestingLevel);1547}1548if (Current.isMemberAccess())1549CurrentState.StartOfFunctionCall = !Current.NextOperator ? 0 : State.Column;1550if (Current.is(TT_SelectorName))1551CurrentState.ObjCSelectorNameFound = true;1552if (Current.is(TT_CtorInitializerColon) &&1553Style.BreakConstructorInitializers != FormatStyle::BCIS_AfterColon) {1554// Indent 2 from the column, so:1555// SomeClass::SomeClass()1556// : First(...), ...1557// Next(...)1558// ^ line up here.1559CurrentState.Indent = State.Column + (Style.BreakConstructorInitializers ==1560FormatStyle::BCIS_BeforeComma1561? 01562: 2);1563CurrentState.NestedBlockIndent = CurrentState.Indent;1564if (Style.PackConstructorInitializers > FormatStyle::PCIS_BinPack) {1565CurrentState.AvoidBinPacking = true;1566CurrentState.BreakBeforeParameter =1567Style.ColumnLimit > 0 &&1568Style.PackConstructorInitializers != FormatStyle::PCIS_NextLine &&1569Style.PackConstructorInitializers != FormatStyle::PCIS_NextLineOnly;1570} else {1571CurrentState.BreakBeforeParameter = false;1572}1573}1574if (Current.is(TT_CtorInitializerColon) &&1575Style.BreakConstructorInitializers == FormatStyle::BCIS_AfterColon) {1576CurrentState.Indent =1577State.FirstIndent + Style.ConstructorInitializerIndentWidth;1578CurrentState.NestedBlockIndent = CurrentState.Indent;1579if (Style.PackConstructorInitializers > FormatStyle::PCIS_BinPack)1580CurrentState.AvoidBinPacking = true;1581else1582CurrentState.BreakBeforeParameter = false;1583}1584if (Current.is(TT_InheritanceColon)) {1585CurrentState.Indent =1586State.FirstIndent + Style.ConstructorInitializerIndentWidth;1587}1588if (Current.isOneOf(TT_BinaryOperator, TT_ConditionalExpr) && Newline)1589CurrentState.NestedBlockIndent = State.Column + Current.ColumnWidth + 1;1590if (Current.isOneOf(TT_LambdaLSquare, TT_LambdaArrow))1591CurrentState.LastSpace = State.Column;1592if (Current.is(TT_RequiresExpression) &&1593Style.RequiresExpressionIndentation == FormatStyle::REI_Keyword) {1594CurrentState.NestedBlockIndent = State.Column;1595}15961597// Insert scopes created by fake parenthesis.1598const FormatToken *Previous = Current.getPreviousNonComment();15991600// Add special behavior to support a format commonly used for JavaScript1601// closures:1602// SomeFunction(function() {1603// foo();1604// bar();1605// }, a, b, c);1606if (Current.isNot(tok::comment) && !Current.ClosesRequiresClause &&1607Previous && Previous->isOneOf(tok::l_brace, TT_ArrayInitializerLSquare) &&1608Previous->isNot(TT_DictLiteral) && State.Stack.size() > 1 &&1609!CurrentState.HasMultipleNestedBlocks) {1610if (State.Stack[State.Stack.size() - 2].NestedBlockInlined && Newline)1611for (ParenState &PState : llvm::drop_end(State.Stack))1612PState.NoLineBreak = true;1613State.Stack[State.Stack.size() - 2].NestedBlockInlined = false;1614}1615if (Previous && (Previous->isOneOf(TT_BinaryOperator, TT_ConditionalExpr) ||1616(Previous->isOneOf(tok::l_paren, tok::comma, tok::colon) &&1617!Previous->isOneOf(TT_DictLiteral, TT_ObjCMethodExpr)))) {1618CurrentState.NestedBlockInlined =1619!Newline && hasNestedBlockInlined(Previous, Current, Style);1620}16211622moveStatePastFakeLParens(State, Newline);1623moveStatePastScopeCloser(State);1624// Do not use CurrentState here, since the two functions before may change the1625// Stack.1626bool AllowBreak = !State.Stack.back().NoLineBreak &&1627!State.Stack.back().NoLineBreakInOperand;1628moveStatePastScopeOpener(State, Newline);1629moveStatePastFakeRParens(State);16301631if (Current.is(TT_ObjCStringLiteral) && State.StartOfStringLiteral == 0)1632State.StartOfStringLiteral = State.Column + 1;1633if (Current.is(TT_CSharpStringLiteral) && State.StartOfStringLiteral == 0) {1634State.StartOfStringLiteral = State.Column + 1;1635} else if (Current.is(TT_TableGenMultiLineString) &&1636State.StartOfStringLiteral == 0) {1637State.StartOfStringLiteral = State.Column + 1;1638} else if (Current.isStringLiteral() && State.StartOfStringLiteral == 0) {1639State.StartOfStringLiteral = State.Column;1640} else if (!Current.isOneOf(tok::comment, tok::identifier, tok::hash) &&1641!Current.isStringLiteral()) {1642State.StartOfStringLiteral = 0;1643}16441645State.Column += Current.ColumnWidth;1646State.NextToken = State.NextToken->Next;1647// Verilog case labels are on the same unwrapped lines as the statements that1648// follow. TokenAnnotator identifies them and sets MustBreakBefore.1649// Indentation is taken care of here. A case label can only have 1 statement1650// in Verilog, so we don't have to worry about lines that follow.1651if (Style.isVerilog() && State.NextToken &&1652State.NextToken->MustBreakBefore &&1653Keywords.isVerilogEndOfLabel(Current)) {1654State.FirstIndent += Style.IndentWidth;1655CurrentState.Indent = State.FirstIndent;1656}16571658unsigned Penalty =1659handleEndOfLine(Current, State, DryRun, AllowBreak, Newline);16601661if (Current.Role)1662Current.Role->formatFromToken(State, this, DryRun);1663// If the previous has a special role, let it consume tokens as appropriate.1664// It is necessary to start at the previous token for the only implemented1665// role (comma separated list). That way, the decision whether or not to break1666// after the "{" is already done and both options are tried and evaluated.1667// FIXME: This is ugly, find a better way.1668if (Previous && Previous->Role)1669Penalty += Previous->Role->formatAfterToken(State, this, DryRun);16701671return Penalty;1672}16731674void ContinuationIndenter::moveStatePastFakeLParens(LineState &State,1675bool Newline) {1676const FormatToken &Current = *State.NextToken;1677if (Current.FakeLParens.empty())1678return;16791680const FormatToken *Previous = Current.getPreviousNonComment();16811682// Don't add extra indentation for the first fake parenthesis after1683// 'return', assignments, opening <({[, or requires clauses. The indentation1684// for these cases is special cased.1685bool SkipFirstExtraIndent =1686Previous &&1687(Previous->opensScope() ||1688Previous->isOneOf(tok::semi, tok::kw_return, TT_RequiresClause) ||1689(Previous->getPrecedence() == prec::Assignment &&1690Style.AlignOperands != FormatStyle::OAS_DontAlign) ||1691Previous->is(TT_ObjCMethodExpr));1692for (const auto &PrecedenceLevel : llvm::reverse(Current.FakeLParens)) {1693const auto &CurrentState = State.Stack.back();1694ParenState NewParenState = CurrentState;1695NewParenState.Tok = nullptr;1696NewParenState.ContainsLineBreak = false;1697NewParenState.LastOperatorWrapped = true;1698NewParenState.IsChainedConditional = false;1699NewParenState.IsWrappedConditional = false;1700NewParenState.UnindentOperator = false;1701NewParenState.NoLineBreak =1702NewParenState.NoLineBreak || CurrentState.NoLineBreakInOperand;17031704// Don't propagate AvoidBinPacking into subexpressions of arg/param lists.1705if (PrecedenceLevel > prec::Comma)1706NewParenState.AvoidBinPacking = false;17071708// Indent from 'LastSpace' unless these are fake parentheses encapsulating1709// a builder type call after 'return' or, if the alignment after opening1710// brackets is disabled.1711if (!Current.isTrailingComment() &&1712(Style.AlignOperands != FormatStyle::OAS_DontAlign ||1713PrecedenceLevel < prec::Assignment) &&1714(!Previous || Previous->isNot(tok::kw_return) ||1715(Style.Language != FormatStyle::LK_Java && PrecedenceLevel > 0)) &&1716(Style.AlignAfterOpenBracket != FormatStyle::BAS_DontAlign ||1717PrecedenceLevel > prec::Comma || Current.NestingLevel == 0) &&1718(!Style.isTableGen() ||1719(Previous && Previous->isOneOf(TT_TableGenDAGArgListComma,1720TT_TableGenDAGArgListCommaToBreak)))) {1721NewParenState.Indent = std::max(1722std::max(State.Column, NewParenState.Indent), CurrentState.LastSpace);1723}17241725// Special case for generic selection expressions, its comma-separated1726// expressions are not aligned to the opening paren like regular calls, but1727// rather continuation-indented relative to the _Generic keyword.1728if (Previous && Previous->endsSequence(tok::l_paren, tok::kw__Generic) &&1729State.Stack.size() > 1) {1730NewParenState.Indent = State.Stack[State.Stack.size() - 2].Indent +1731Style.ContinuationIndentWidth;1732}17331734if ((shouldUnindentNextOperator(Current) ||1735(Previous &&1736(PrecedenceLevel == prec::Conditional &&1737Previous->is(tok::question) && Previous->is(TT_ConditionalExpr)))) &&1738!Newline) {1739// If BreakBeforeBinaryOperators is set, un-indent a bit to account for1740// the operator and keep the operands aligned.1741if (Style.AlignOperands == FormatStyle::OAS_AlignAfterOperator)1742NewParenState.UnindentOperator = true;1743// Mark indentation as alignment if the expression is aligned.1744if (Style.AlignOperands != FormatStyle::OAS_DontAlign)1745NewParenState.IsAligned = true;1746}17471748// Do not indent relative to the fake parentheses inserted for "." or "->".1749// This is a special case to make the following to statements consistent:1750// OuterFunction(InnerFunctionCall( // break1751// ParameterToInnerFunction));1752// OuterFunction(SomeObject.InnerFunctionCall( // break1753// ParameterToInnerFunction));1754if (PrecedenceLevel > prec::Unknown)1755NewParenState.LastSpace = std::max(NewParenState.LastSpace, State.Column);1756if (PrecedenceLevel != prec::Conditional &&1757Current.isNot(TT_UnaryOperator) &&1758Style.AlignAfterOpenBracket != FormatStyle::BAS_DontAlign) {1759NewParenState.StartOfFunctionCall = State.Column;1760}17611762// Indent conditional expressions, unless they are chained "else-if"1763// conditionals. Never indent expression where the 'operator' is ',', ';' or1764// an assignment (i.e. *I <= prec::Assignment) as those have different1765// indentation rules. Indent other expression, unless the indentation needs1766// to be skipped.1767if (PrecedenceLevel == prec::Conditional && Previous &&1768Previous->is(tok::colon) && Previous->is(TT_ConditionalExpr) &&1769&PrecedenceLevel == &Current.FakeLParens.back() &&1770!CurrentState.IsWrappedConditional) {1771NewParenState.IsChainedConditional = true;1772NewParenState.UnindentOperator = State.Stack.back().UnindentOperator;1773} else if (PrecedenceLevel == prec::Conditional ||1774(!SkipFirstExtraIndent && PrecedenceLevel > prec::Assignment &&1775!Current.isTrailingComment())) {1776NewParenState.Indent += Style.ContinuationIndentWidth;1777}1778if ((Previous && !Previous->opensScope()) || PrecedenceLevel != prec::Comma)1779NewParenState.BreakBeforeParameter = false;1780State.Stack.push_back(NewParenState);1781SkipFirstExtraIndent = false;1782}1783}17841785void ContinuationIndenter::moveStatePastFakeRParens(LineState &State) {1786for (unsigned i = 0, e = State.NextToken->FakeRParens; i != e; ++i) {1787unsigned VariablePos = State.Stack.back().VariablePos;1788if (State.Stack.size() == 1) {1789// Do not pop the last element.1790break;1791}1792State.Stack.pop_back();1793State.Stack.back().VariablePos = VariablePos;1794}17951796if (State.NextToken->ClosesRequiresClause && Style.IndentRequiresClause) {1797// Remove the indentation of the requires clauses (which is not in Indent,1798// but in LastSpace).1799State.Stack.back().LastSpace -= Style.IndentWidth;1800}1801}18021803void ContinuationIndenter::moveStatePastScopeOpener(LineState &State,1804bool Newline) {1805const FormatToken &Current = *State.NextToken;1806if (!Current.opensScope())1807return;18081809const auto &CurrentState = State.Stack.back();18101811// Don't allow '<' or '(' in C# generic type constraints to start new scopes.1812if (Current.isOneOf(tok::less, tok::l_paren) &&1813CurrentState.IsCSharpGenericTypeConstraint) {1814return;1815}18161817if (Current.MatchingParen && Current.is(BK_Block)) {1818moveStateToNewBlock(State, Newline);1819return;1820}18211822unsigned NewIndent;1823unsigned LastSpace = CurrentState.LastSpace;1824bool AvoidBinPacking;1825bool BreakBeforeParameter = false;1826unsigned NestedBlockIndent = std::max(CurrentState.StartOfFunctionCall,1827CurrentState.NestedBlockIndent);1828if (Current.isOneOf(tok::l_brace, TT_ArrayInitializerLSquare) ||1829opensProtoMessageField(Current, Style)) {1830if (Current.opensBlockOrBlockTypeList(Style)) {1831NewIndent = Style.IndentWidth +1832std::min(State.Column, CurrentState.NestedBlockIndent);1833} else if (Current.is(tok::l_brace)) {1834NewIndent =1835CurrentState.LastSpace + Style.BracedInitializerIndentWidth.value_or(1836Style.ContinuationIndentWidth);1837} else {1838NewIndent = CurrentState.LastSpace + Style.ContinuationIndentWidth;1839}1840const FormatToken *NextNonComment = Current.getNextNonComment();1841bool EndsInComma = Current.MatchingParen &&1842Current.MatchingParen->Previous &&1843Current.MatchingParen->Previous->is(tok::comma);1844AvoidBinPacking = EndsInComma || Current.is(TT_DictLiteral) ||1845Style.isProto() || !Style.BinPackArguments ||1846(NextNonComment && NextNonComment->isOneOf(1847TT_DesignatedInitializerPeriod,1848TT_DesignatedInitializerLSquare));1849BreakBeforeParameter = EndsInComma;1850if (Current.ParameterCount > 1)1851NestedBlockIndent = std::max(NestedBlockIndent, State.Column + 1);1852} else {1853NewIndent =1854Style.ContinuationIndentWidth +1855std::max(CurrentState.LastSpace, CurrentState.StartOfFunctionCall);18561857if (Style.isTableGen() && Current.is(TT_TableGenDAGArgOpenerToBreak) &&1858Style.TableGenBreakInsideDAGArg == FormatStyle::DAS_BreakElements) {1859// For the case the next token is a TableGen DAGArg operator identifier1860// that is not marked to have a line break after it.1861// In this case the option DAS_BreakElements requires to align the1862// DAGArg elements to the operator.1863const FormatToken *Next = Current.Next;1864if (Next && Next->is(TT_TableGenDAGArgOperatorID))1865NewIndent = State.Column + Next->TokenText.size() + 2;1866}18671868// Ensure that different different brackets force relative alignment, e.g.:1869// void SomeFunction(vector< // break1870// int> v);1871// FIXME: We likely want to do this for more combinations of brackets.1872if (Current.is(tok::less) && Current.ParentBracket == tok::l_paren) {1873NewIndent = std::max(NewIndent, CurrentState.Indent);1874LastSpace = std::max(LastSpace, CurrentState.Indent);1875}18761877bool EndsInComma =1878Current.MatchingParen &&1879Current.MatchingParen->getPreviousNonComment() &&1880Current.MatchingParen->getPreviousNonComment()->is(tok::comma);18811882// If ObjCBinPackProtocolList is unspecified, fall back to BinPackParameters1883// for backwards compatibility.1884bool ObjCBinPackProtocolList =1885(Style.ObjCBinPackProtocolList == FormatStyle::BPS_Auto &&1886Style.BinPackParameters) ||1887Style.ObjCBinPackProtocolList == FormatStyle::BPS_Always;18881889bool BinPackDeclaration =1890(State.Line->Type != LT_ObjCDecl && Style.BinPackParameters) ||1891(State.Line->Type == LT_ObjCDecl && ObjCBinPackProtocolList);18921893bool GenericSelection =1894Current.getPreviousNonComment() &&1895Current.getPreviousNonComment()->is(tok::kw__Generic);18961897AvoidBinPacking =1898(CurrentState.IsCSharpGenericTypeConstraint) || GenericSelection ||1899(Style.isJavaScript() && EndsInComma) ||1900(State.Line->MustBeDeclaration && !BinPackDeclaration) ||1901(!State.Line->MustBeDeclaration && !Style.BinPackArguments) ||1902(Style.ExperimentalAutoDetectBinPacking &&1903(Current.is(PPK_OnePerLine) ||1904(!BinPackInconclusiveFunctions && Current.is(PPK_Inconclusive))));19051906if (Current.is(TT_ObjCMethodExpr) && Current.MatchingParen &&1907Style.ObjCBreakBeforeNestedBlockParam) {1908if (Style.ColumnLimit) {1909// If this '[' opens an ObjC call, determine whether all parameters fit1910// into one line and put one per line if they don't.1911if (getLengthToMatchingParen(Current, State.Stack) + State.Column >1912getColumnLimit(State)) {1913BreakBeforeParameter = true;1914}1915} else {1916// For ColumnLimit = 0, we have to figure out whether there is or has to1917// be a line break within this call.1918for (const FormatToken *Tok = &Current;1919Tok && Tok != Current.MatchingParen; Tok = Tok->Next) {1920if (Tok->MustBreakBefore ||1921(Tok->CanBreakBefore && Tok->NewlinesBefore > 0)) {1922BreakBeforeParameter = true;1923break;1924}1925}1926}1927}19281929if (Style.isJavaScript() && EndsInComma)1930BreakBeforeParameter = true;1931}1932// Generally inherit NoLineBreak from the current scope to nested scope.1933// However, don't do this for non-empty nested blocks, dict literals and1934// array literals as these follow different indentation rules.1935bool NoLineBreak =1936Current.Children.empty() &&1937!Current.isOneOf(TT_DictLiteral, TT_ArrayInitializerLSquare) &&1938(CurrentState.NoLineBreak || CurrentState.NoLineBreakInOperand ||1939(Current.is(TT_TemplateOpener) &&1940CurrentState.ContainsUnwrappedBuilder));1941State.Stack.push_back(1942ParenState(&Current, NewIndent, LastSpace, AvoidBinPacking, NoLineBreak));1943auto &NewState = State.Stack.back();1944NewState.NestedBlockIndent = NestedBlockIndent;1945NewState.BreakBeforeParameter = BreakBeforeParameter;1946NewState.HasMultipleNestedBlocks = (Current.BlockParameterCount > 1);19471948if (Style.BraceWrapping.BeforeLambdaBody && Current.Next &&1949Current.is(tok::l_paren)) {1950// Search for any parameter that is a lambda.1951FormatToken const *next = Current.Next;1952while (next) {1953if (next->is(TT_LambdaLSquare)) {1954NewState.HasMultipleNestedBlocks = true;1955break;1956}1957next = next->Next;1958}1959}19601961NewState.IsInsideObjCArrayLiteral = Current.is(TT_ArrayInitializerLSquare) &&1962Current.Previous &&1963Current.Previous->is(tok::at);1964}19651966void ContinuationIndenter::moveStatePastScopeCloser(LineState &State) {1967const FormatToken &Current = *State.NextToken;1968if (!Current.closesScope())1969return;19701971// If we encounter a closing ), ], } or >, we can remove a level from our1972// stacks.1973if (State.Stack.size() > 1 &&1974(Current.isOneOf(tok::r_paren, tok::r_square, TT_TemplateString) ||1975(Current.is(tok::r_brace) && State.NextToken != State.Line->First) ||1976State.NextToken->is(TT_TemplateCloser) ||1977State.NextToken->is(TT_TableGenListCloser) ||1978(Current.is(tok::greater) && Current.is(TT_DictLiteral)))) {1979State.Stack.pop_back();1980}19811982auto &CurrentState = State.Stack.back();19831984// Reevaluate whether ObjC message arguments fit into one line.1985// If a receiver spans multiple lines, e.g.:1986// [[object block:^{1987// return 42;1988// }] a:42 b:42];1989// BreakBeforeParameter is calculated based on an incorrect assumption1990// (it is checked whether the whole expression fits into one line without1991// considering a line break inside a message receiver).1992// We check whether arguments fit after receiver scope closer (into the same1993// line).1994if (CurrentState.BreakBeforeParameter && Current.MatchingParen &&1995Current.MatchingParen->Previous) {1996const FormatToken &CurrentScopeOpener = *Current.MatchingParen->Previous;1997if (CurrentScopeOpener.is(TT_ObjCMethodExpr) &&1998CurrentScopeOpener.MatchingParen) {1999int NecessarySpaceInLine =2000getLengthToMatchingParen(CurrentScopeOpener, State.Stack) +2001CurrentScopeOpener.TotalLength - Current.TotalLength - 1;2002if (State.Column + Current.ColumnWidth + NecessarySpaceInLine <=2003Style.ColumnLimit) {2004CurrentState.BreakBeforeParameter = false;2005}2006}2007}20082009if (Current.is(tok::r_square)) {2010// If this ends the array subscript expr, reset the corresponding value.2011const FormatToken *NextNonComment = Current.getNextNonComment();2012if (NextNonComment && NextNonComment->isNot(tok::l_square))2013CurrentState.StartOfArraySubscripts = 0;2014}2015}20162017void ContinuationIndenter::moveStateToNewBlock(LineState &State, bool NewLine) {2018if (Style.LambdaBodyIndentation == FormatStyle::LBI_OuterScope &&2019State.NextToken->is(TT_LambdaLBrace) &&2020!State.Line->MightBeFunctionDecl) {2021State.Stack.back().NestedBlockIndent = State.FirstIndent;2022}2023unsigned NestedBlockIndent = State.Stack.back().NestedBlockIndent;2024// ObjC block sometimes follow special indentation rules.2025unsigned NewIndent =2026NestedBlockIndent + (State.NextToken->is(TT_ObjCBlockLBrace)2027? Style.ObjCBlockIndentWidth2028: Style.IndentWidth);20292030// Even when wrapping before lambda body, the left brace can still be added to2031// the same line. This occurs when checking whether the whole lambda body can2032// go on a single line. In this case we have to make sure there are no line2033// breaks in the body, otherwise we could just end up with a regular lambda2034// body without the brace wrapped.2035bool NoLineBreak = Style.BraceWrapping.BeforeLambdaBody && !NewLine &&2036State.NextToken->is(TT_LambdaLBrace);20372038State.Stack.push_back(ParenState(State.NextToken, NewIndent,2039State.Stack.back().LastSpace,2040/*AvoidBinPacking=*/true, NoLineBreak));2041State.Stack.back().NestedBlockIndent = NestedBlockIndent;2042State.Stack.back().BreakBeforeParameter = true;2043}20442045static unsigned getLastLineEndColumn(StringRef Text, unsigned StartColumn,2046unsigned TabWidth,2047encoding::Encoding Encoding) {2048size_t LastNewlinePos = Text.find_last_of("\n");2049if (LastNewlinePos == StringRef::npos) {2050return StartColumn +2051encoding::columnWidthWithTabs(Text, StartColumn, TabWidth, Encoding);2052} else {2053return encoding::columnWidthWithTabs(Text.substr(LastNewlinePos),2054/*StartColumn=*/0, TabWidth, Encoding);2055}2056}20572058unsigned ContinuationIndenter::reformatRawStringLiteral(2059const FormatToken &Current, LineState &State,2060const FormatStyle &RawStringStyle, bool DryRun, bool Newline) {2061unsigned StartColumn = State.Column - Current.ColumnWidth;2062StringRef OldDelimiter = *getRawStringDelimiter(Current.TokenText);2063StringRef NewDelimiter =2064getCanonicalRawStringDelimiter(Style, RawStringStyle.Language);2065if (NewDelimiter.empty())2066NewDelimiter = OldDelimiter;2067// The text of a raw string is between the leading 'R"delimiter(' and the2068// trailing 'delimiter)"'.2069unsigned OldPrefixSize = 3 + OldDelimiter.size();2070unsigned OldSuffixSize = 2 + OldDelimiter.size();2071// We create a virtual text environment which expects a null-terminated2072// string, so we cannot use StringRef.2073std::string RawText = std::string(2074Current.TokenText.substr(OldPrefixSize).drop_back(OldSuffixSize));2075if (NewDelimiter != OldDelimiter) {2076// Don't update to the canonical delimiter 'deli' if ')deli"' occurs in the2077// raw string.2078std::string CanonicalDelimiterSuffix = (")" + NewDelimiter + "\"").str();2079if (StringRef(RawText).contains(CanonicalDelimiterSuffix))2080NewDelimiter = OldDelimiter;2081}20822083unsigned NewPrefixSize = 3 + NewDelimiter.size();2084unsigned NewSuffixSize = 2 + NewDelimiter.size();20852086// The first start column is the column the raw text starts after formatting.2087unsigned FirstStartColumn = StartColumn + NewPrefixSize;20882089// The next start column is the intended indentation a line break inside2090// the raw string at level 0. It is determined by the following rules:2091// - if the content starts on newline, it is one level more than the current2092// indent, and2093// - if the content does not start on a newline, it is the first start2094// column.2095// These rules have the advantage that the formatted content both does not2096// violate the rectangle rule and visually flows within the surrounding2097// source.2098bool ContentStartsOnNewline = Current.TokenText[OldPrefixSize] == '\n';2099// If this token is the last parameter (checked by looking if it's followed by2100// `)` and is not on a newline, the base the indent off the line's nested2101// block indent. Otherwise, base the indent off the arguments indent, so we2102// can achieve:2103//2104// fffffffffff(1, 2, 3, R"pb(2105// key1: 1 #2106// key2: 2)pb");2107//2108// fffffffffff(1, 2, 3,2109// R"pb(2110// key1: 1 #2111// key2: 22112// )pb");2113//2114// fffffffffff(1, 2, 3,2115// R"pb(2116// key1: 1 #2117// key2: 22118// )pb",2119// 5);2120unsigned CurrentIndent =2121(!Newline && Current.Next && Current.Next->is(tok::r_paren))2122? State.Stack.back().NestedBlockIndent2123: State.Stack.back().Indent;2124unsigned NextStartColumn = ContentStartsOnNewline2125? CurrentIndent + Style.IndentWidth2126: FirstStartColumn;21272128// The last start column is the column the raw string suffix starts if it is2129// put on a newline.2130// The last start column is the intended indentation of the raw string postfix2131// if it is put on a newline. It is determined by the following rules:2132// - if the raw string prefix starts on a newline, it is the column where2133// that raw string prefix starts, and2134// - if the raw string prefix does not start on a newline, it is the current2135// indent.2136unsigned LastStartColumn =2137Current.NewlinesBefore ? FirstStartColumn - NewPrefixSize : CurrentIndent;21382139std::pair<tooling::Replacements, unsigned> Fixes = internal::reformat(2140RawStringStyle, RawText, {tooling::Range(0, RawText.size())},2141FirstStartColumn, NextStartColumn, LastStartColumn, "<stdin>",2142/*Status=*/nullptr);21432144auto NewCode = applyAllReplacements(RawText, Fixes.first);2145tooling::Replacements NoFixes;2146if (!NewCode)2147return addMultilineToken(Current, State);2148if (!DryRun) {2149if (NewDelimiter != OldDelimiter) {2150// In 'R"delimiter(...', the delimiter starts 2 characters after the start2151// of the token.2152SourceLocation PrefixDelimiterStart =2153Current.Tok.getLocation().getLocWithOffset(2);2154auto PrefixErr = Whitespaces.addReplacement(tooling::Replacement(2155SourceMgr, PrefixDelimiterStart, OldDelimiter.size(), NewDelimiter));2156if (PrefixErr) {2157llvm::errs()2158<< "Failed to update the prefix delimiter of a raw string: "2159<< llvm::toString(std::move(PrefixErr)) << "\n";2160}2161// In 'R"delimiter(...)delimiter"', the suffix delimiter starts at2162// position length - 1 - |delimiter|.2163SourceLocation SuffixDelimiterStart =2164Current.Tok.getLocation().getLocWithOffset(Current.TokenText.size() -21651 - OldDelimiter.size());2166auto SuffixErr = Whitespaces.addReplacement(tooling::Replacement(2167SourceMgr, SuffixDelimiterStart, OldDelimiter.size(), NewDelimiter));2168if (SuffixErr) {2169llvm::errs()2170<< "Failed to update the suffix delimiter of a raw string: "2171<< llvm::toString(std::move(SuffixErr)) << "\n";2172}2173}2174SourceLocation OriginLoc =2175Current.Tok.getLocation().getLocWithOffset(OldPrefixSize);2176for (const tooling::Replacement &Fix : Fixes.first) {2177auto Err = Whitespaces.addReplacement(tooling::Replacement(2178SourceMgr, OriginLoc.getLocWithOffset(Fix.getOffset()),2179Fix.getLength(), Fix.getReplacementText()));2180if (Err) {2181llvm::errs() << "Failed to reformat raw string: "2182<< llvm::toString(std::move(Err)) << "\n";2183}2184}2185}2186unsigned RawLastLineEndColumn = getLastLineEndColumn(2187*NewCode, FirstStartColumn, Style.TabWidth, Encoding);2188State.Column = RawLastLineEndColumn + NewSuffixSize;2189// Since we're updating the column to after the raw string literal here, we2190// have to manually add the penalty for the prefix R"delim( over the column2191// limit.2192unsigned PrefixExcessCharacters =2193StartColumn + NewPrefixSize > Style.ColumnLimit2194? StartColumn + NewPrefixSize - Style.ColumnLimit2195: 0;2196bool IsMultiline =2197ContentStartsOnNewline || (NewCode->find('\n') != std::string::npos);2198if (IsMultiline) {2199// Break before further function parameters on all levels.2200for (ParenState &Paren : State.Stack)2201Paren.BreakBeforeParameter = true;2202}2203return Fixes.second + PrefixExcessCharacters * Style.PenaltyExcessCharacter;2204}22052206unsigned ContinuationIndenter::addMultilineToken(const FormatToken &Current,2207LineState &State) {2208// Break before further function parameters on all levels.2209for (ParenState &Paren : State.Stack)2210Paren.BreakBeforeParameter = true;22112212unsigned ColumnsUsed = State.Column;2213// We can only affect layout of the first and the last line, so the penalty2214// for all other lines is constant, and we ignore it.2215State.Column = Current.LastLineColumnWidth;22162217if (ColumnsUsed > getColumnLimit(State))2218return Style.PenaltyExcessCharacter * (ColumnsUsed - getColumnLimit(State));2219return 0;2220}22212222unsigned ContinuationIndenter::handleEndOfLine(const FormatToken &Current,2223LineState &State, bool DryRun,2224bool AllowBreak, bool Newline) {2225unsigned Penalty = 0;2226// Compute the raw string style to use in case this is a raw string literal2227// that can be reformatted.2228auto RawStringStyle = getRawStringStyle(Current, State);2229if (RawStringStyle && !Current.Finalized) {2230Penalty = reformatRawStringLiteral(Current, State, *RawStringStyle, DryRun,2231Newline);2232} else if (Current.IsMultiline && Current.isNot(TT_BlockComment)) {2233// Don't break multi-line tokens other than block comments and raw string2234// literals. Instead, just update the state.2235Penalty = addMultilineToken(Current, State);2236} else if (State.Line->Type != LT_ImportStatement) {2237// We generally don't break import statements.2238LineState OriginalState = State;22392240// Whether we force the reflowing algorithm to stay strictly within the2241// column limit.2242bool Strict = false;2243// Whether the first non-strict attempt at reflowing did intentionally2244// exceed the column limit.2245bool Exceeded = false;2246std::tie(Penalty, Exceeded) = breakProtrudingToken(2247Current, State, AllowBreak, /*DryRun=*/true, Strict);2248if (Exceeded) {2249// If non-strict reflowing exceeds the column limit, try whether strict2250// reflowing leads to an overall lower penalty.2251LineState StrictState = OriginalState;2252unsigned StrictPenalty =2253breakProtrudingToken(Current, StrictState, AllowBreak,2254/*DryRun=*/true, /*Strict=*/true)2255.first;2256Strict = StrictPenalty <= Penalty;2257if (Strict) {2258Penalty = StrictPenalty;2259State = StrictState;2260}2261}2262if (!DryRun) {2263// If we're not in dry-run mode, apply the changes with the decision on2264// strictness made above.2265breakProtrudingToken(Current, OriginalState, AllowBreak, /*DryRun=*/false,2266Strict);2267}2268}2269if (State.Column > getColumnLimit(State)) {2270unsigned ExcessCharacters = State.Column - getColumnLimit(State);2271Penalty += Style.PenaltyExcessCharacter * ExcessCharacters;2272}2273return Penalty;2274}22752276// Returns the enclosing function name of a token, or the empty string if not2277// found.2278static StringRef getEnclosingFunctionName(const FormatToken &Current) {2279// Look for: 'function(' or 'function<templates>(' before Current.2280auto Tok = Current.getPreviousNonComment();2281if (!Tok || Tok->isNot(tok::l_paren))2282return "";2283Tok = Tok->getPreviousNonComment();2284if (!Tok)2285return "";2286if (Tok->is(TT_TemplateCloser)) {2287Tok = Tok->MatchingParen;2288if (Tok)2289Tok = Tok->getPreviousNonComment();2290}2291if (!Tok || Tok->isNot(tok::identifier))2292return "";2293return Tok->TokenText;2294}22952296std::optional<FormatStyle>2297ContinuationIndenter::getRawStringStyle(const FormatToken &Current,2298const LineState &State) {2299if (!Current.isStringLiteral())2300return std::nullopt;2301auto Delimiter = getRawStringDelimiter(Current.TokenText);2302if (!Delimiter)2303return std::nullopt;2304auto RawStringStyle = RawStringFormats.getDelimiterStyle(*Delimiter);2305if (!RawStringStyle && Delimiter->empty()) {2306RawStringStyle = RawStringFormats.getEnclosingFunctionStyle(2307getEnclosingFunctionName(Current));2308}2309if (!RawStringStyle)2310return std::nullopt;2311RawStringStyle->ColumnLimit = getColumnLimit(State);2312return RawStringStyle;2313}23142315std::unique_ptr<BreakableToken>2316ContinuationIndenter::createBreakableToken(const FormatToken &Current,2317LineState &State, bool AllowBreak) {2318unsigned StartColumn = State.Column - Current.ColumnWidth;2319if (Current.isStringLiteral()) {2320// Strings in JSON cannot be broken. Breaking strings in JavaScript is2321// disabled for now.2322if (Style.isJson() || Style.isJavaScript() || !Style.BreakStringLiterals ||2323!AllowBreak) {2324return nullptr;2325}23262327// Don't break string literals inside preprocessor directives (except for2328// #define directives, as their contents are stored in separate lines and2329// are not affected by this check).2330// This way we avoid breaking code with line directives and unknown2331// preprocessor directives that contain long string literals.2332if (State.Line->Type == LT_PreprocessorDirective)2333return nullptr;2334// Exempts unterminated string literals from line breaking. The user will2335// likely want to terminate the string before any line breaking is done.2336if (Current.IsUnterminatedLiteral)2337return nullptr;2338// Don't break string literals inside Objective-C array literals (doing so2339// raises the warning -Wobjc-string-concatenation).2340if (State.Stack.back().IsInsideObjCArrayLiteral)2341return nullptr;23422343// The "DPI"/"DPI-C" in SystemVerilog direct programming interface2344// imports/exports cannot be split, e.g.2345// `import "DPI" function foo();`2346// FIXME: make this use same infra as C++ import checks2347if (Style.isVerilog() && Current.Previous &&2348Current.Previous->isOneOf(tok::kw_export, Keywords.kw_import)) {2349return nullptr;2350}2351StringRef Text = Current.TokenText;23522353// We need this to address the case where there is an unbreakable tail only2354// if certain other formatting decisions have been taken. The2355// UnbreakableTailLength of Current is an overapproximation in that case and2356// we need to be correct here.2357unsigned UnbreakableTailLength = (State.NextToken && canBreak(State))2358? 02359: Current.UnbreakableTailLength;23602361if (Style.isVerilog() || Style.Language == FormatStyle::LK_Java ||2362Style.isJavaScript() || Style.isCSharp()) {2363BreakableStringLiteralUsingOperators::QuoteStyleType QuoteStyle;2364if (Style.isJavaScript() && Text.starts_with("'") &&2365Text.ends_with("'")) {2366QuoteStyle = BreakableStringLiteralUsingOperators::SingleQuotes;2367} else if (Style.isCSharp() && Text.starts_with("@\"") &&2368Text.ends_with("\"")) {2369QuoteStyle = BreakableStringLiteralUsingOperators::AtDoubleQuotes;2370} else if (Text.starts_with("\"") && Text.ends_with("\"")) {2371QuoteStyle = BreakableStringLiteralUsingOperators::DoubleQuotes;2372} else {2373return nullptr;2374}2375return std::make_unique<BreakableStringLiteralUsingOperators>(2376Current, QuoteStyle,2377/*UnindentPlus=*/shouldUnindentNextOperator(Current), StartColumn,2378UnbreakableTailLength, State.Line->InPPDirective, Encoding, Style);2379}23802381StringRef Prefix;2382StringRef Postfix;2383// FIXME: Handle whitespace between '_T', '(', '"..."', and ')'.2384// FIXME: Store Prefix and Suffix (or PrefixLength and SuffixLength to2385// reduce the overhead) for each FormatToken, which is a string, so that we2386// don't run multiple checks here on the hot path.2387if ((Text.ends_with(Postfix = "\"") &&2388(Text.starts_with(Prefix = "@\"") || Text.starts_with(Prefix = "\"") ||2389Text.starts_with(Prefix = "u\"") ||2390Text.starts_with(Prefix = "U\"") ||2391Text.starts_with(Prefix = "u8\"") ||2392Text.starts_with(Prefix = "L\""))) ||2393(Text.starts_with(Prefix = "_T(\"") &&2394Text.ends_with(Postfix = "\")"))) {2395return std::make_unique<BreakableStringLiteral>(2396Current, StartColumn, Prefix, Postfix, UnbreakableTailLength,2397State.Line->InPPDirective, Encoding, Style);2398}2399} else if (Current.is(TT_BlockComment)) {2400if (!Style.ReflowComments ||2401// If a comment token switches formatting, like2402// /* clang-format on */, we don't want to break it further,2403// but we may still want to adjust its indentation.2404switchesFormatting(Current)) {2405return nullptr;2406}2407return std::make_unique<BreakableBlockComment>(2408Current, StartColumn, Current.OriginalColumn, !Current.Previous,2409State.Line->InPPDirective, Encoding, Style, Whitespaces.useCRLF());2410} else if (Current.is(TT_LineComment) &&2411(!Current.Previous ||2412Current.Previous->isNot(TT_ImplicitStringLiteral))) {2413bool RegularComments = [&]() {2414for (const FormatToken *T = &Current; T && T->is(TT_LineComment);2415T = T->Next) {2416if (!(T->TokenText.starts_with("//") || T->TokenText.starts_with("#")))2417return false;2418}2419return true;2420}();2421if (!Style.ReflowComments ||2422CommentPragmasRegex.match(Current.TokenText.substr(2)) ||2423switchesFormatting(Current) || !RegularComments) {2424return nullptr;2425}2426return std::make_unique<BreakableLineCommentSection>(2427Current, StartColumn, /*InPPDirective=*/false, Encoding, Style);2428}2429return nullptr;2430}24312432std::pair<unsigned, bool>2433ContinuationIndenter::breakProtrudingToken(const FormatToken &Current,2434LineState &State, bool AllowBreak,2435bool DryRun, bool Strict) {2436std::unique_ptr<const BreakableToken> Token =2437createBreakableToken(Current, State, AllowBreak);2438if (!Token)2439return {0, false};2440assert(Token->getLineCount() > 0);2441unsigned ColumnLimit = getColumnLimit(State);2442if (Current.is(TT_LineComment)) {2443// We don't insert backslashes when breaking line comments.2444ColumnLimit = Style.ColumnLimit;2445}2446if (ColumnLimit == 0) {2447// To make the rest of the function easier set the column limit to the2448// maximum, if there should be no limit.2449ColumnLimit = std::numeric_limits<decltype(ColumnLimit)>::max();2450}2451if (Current.UnbreakableTailLength >= ColumnLimit)2452return {0, false};2453// ColumnWidth was already accounted into State.Column before calling2454// breakProtrudingToken.2455unsigned StartColumn = State.Column - Current.ColumnWidth;2456unsigned NewBreakPenalty = Current.isStringLiteral()2457? Style.PenaltyBreakString2458: Style.PenaltyBreakComment;2459// Stores whether we intentionally decide to let a line exceed the column2460// limit.2461bool Exceeded = false;2462// Stores whether we introduce a break anywhere in the token.2463bool BreakInserted = Token->introducesBreakBeforeToken();2464// Store whether we inserted a new line break at the end of the previous2465// logical line.2466bool NewBreakBefore = false;2467// We use a conservative reflowing strategy. Reflow starts after a line is2468// broken or the corresponding whitespace compressed. Reflow ends as soon as a2469// line that doesn't get reflown with the previous line is reached.2470bool Reflow = false;2471// Keep track of where we are in the token:2472// Where we are in the content of the current logical line.2473unsigned TailOffset = 0;2474// The column number we're currently at.2475unsigned ContentStartColumn =2476Token->getContentStartColumn(0, /*Break=*/false);2477// The number of columns left in the current logical line after TailOffset.2478unsigned RemainingTokenColumns =2479Token->getRemainingLength(0, TailOffset, ContentStartColumn);2480// Adapt the start of the token, for example indent.2481if (!DryRun)2482Token->adaptStartOfLine(0, Whitespaces);24832484unsigned ContentIndent = 0;2485unsigned Penalty = 0;2486LLVM_DEBUG(llvm::dbgs() << "Breaking protruding token at column "2487<< StartColumn << ".\n");2488for (unsigned LineIndex = 0, EndIndex = Token->getLineCount();2489LineIndex != EndIndex; ++LineIndex) {2490LLVM_DEBUG(llvm::dbgs()2491<< " Line: " << LineIndex << " (Reflow: " << Reflow << ")\n");2492NewBreakBefore = false;2493// If we did reflow the previous line, we'll try reflowing again. Otherwise2494// we'll start reflowing if the current line is broken or whitespace is2495// compressed.2496bool TryReflow = Reflow;2497// Break the current token until we can fit the rest of the line.2498while (ContentStartColumn + RemainingTokenColumns > ColumnLimit) {2499LLVM_DEBUG(llvm::dbgs() << " Over limit, need: "2500<< (ContentStartColumn + RemainingTokenColumns)2501<< ", space: " << ColumnLimit2502<< ", reflown prefix: " << ContentStartColumn2503<< ", offset in line: " << TailOffset << "\n");2504// If the current token doesn't fit, find the latest possible split in the2505// current line so that breaking at it will be under the column limit.2506// FIXME: Use the earliest possible split while reflowing to correctly2507// compress whitespace within a line.2508BreakableToken::Split Split =2509Token->getSplit(LineIndex, TailOffset, ColumnLimit,2510ContentStartColumn, CommentPragmasRegex);2511if (Split.first == StringRef::npos) {2512// No break opportunity - update the penalty and continue with the next2513// logical line.2514if (LineIndex < EndIndex - 1) {2515// The last line's penalty is handled in addNextStateToQueue() or when2516// calling replaceWhitespaceAfterLastLine below.2517Penalty += Style.PenaltyExcessCharacter *2518(ContentStartColumn + RemainingTokenColumns - ColumnLimit);2519}2520LLVM_DEBUG(llvm::dbgs() << " No break opportunity.\n");2521break;2522}2523assert(Split.first != 0);25242525if (Token->supportsReflow()) {2526// Check whether the next natural split point after the current one can2527// still fit the line, either because we can compress away whitespace,2528// or because the penalty the excess characters introduce is lower than2529// the break penalty.2530// We only do this for tokens that support reflowing, and thus allow us2531// to change the whitespace arbitrarily (e.g. comments).2532// Other tokens, like string literals, can be broken on arbitrary2533// positions.25342535// First, compute the columns from TailOffset to the next possible split2536// position.2537// For example:2538// ColumnLimit: |2539// // Some text that breaks2540// ^ tail offset2541// ^-- split2542// ^-------- to split columns2543// ^--- next split2544// ^--------------- to next split columns2545unsigned ToSplitColumns = Token->getRangeLength(2546LineIndex, TailOffset, Split.first, ContentStartColumn);2547LLVM_DEBUG(llvm::dbgs() << " ToSplit: " << ToSplitColumns << "\n");25482549BreakableToken::Split NextSplit = Token->getSplit(2550LineIndex, TailOffset + Split.first + Split.second, ColumnLimit,2551ContentStartColumn + ToSplitColumns + 1, CommentPragmasRegex);2552// Compute the columns necessary to fit the next non-breakable sequence2553// into the current line.2554unsigned ToNextSplitColumns = 0;2555if (NextSplit.first == StringRef::npos) {2556ToNextSplitColumns = Token->getRemainingLength(LineIndex, TailOffset,2557ContentStartColumn);2558} else {2559ToNextSplitColumns = Token->getRangeLength(2560LineIndex, TailOffset,2561Split.first + Split.second + NextSplit.first, ContentStartColumn);2562}2563// Compress the whitespace between the break and the start of the next2564// unbreakable sequence.2565ToNextSplitColumns =2566Token->getLengthAfterCompression(ToNextSplitColumns, Split);2567LLVM_DEBUG(llvm::dbgs()2568<< " ContentStartColumn: " << ContentStartColumn << "\n");2569LLVM_DEBUG(llvm::dbgs()2570<< " ToNextSplit: " << ToNextSplitColumns << "\n");2571// If the whitespace compression makes us fit, continue on the current2572// line.2573bool ContinueOnLine =2574ContentStartColumn + ToNextSplitColumns <= ColumnLimit;2575unsigned ExcessCharactersPenalty = 0;2576if (!ContinueOnLine && !Strict) {2577// Similarly, if the excess characters' penalty is lower than the2578// penalty of introducing a new break, continue on the current line.2579ExcessCharactersPenalty =2580(ContentStartColumn + ToNextSplitColumns - ColumnLimit) *2581Style.PenaltyExcessCharacter;2582LLVM_DEBUG(llvm::dbgs()2583<< " Penalty excess: " << ExcessCharactersPenalty2584<< "\n break : " << NewBreakPenalty << "\n");2585if (ExcessCharactersPenalty < NewBreakPenalty) {2586Exceeded = true;2587ContinueOnLine = true;2588}2589}2590if (ContinueOnLine) {2591LLVM_DEBUG(llvm::dbgs() << " Continuing on line...\n");2592// The current line fits after compressing the whitespace - reflow2593// the next line into it if possible.2594TryReflow = true;2595if (!DryRun) {2596Token->compressWhitespace(LineIndex, TailOffset, Split,2597Whitespaces);2598}2599// When we continue on the same line, leave one space between content.2600ContentStartColumn += ToSplitColumns + 1;2601Penalty += ExcessCharactersPenalty;2602TailOffset += Split.first + Split.second;2603RemainingTokenColumns = Token->getRemainingLength(2604LineIndex, TailOffset, ContentStartColumn);2605continue;2606}2607}2608LLVM_DEBUG(llvm::dbgs() << " Breaking...\n");2609// Update the ContentIndent only if the current line was not reflown with2610// the previous line, since in that case the previous line should still2611// determine the ContentIndent. Also never intent the last line.2612if (!Reflow)2613ContentIndent = Token->getContentIndent(LineIndex);2614LLVM_DEBUG(llvm::dbgs()2615<< " ContentIndent: " << ContentIndent << "\n");2616ContentStartColumn = ContentIndent + Token->getContentStartColumn(2617LineIndex, /*Break=*/true);26182619unsigned NewRemainingTokenColumns = Token->getRemainingLength(2620LineIndex, TailOffset + Split.first + Split.second,2621ContentStartColumn);2622if (NewRemainingTokenColumns == 0) {2623// No content to indent.2624ContentIndent = 0;2625ContentStartColumn =2626Token->getContentStartColumn(LineIndex, /*Break=*/true);2627NewRemainingTokenColumns = Token->getRemainingLength(2628LineIndex, TailOffset + Split.first + Split.second,2629ContentStartColumn);2630}26312632// When breaking before a tab character, it may be moved by a few columns,2633// but will still be expanded to the next tab stop, so we don't save any2634// columns.2635if (NewRemainingTokenColumns >= RemainingTokenColumns) {2636// FIXME: Do we need to adjust the penalty?2637break;2638}26392640LLVM_DEBUG(llvm::dbgs() << " Breaking at: " << TailOffset + Split.first2641<< ", " << Split.second << "\n");2642if (!DryRun) {2643Token->insertBreak(LineIndex, TailOffset, Split, ContentIndent,2644Whitespaces);2645}26462647Penalty += NewBreakPenalty;2648TailOffset += Split.first + Split.second;2649RemainingTokenColumns = NewRemainingTokenColumns;2650BreakInserted = true;2651NewBreakBefore = true;2652}2653// In case there's another line, prepare the state for the start of the next2654// line.2655if (LineIndex + 1 != EndIndex) {2656unsigned NextLineIndex = LineIndex + 1;2657if (NewBreakBefore) {2658// After breaking a line, try to reflow the next line into the current2659// one once RemainingTokenColumns fits.2660TryReflow = true;2661}2662if (TryReflow) {2663// We decided that we want to try reflowing the next line into the2664// current one.2665// We will now adjust the state as if the reflow is successful (in2666// preparation for the next line), and see whether that works. If we2667// decide that we cannot reflow, we will later reset the state to the2668// start of the next line.2669Reflow = false;2670// As we did not continue breaking the line, RemainingTokenColumns is2671// known to fit after ContentStartColumn. Adapt ContentStartColumn to2672// the position at which we want to format the next line if we do2673// actually reflow.2674// When we reflow, we need to add a space between the end of the current2675// line and the next line's start column.2676ContentStartColumn += RemainingTokenColumns + 1;2677// Get the split that we need to reflow next logical line into the end2678// of the current one; the split will include any leading whitespace of2679// the next logical line.2680BreakableToken::Split SplitBeforeNext =2681Token->getReflowSplit(NextLineIndex, CommentPragmasRegex);2682LLVM_DEBUG(llvm::dbgs()2683<< " Size of reflown text: " << ContentStartColumn2684<< "\n Potential reflow split: ");2685if (SplitBeforeNext.first != StringRef::npos) {2686LLVM_DEBUG(llvm::dbgs() << SplitBeforeNext.first << ", "2687<< SplitBeforeNext.second << "\n");2688TailOffset = SplitBeforeNext.first + SplitBeforeNext.second;2689// If the rest of the next line fits into the current line below the2690// column limit, we can safely reflow.2691RemainingTokenColumns = Token->getRemainingLength(2692NextLineIndex, TailOffset, ContentStartColumn);2693Reflow = true;2694if (ContentStartColumn + RemainingTokenColumns > ColumnLimit) {2695LLVM_DEBUG(llvm::dbgs()2696<< " Over limit after reflow, need: "2697<< (ContentStartColumn + RemainingTokenColumns)2698<< ", space: " << ColumnLimit2699<< ", reflown prefix: " << ContentStartColumn2700<< ", offset in line: " << TailOffset << "\n");2701// If the whole next line does not fit, try to find a point in2702// the next line at which we can break so that attaching the part2703// of the next line to that break point onto the current line is2704// below the column limit.2705BreakableToken::Split Split =2706Token->getSplit(NextLineIndex, TailOffset, ColumnLimit,2707ContentStartColumn, CommentPragmasRegex);2708if (Split.first == StringRef::npos) {2709LLVM_DEBUG(llvm::dbgs() << " Did not find later break\n");2710Reflow = false;2711} else {2712// Check whether the first split point gets us below the column2713// limit. Note that we will execute this split below as part of2714// the normal token breaking and reflow logic within the line.2715unsigned ToSplitColumns = Token->getRangeLength(2716NextLineIndex, TailOffset, Split.first, ContentStartColumn);2717if (ContentStartColumn + ToSplitColumns > ColumnLimit) {2718LLVM_DEBUG(llvm::dbgs() << " Next split protrudes, need: "2719<< (ContentStartColumn + ToSplitColumns)2720<< ", space: " << ColumnLimit);2721unsigned ExcessCharactersPenalty =2722(ContentStartColumn + ToSplitColumns - ColumnLimit) *2723Style.PenaltyExcessCharacter;2724if (NewBreakPenalty < ExcessCharactersPenalty)2725Reflow = false;2726}2727}2728}2729} else {2730LLVM_DEBUG(llvm::dbgs() << "not found.\n");2731}2732}2733if (!Reflow) {2734// If we didn't reflow into the next line, the only space to consider is2735// the next logical line. Reset our state to match the start of the next2736// line.2737TailOffset = 0;2738ContentStartColumn =2739Token->getContentStartColumn(NextLineIndex, /*Break=*/false);2740RemainingTokenColumns = Token->getRemainingLength(2741NextLineIndex, TailOffset, ContentStartColumn);2742// Adapt the start of the token, for example indent.2743if (!DryRun)2744Token->adaptStartOfLine(NextLineIndex, Whitespaces);2745} else {2746// If we found a reflow split and have added a new break before the next2747// line, we are going to remove the line break at the start of the next2748// logical line. For example, here we'll add a new line break after2749// 'text', and subsequently delete the line break between 'that' and2750// 'reflows'.2751// // some text that2752// // reflows2753// ->2754// // some text2755// // that reflows2756// When adding the line break, we also added the penalty for it, so we2757// need to subtract that penalty again when we remove the line break due2758// to reflowing.2759if (NewBreakBefore) {2760assert(Penalty >= NewBreakPenalty);2761Penalty -= NewBreakPenalty;2762}2763if (!DryRun)2764Token->reflow(NextLineIndex, Whitespaces);2765}2766}2767}27682769BreakableToken::Split SplitAfterLastLine =2770Token->getSplitAfterLastLine(TailOffset);2771if (SplitAfterLastLine.first != StringRef::npos) {2772LLVM_DEBUG(llvm::dbgs() << "Replacing whitespace after last line.\n");27732774// We add the last line's penalty here, since that line is going to be split2775// now.2776Penalty += Style.PenaltyExcessCharacter *2777(ContentStartColumn + RemainingTokenColumns - ColumnLimit);27782779if (!DryRun) {2780Token->replaceWhitespaceAfterLastLine(TailOffset, SplitAfterLastLine,2781Whitespaces);2782}2783ContentStartColumn =2784Token->getContentStartColumn(Token->getLineCount() - 1, /*Break=*/true);2785RemainingTokenColumns = Token->getRemainingLength(2786Token->getLineCount() - 1,2787TailOffset + SplitAfterLastLine.first + SplitAfterLastLine.second,2788ContentStartColumn);2789}27902791State.Column = ContentStartColumn + RemainingTokenColumns -2792Current.UnbreakableTailLength;27932794if (BreakInserted) {2795if (!DryRun)2796Token->updateAfterBroken(Whitespaces);27972798// If we break the token inside a parameter list, we need to break before2799// the next parameter on all levels, so that the next parameter is clearly2800// visible. Line comments already introduce a break.2801if (Current.isNot(TT_LineComment))2802for (ParenState &Paren : State.Stack)2803Paren.BreakBeforeParameter = true;28042805if (Current.is(TT_BlockComment))2806State.NoContinuation = true;28072808State.Stack.back().LastSpace = StartColumn;2809}28102811Token->updateNextToken(State);28122813return {Penalty, Exceeded};2814}28152816unsigned ContinuationIndenter::getColumnLimit(const LineState &State) const {2817// In preprocessor directives reserve two chars for trailing " \".2818return Style.ColumnLimit - (State.Line->InPPDirective ? 2 : 0);2819}28202821bool ContinuationIndenter::nextIsMultilineString(const LineState &State) {2822const FormatToken &Current = *State.NextToken;2823if (!Current.isStringLiteral() || Current.is(TT_ImplicitStringLiteral))2824return false;2825// We never consider raw string literals "multiline" for the purpose of2826// AlwaysBreakBeforeMultilineStrings implementation as they are special-cased2827// (see TokenAnnotator::mustBreakBefore().2828if (Current.TokenText.starts_with("R\""))2829return false;2830if (Current.IsMultiline)2831return true;2832if (Current.getNextNonComment() &&2833Current.getNextNonComment()->isStringLiteral()) {2834return true; // Implicit concatenation.2835}2836if (Style.ColumnLimit != 0 && Style.BreakStringLiterals &&2837State.Column + Current.ColumnWidth + Current.UnbreakableTailLength >2838Style.ColumnLimit) {2839return true; // String will be split.2840}2841return false;2842}28432844} // namespace format2845} // namespace clang284628472848