#include "ContinuationIndenter.h"
#include "BreakableToken.h"
#include "FormatInternal.h"
#include "FormatToken.h"
#include "WhitespaceManager.h"
#include "clang/Basic/OperatorPrecedence.h"
#include "clang/Basic/SourceManager.h"
#include "clang/Format/Format.h"
#include "llvm/ADT/StringSet.h"
#include "llvm/Support/Debug.h"
#define DEBUG_TYPE "format-indenter"
namespace clang {
namespace format {
static bool shouldIndentWrappedSelectorName(const FormatStyle &Style,
LineType LineType) {
return Style.IndentWrappedFunctionNames || LineType == LT_ObjCMethodDecl;
}
static unsigned getLengthToMatchingParen(const FormatToken &Tok,
ArrayRef<ParenState> Stack) {
if (!Tok.MatchingParen)
return 0;
FormatToken *End = Tok.MatchingParen;
int MatchingStackIndex = Stack.size() - 1;
auto FindParenState = [&](const FormatToken *LBrace) -> const ParenState * {
while (MatchingStackIndex >= 0 && Stack[MatchingStackIndex].Tok != LBrace)
--MatchingStackIndex;
return MatchingStackIndex >= 0 ? &Stack[MatchingStackIndex] : nullptr;
};
for (; End->Next; End = End->Next) {
if (End->Next->CanBreakBefore)
break;
if (!End->Next->closesScope())
continue;
if (End->Next->MatchingParen &&
End->Next->MatchingParen->isOneOf(
tok::l_brace, TT_ArrayInitializerLSquare, tok::less)) {
const ParenState *State = FindParenState(End->Next->MatchingParen);
if (State && State->BreakBeforeClosingBrace)
break;
}
}
return End->TotalLength - Tok.TotalLength + 1;
}
static unsigned getLengthToNextOperator(const FormatToken &Tok) {
if (!Tok.NextOperator)
return 0;
return Tok.NextOperator->TotalLength - Tok.TotalLength;
}
static bool startsSegmentOfBuilderTypeCall(const FormatToken &Tok) {
return Tok.isMemberAccess() && Tok.Previous && Tok.Previous->closesScope();
}
static bool startsNextParameter(const FormatToken &Current,
const FormatStyle &Style) {
const FormatToken &Previous = *Current.Previous;
if (Current.is(TT_CtorInitializerComma) &&
Style.BreakConstructorInitializers == FormatStyle::BCIS_BeforeComma) {
return true;
}
if (Style.Language == FormatStyle::LK_Proto && Current.is(TT_SelectorName))
return true;
return Previous.is(tok::comma) && !Current.isTrailingComment() &&
((Previous.isNot(TT_CtorInitializerComma) ||
Style.BreakConstructorInitializers !=
FormatStyle::BCIS_BeforeComma) &&
(Previous.isNot(TT_InheritanceComma) ||
Style.BreakInheritanceList != FormatStyle::BILS_BeforeComma));
}
static bool opensProtoMessageField(const FormatToken &LessTok,
const FormatStyle &Style) {
if (LessTok.isNot(tok::less))
return false;
return Style.Language == FormatStyle::LK_TextProto ||
(Style.Language == FormatStyle::LK_Proto &&
(LessTok.NestingLevel > 0 ||
(LessTok.Previous && LessTok.Previous->is(tok::equal))));
}
static llvm::Optional<StringRef> getRawStringDelimiter(StringRef TokenText) {
if (TokenText.size() < 5 || !TokenText.startswith("R\"") || !TokenText.endswith("\"")) {
return None;
}
size_t LParenPos = TokenText.substr(0, 19).find_first_of('(');
if (LParenPos == StringRef::npos)
return None;
StringRef Delimiter = TokenText.substr(2, LParenPos - 2);
size_t RParenPos = TokenText.size() - Delimiter.size() - 2;
if (TokenText[RParenPos] != ')')
return None;
if (!TokenText.substr(RParenPos + 1).startswith(Delimiter))
return None;
return Delimiter;
}
static StringRef
getCanonicalRawStringDelimiter(const FormatStyle &Style,
FormatStyle::LanguageKind Language) {
for (const auto &Format : Style.RawStringFormats)
if (Format.Language == Language)
return StringRef(Format.CanonicalDelimiter);
return "";
}
RawStringFormatStyleManager::RawStringFormatStyleManager(
const FormatStyle &CodeStyle) {
for (const auto &RawStringFormat : CodeStyle.RawStringFormats) {
llvm::Optional<FormatStyle> LanguageStyle =
CodeStyle.GetLanguageStyle(RawStringFormat.Language);
if (!LanguageStyle) {
FormatStyle PredefinedStyle;
if (!getPredefinedStyle(RawStringFormat.BasedOnStyle,
RawStringFormat.Language, &PredefinedStyle)) {
PredefinedStyle = getLLVMStyle();
PredefinedStyle.Language = RawStringFormat.Language;
}
LanguageStyle = PredefinedStyle;
}
LanguageStyle->ColumnLimit = CodeStyle.ColumnLimit;
for (StringRef Delimiter : RawStringFormat.Delimiters)
DelimiterStyle.insert({Delimiter, *LanguageStyle});
for (StringRef EnclosingFunction : RawStringFormat.EnclosingFunctions)
EnclosingFunctionStyle.insert({EnclosingFunction, *LanguageStyle});
}
}
llvm::Optional<FormatStyle>
RawStringFormatStyleManager::getDelimiterStyle(StringRef Delimiter) const {
auto It = DelimiterStyle.find(Delimiter);
if (It == DelimiterStyle.end())
return None;
return It->second;
}
llvm::Optional<FormatStyle>
RawStringFormatStyleManager::getEnclosingFunctionStyle(
StringRef EnclosingFunction) const {
auto It = EnclosingFunctionStyle.find(EnclosingFunction);
if (It == EnclosingFunctionStyle.end())
return None;
return It->second;
}
ContinuationIndenter::ContinuationIndenter(const FormatStyle &Style,
const AdditionalKeywords &Keywords,
const SourceManager &SourceMgr,
WhitespaceManager &Whitespaces,
encoding::Encoding Encoding,
bool BinPackInconclusiveFunctions)
: Style(Style), Keywords(Keywords), SourceMgr(SourceMgr),
Whitespaces(Whitespaces), Encoding(Encoding),
BinPackInconclusiveFunctions(BinPackInconclusiveFunctions),
CommentPragmasRegex(Style.CommentPragmas), RawStringFormats(Style) {}
LineState ContinuationIndenter::getInitialState(unsigned FirstIndent,
unsigned FirstStartColumn,
const AnnotatedLine *Line,
bool DryRun) {
LineState State;
State.FirstIndent = FirstIndent;
if (FirstStartColumn && Line->First->NewlinesBefore == 0)
State.Column = FirstStartColumn;
else
State.Column = FirstIndent;
if (Style.IndentPPDirectives == FormatStyle::PPDIS_AfterHash &&
(Line->Type == LT_PreprocessorDirective ||
Line->Type == LT_ImportStatement)) {
State.Column = 0;
}
State.Line = Line;
State.NextToken = Line->First;
State.Stack.push_back(ParenState(nullptr, FirstIndent, FirstIndent,
false,
false));
State.NoContinuation = false;
State.StartOfStringLiteral = 0;
State.StartOfLineLevel = 0;
State.LowestLevelOnLine = 0;
State.IgnoreStackForComparison = false;
if (Style.Language == FormatStyle::LK_TextProto) {
auto &CurrentState = State.Stack.back();
CurrentState.AvoidBinPacking = true;
CurrentState.BreakBeforeParameter = true;
CurrentState.AlignColons = false;
}
moveStateToNextToken(State, DryRun, false);
return State;
}
bool ContinuationIndenter::canBreak(const LineState &State) {
const FormatToken &Current = *State.NextToken;
const FormatToken &Previous = *Current.Previous;
const auto &CurrentState = State.Stack.back();
assert(&Previous == Current.Previous);
if (!Current.CanBreakBefore && !(CurrentState.BreakBeforeClosingBrace &&
Current.closesBlockOrBlockTypeList(Style))) {
return false;
}
if (!Current.MustBreakBefore && Previous.is(tok::l_brace) &&
Previous.isNot(TT_DictLiteral) && Previous.is(BK_BracedInit) &&
Previous.Previous &&
Previous.Previous->isOneOf(tok::l_brace, tok::l_paren, tok::comma)) {
return false;
}
if (Previous.opensScope() && Previous.isNot(tok::l_brace) &&
State.LowestLevelOnLine < State.StartOfLineLevel &&
State.LowestLevelOnLine < Current.NestingLevel) {
return false;
}
if (Current.isMemberAccess() && CurrentState.ContainsUnwrappedBuilder)
return false;
if (Previous.is(tok::l_brace) && State.Stack.size() > 1 &&
State.Stack[State.Stack.size() - 2].NestedBlockInlined &&
State.Stack[State.Stack.size() - 2].HasMultipleNestedBlocks) {
return false;
}
if (Current.is(TT_FunctionDeclarationName) && State.Column < 6) {
if (Style.AlwaysBreakAfterReturnType == FormatStyle::RTBS_None)
return false;
}
if (!Current.isOneOf(TT_BinaryOperator, tok::comma) &&
CurrentState.NoLineBreakInOperand) {
return false;
}
if (Previous.is(tok::l_square) && Previous.is(TT_ObjCMethodExpr))
return false;
return !CurrentState.NoLineBreak;
}
bool ContinuationIndenter::mustBreak(const LineState &State) {
const FormatToken &Current = *State.NextToken;
const FormatToken &Previous = *Current.Previous;
const auto &CurrentState = State.Stack.back();
if (Style.BraceWrapping.BeforeLambdaBody && Current.CanBreakBefore &&
Current.is(TT_LambdaLBrace) && Previous.isNot(TT_LineComment)) {
auto LambdaBodyLength = getLengthToMatchingParen(Current, State.Stack);
return LambdaBodyLength > getColumnLimit(State);
}
if (Current.MustBreakBefore || Current.is(TT_InlineASMColon))
return true;
if (CurrentState.BreakBeforeClosingBrace &&
Current.closesBlockOrBlockTypeList(Style)) {
return true;
}
if (CurrentState.BreakBeforeClosingParen && Current.is(tok::r_paren))
return true;
if (Style.Language == FormatStyle::LK_ObjC &&
Style.ObjCBreakBeforeNestedBlockParam &&
Current.ObjCSelectorNameParts > 1 &&
Current.startsSequence(TT_SelectorName, tok::colon, tok::caret)) {
return true;
}
if (CurrentState.IsCSharpGenericTypeConstraint &&
Previous.isNot(TT_CSharpGenericTypeConstraintComma)) {
return false;
}
if ((startsNextParameter(Current, Style) || Previous.is(tok::semi) ||
(Previous.is(TT_TemplateCloser) && Current.is(TT_StartOfName) &&
Style.isCpp() &&
(Previous.NestingLevel == 1 || Style.BinPackParameters)) ||
(Style.BreakBeforeTernaryOperators && Current.is(TT_ConditionalExpr) &&
Previous.isNot(tok::question)) ||
(!Style.BreakBeforeTernaryOperators &&
Previous.is(TT_ConditionalExpr))) &&
CurrentState.BreakBeforeParameter && !Current.isTrailingComment() &&
!Current.isOneOf(tok::r_paren, tok::r_brace)) {
return true;
}
if (CurrentState.IsChainedConditional &&
((Style.BreakBeforeTernaryOperators && Current.is(TT_ConditionalExpr) &&
Current.is(tok::colon)) ||
(!Style.BreakBeforeTernaryOperators && Previous.is(TT_ConditionalExpr) &&
Previous.is(tok::colon)))) {
return true;
}
if (((Previous.is(TT_DictLiteral) && Previous.is(tok::l_brace)) ||
(Previous.is(TT_ArrayInitializerLSquare) &&
Previous.ParameterCount > 1) ||
opensProtoMessageField(Previous, Style)) &&
Style.ColumnLimit > 0 &&
getLengthToMatchingParen(Previous, State.Stack) + State.Column - 1 >
getColumnLimit(State)) {
return true;
}
const FormatToken &BreakConstructorInitializersToken =
Style.BreakConstructorInitializers == FormatStyle::BCIS_AfterColon
? Previous
: Current;
if (BreakConstructorInitializersToken.is(TT_CtorInitializerColon) &&
(State.Column + State.Line->Last->TotalLength - Previous.TotalLength >
getColumnLimit(State) ||
CurrentState.BreakBeforeParameter) &&
(!Current.isTrailingComment() || Current.NewlinesBefore > 0) &&
(Style.AllowShortFunctionsOnASingleLine != FormatStyle::SFS_All ||
Style.BreakConstructorInitializers != FormatStyle::BCIS_BeforeColon ||
Style.ColumnLimit != 0)) {
return true;
}
if (Current.is(TT_ObjCMethodExpr) && !Previous.is(TT_SelectorName) &&
State.Line->startsWith(TT_ObjCMethodSpecifier)) {
return true;
}
if (Current.is(TT_SelectorName) && !Previous.is(tok::at) &&
CurrentState.ObjCSelectorNameFound && CurrentState.BreakBeforeParameter &&
(Style.ObjCBreakBeforeNestedBlockParam ||
!Current.startsSequence(TT_SelectorName, tok::colon, tok::caret))) {
return true;
}
unsigned NewLineColumn = getNewLineColumn(State);
if (Current.isMemberAccess() && Style.ColumnLimit != 0 &&
State.Column + getLengthToNextOperator(Current) > Style.ColumnLimit &&
(State.Column > NewLineColumn ||
Current.NestingLevel < State.StartOfLineLevel)) {
return true;
}
if (startsSegmentOfBuilderTypeCall(Current) &&
(CurrentState.CallContinuation != 0 ||
CurrentState.BreakBeforeParameter) &&
!(State.Column <= NewLineColumn && Style.isJavaScript()) &&
!(Previous.closesScopeAfterBlock() && State.Column <= NewLineColumn)) {
return true;
}
if (Previous.ClosesTemplateDeclaration && CurrentState.BreakBeforeParameter &&
Current.CanBreakBefore) {
return true;
}
if (!State.Line->First->is(tok::kw_enum) && State.Column <= NewLineColumn)
return false;
if (Style.AlwaysBreakBeforeMultilineStrings &&
(NewLineColumn == State.FirstIndent + Style.ContinuationIndentWidth ||
Previous.is(tok::comma) || Current.NestingLevel < 2) &&
!Previous.isOneOf(tok::kw_return, tok::lessless, tok::at,
Keywords.kw_dollar) &&
!Previous.isOneOf(TT_InlineASMColon, TT_ConditionalExpr) &&
nextIsMultilineString(State)) {
return true;
}
if (Previous.is(TT_BinaryOperator) && Current.CanBreakBefore) {
const auto PreviousPrecedence = Previous.getPrecedence();
if (PreviousPrecedence != prec::Assignment &&
CurrentState.BreakBeforeParameter && !Current.isTrailingComment()) {
const bool LHSIsBinaryExpr =
Previous.Previous && Previous.Previous->EndsBinaryExpression;
if (LHSIsBinaryExpr)
return true;
const bool IsComparison =
(PreviousPrecedence == prec::Relational ||
PreviousPrecedence == prec::Equality ||
PreviousPrecedence == prec::Spaceship) &&
Previous.Previous &&
Previous.Previous->isNot(TT_BinaryOperator); if (!IsComparison)
return true;
}
} else if (Current.is(TT_BinaryOperator) && Current.CanBreakBefore &&
CurrentState.BreakBeforeParameter) {
return true;
}
if (Current.is(tok::lessless) && Current.isNot(TT_OverloadedOperator) &&
CurrentState.BreakBeforeParameter && CurrentState.FirstLessLess == 0) {
return true;
}
if (Current.NestingLevel == 0 && !Current.isTrailingComment()) {
if (Previous.ClosesTemplateDeclaration) {
if (Current.is(tok::kw_concept)) {
switch (Style.BreakBeforeConceptDeclarations) {
case FormatStyle::BBCDS_Allowed:
break;
case FormatStyle::BBCDS_Always:
return true;
case FormatStyle::BBCDS_Never:
return false;
}
}
if (Current.is(TT_RequiresClause)) {
switch (Style.RequiresClausePosition) {
case FormatStyle::RCPS_SingleLine:
case FormatStyle::RCPS_WithPreceding:
return false;
default:
return true;
}
}
return Style.AlwaysBreakTemplateDeclarations != FormatStyle::BTDS_No;
}
if (Previous.is(TT_FunctionAnnotationRParen) &&
State.Line->Type != LT_PreprocessorDirective) {
return true;
}
if (Previous.is(TT_LeadingJavaAnnotation) && Current.isNot(tok::l_paren) &&
Current.isNot(TT_LeadingJavaAnnotation)) {
return true;
}
}
if (Style.isJavaScript() && Previous.is(tok::r_paren) &&
Previous.is(TT_JavaAnnotation)) {
static const llvm::StringSet<> BreakBeforeDecoratedTokens = {"get", "set",
"function"};
if (BreakBeforeDecoratedTokens.contains(Current.TokenText))
return true;
}
if (((Current.is(TT_FunctionDeclarationName) &&
(!Style.isCSharp() ||
Style.AlwaysBreakAfterReturnType != FormatStyle::RTBS_None) &&
!Style.isJavaScript()) ||
(Current.is(tok::kw_operator) && !Previous.is(tok::coloncolon))) &&
!Previous.is(tok::kw_template) && CurrentState.BreakBeforeParameter) {
return true;
}
if (Style.ColumnLimit != 0 && Previous.is(BK_Block) &&
Previous.is(tok::l_brace) &&
!Current.isOneOf(tok::r_brace, tok::comment)) {
return true;
}
if (Current.is(tok::lessless) &&
((Previous.is(tok::identifier) && Previous.TokenText == "endl") ||
(Previous.Tok.isLiteral() && (Previous.TokenText.endswith("\\n\"") ||
Previous.TokenText == "\'\\n\'")))) {
return true;
}
if (Previous.is(TT_BlockComment) && Previous.IsMultiline)
return true;
if (State.NoContinuation)
return true;
return false;
}
unsigned ContinuationIndenter::addTokenToState(LineState &State, bool Newline,
bool DryRun,
unsigned ExtraSpaces) {
const FormatToken &Current = *State.NextToken;
assert(State.NextToken->Previous);
const FormatToken &Previous = *State.NextToken->Previous;
assert(!State.Stack.empty());
State.NoContinuation = false;
if ((Current.is(TT_ImplicitStringLiteral) &&
(Previous.Tok.getIdentifierInfo() == nullptr ||
Previous.Tok.getIdentifierInfo()->getPPKeywordID() ==
tok::pp_not_keyword))) {
unsigned EndColumn =
SourceMgr.getSpellingColumnNumber(Current.WhitespaceRange.getEnd());
if (Current.LastNewlineOffset != 0) {
State.Column = EndColumn;
} else {
unsigned StartColumn =
SourceMgr.getSpellingColumnNumber(Current.WhitespaceRange.getBegin());
assert(EndColumn >= StartColumn);
State.Column += EndColumn - StartColumn;
}
moveStateToNextToken(State, DryRun, false);
return 0;
}
unsigned Penalty = 0;
if (Newline)
Penalty = addTokenOnNewLine(State, DryRun);
else
addTokenOnCurrentLine(State, DryRun, ExtraSpaces);
return moveStateToNextToken(State, DryRun, Newline) + Penalty;
}
void ContinuationIndenter::addTokenOnCurrentLine(LineState &State, bool DryRun,
unsigned ExtraSpaces) {
FormatToken &Current = *State.NextToken;
assert(State.NextToken->Previous);
const FormatToken &Previous = *State.NextToken->Previous;
auto &CurrentState = State.Stack.back();
if (Current.is(tok::equal) &&
(State.Line->First->is(tok::kw_for) || Current.NestingLevel == 0) &&
CurrentState.VariablePos == 0) {
CurrentState.VariablePos = State.Column;
const FormatToken *Tok = &Previous;
while (Tok && CurrentState.VariablePos >= Tok->ColumnWidth) {
CurrentState.VariablePos -= Tok->ColumnWidth;
if (Tok->SpacesRequiredBefore != 0)
break;
Tok = Tok->Previous;
}
if (Previous.PartOfMultiVariableDeclStmt)
CurrentState.LastSpace = CurrentState.VariablePos;
}
unsigned Spaces = Current.SpacesRequiredBefore + ExtraSpaces;
int PPColumnCorrection = 0;
if (Style.IndentPPDirectives == FormatStyle::PPDIS_AfterHash &&
Previous.is(tok::hash) && State.FirstIndent > 0 &&
&Previous == State.Line->First &&
(State.Line->Type == LT_PreprocessorDirective ||
State.Line->Type == LT_ImportStatement)) {
Spaces += State.FirstIndent;
if (Style.UseTab != FormatStyle::UT_Never)
PPColumnCorrection = -1;
}
if (!DryRun) {
Whitespaces.replaceWhitespace(Current, 0, Spaces,
State.Column + Spaces + PPColumnCorrection);
}
if (Style.BreakInheritanceList == FormatStyle::BILS_BeforeComma &&
Current.is(TT_InheritanceColon)) {
CurrentState.NoLineBreak = true;
}
if (Style.BreakInheritanceList == FormatStyle::BILS_AfterColon &&
Previous.is(TT_InheritanceColon)) {
CurrentState.NoLineBreak = true;
}
if (Current.is(TT_SelectorName) && !CurrentState.ObjCSelectorNameFound) {
unsigned MinIndent = std::max(
State.FirstIndent + Style.ContinuationIndentWidth, CurrentState.Indent);
unsigned FirstColonPos = State.Column + Spaces + Current.ColumnWidth;
if (Current.LongestObjCSelectorName == 0)
CurrentState.AlignColons = false;
else if (MinIndent + Current.LongestObjCSelectorName > FirstColonPos)
CurrentState.ColonPos = MinIndent + Current.LongestObjCSelectorName;
else
CurrentState.ColonPos = FirstColonPos;
}
if ((Style.AlignAfterOpenBracket == FormatStyle::BAS_AlwaysBreak ||
Style.AlignAfterOpenBracket == FormatStyle::BAS_BlockIndent) &&
(Previous.isOneOf(tok::l_paren, TT_TemplateOpener, tok::l_square) ||
(Previous.is(tok::l_brace) && Previous.isNot(BK_Block) &&
Style.Cpp11BracedListStyle)) &&
State.Column > getNewLineColumn(State) &&
(!Previous.Previous || !Previous.Previous->isOneOf(
tok::kw_for, tok::kw_while, tok::kw_switch)) &&
Current.FakeLParens.size() > 0 &&
Current.FakeLParens.back() > prec::Unknown) {
CurrentState.NoLineBreak = true;
}
if (Previous.is(TT_TemplateString) && Previous.opensScope())
CurrentState.NoLineBreak = true;
if (Style.AlignAfterOpenBracket != FormatStyle::BAS_DontAlign &&
!CurrentState.IsCSharpGenericTypeConstraint && Previous.opensScope() &&
Previous.isNot(TT_ObjCMethodExpr) && Previous.isNot(TT_RequiresClause) &&
(Current.isNot(TT_LineComment) || Previous.is(BK_BracedInit))) {
CurrentState.Indent = State.Column + Spaces;
CurrentState.IsAligned = true;
}
if (CurrentState.AvoidBinPacking && startsNextParameter(Current, Style))
CurrentState.NoLineBreak = true;
if (startsSegmentOfBuilderTypeCall(Current) &&
State.Column > getNewLineColumn(State)) {
CurrentState.ContainsUnwrappedBuilder = true;
}
if (Current.is(TT_LambdaArrow) && Style.Language == FormatStyle::LK_Java)
CurrentState.NoLineBreak = true;
if (Current.isMemberAccess() && Previous.is(tok::r_paren) &&
(Previous.MatchingParen &&
(Previous.TotalLength - Previous.MatchingParen->TotalLength > 10))) {
CurrentState.NoLineBreak = true;
}
const FormatToken *P = Current.getPreviousNonComment();
if (!Current.is(tok::comment) && P &&
(P->isOneOf(TT_BinaryOperator, tok::comma) ||
(P->is(TT_ConditionalExpr) && P->is(tok::colon))) &&
!P->isOneOf(TT_OverloadedOperator, TT_CtorInitializerComma) &&
P->getPrecedence() != prec::Assignment &&
P->getPrecedence() != prec::Relational &&
P->getPrecedence() != prec::Spaceship) {
bool BreakBeforeOperator =
P->MustBreakBefore || P->is(tok::lessless) ||
(P->is(TT_BinaryOperator) &&
Style.BreakBeforeBinaryOperators != FormatStyle::BOS_None) ||
(P->is(TT_ConditionalExpr) && Style.BreakBeforeTernaryOperators);
bool HasTwoOperands =
P->OperatorIndex == 0 && !P->NextOperator && !P->is(TT_ConditionalExpr);
if ((!BreakBeforeOperator &&
!(HasTwoOperands &&
Style.AlignOperands != FormatStyle::OAS_DontAlign)) ||
(!CurrentState.LastOperatorWrapped && BreakBeforeOperator)) {
CurrentState.NoLineBreakInOperand = true;
}
}
State.Column += Spaces;
if (Current.isNot(tok::comment) && Previous.is(tok::l_paren) &&
Previous.Previous &&
(Previous.Previous->is(tok::kw_for) || Previous.Previous->isIf())) {
CurrentState.LastSpace = State.Column;
CurrentState.NestedBlockIndent = State.Column;
} else if (!Current.isOneOf(tok::comment, tok::caret) &&
((Previous.is(tok::comma) &&
!Previous.is(TT_OverloadedOperator)) ||
(Previous.is(tok::colon) && Previous.is(TT_ObjCMethodExpr)))) {
CurrentState.LastSpace = State.Column;
} else if (Previous.is(TT_CtorInitializerColon) &&
(!Current.isTrailingComment() || Current.NewlinesBefore > 0) &&
Style.BreakConstructorInitializers ==
FormatStyle::BCIS_AfterColon) {
CurrentState.Indent = State.Column;
CurrentState.LastSpace = State.Column;
} else if ((Previous.isOneOf(TT_BinaryOperator, TT_ConditionalExpr,
TT_CtorInitializerColon)) &&
((Previous.getPrecedence() != prec::Assignment &&
(Previous.isNot(tok::lessless) || Previous.OperatorIndex != 0 ||
Previous.NextOperator)) ||
Current.StartsBinaryExpression)) {
if (Style.BreakBeforeBinaryOperators == FormatStyle::BOS_None)
CurrentState.LastSpace = State.Column;
} else if (Previous.is(TT_InheritanceColon)) {
CurrentState.Indent = State.Column;
CurrentState.LastSpace = State.Column;
} else if (Current.is(TT_CSharpGenericTypeConstraintColon)) {
CurrentState.ColonPos = State.Column;
} else if (Previous.opensScope()) {
if (Previous.MatchingParen) {
const FormatToken *Next = Previous.MatchingParen->getNextNonComment();
if (Next && Next->isMemberAccess() && State.Stack.size() > 1 &&
State.Stack[State.Stack.size() - 2].CallContinuation == 0) {
CurrentState.LastSpace = State.Column;
}
}
}
}
unsigned ContinuationIndenter::addTokenOnNewLine(LineState &State,
bool DryRun) {
FormatToken &Current = *State.NextToken;
assert(State.NextToken->Previous);
const FormatToken &Previous = *State.NextToken->Previous;
auto &CurrentState = State.Stack.back();
unsigned Penalty = 0;
const FormatToken *PreviousNonComment = Current.getPreviousNonComment();
const FormatToken *NextNonComment = Previous.getNextNonComment();
if (!NextNonComment)
NextNonComment = &Current;
if (!CurrentState.ContainsLineBreak)
Penalty += 15;
CurrentState.ContainsLineBreak = true;
Penalty += State.NextToken->SplitPenalty;
if (NextNonComment->is(tok::lessless) && CurrentState.FirstLessLess == 0 &&
(State.Column <= Style.ColumnLimit / 3 ||
CurrentState.BreakBeforeParameter)) {
Penalty += Style.PenaltyBreakFirstLessLess;
}
State.Column = getNewLineColumn(State);
if (State.Column > State.FirstIndent) {
Penalty +=
Style.PenaltyIndentedWhitespace * (State.Column - State.FirstIndent);
}
if (!Current.is(TT_LambdaArrow) &&
(!Style.isJavaScript() || Current.NestingLevel != 0 ||
!PreviousNonComment || !PreviousNonComment->is(tok::equal) ||
!Current.isOneOf(Keywords.kw_async, Keywords.kw_function))) {
CurrentState.NestedBlockIndent = State.Column;
}
if (NextNonComment->isMemberAccess()) {
if (CurrentState.CallContinuation == 0)
CurrentState.CallContinuation = State.Column;
} else if (NextNonComment->is(TT_SelectorName)) {
if (!CurrentState.ObjCSelectorNameFound) {
if (NextNonComment->LongestObjCSelectorName == 0) {
CurrentState.AlignColons = false;
} else {
CurrentState.ColonPos =
(shouldIndentWrappedSelectorName(Style, State.Line->Type)
? std::max(CurrentState.Indent,
State.FirstIndent + Style.ContinuationIndentWidth)
: CurrentState.Indent) +
std::max(NextNonComment->LongestObjCSelectorName,
NextNonComment->ColumnWidth);
}
} else if (CurrentState.AlignColons &&
CurrentState.ColonPos <= NextNonComment->ColumnWidth) {
CurrentState.ColonPos = State.Column + NextNonComment->ColumnWidth;
}
} else if (PreviousNonComment && PreviousNonComment->is(tok::colon) &&
PreviousNonComment->isOneOf(TT_ObjCMethodExpr, TT_DictLiteral)) {
if (State.Stack.size() > 1) {
State.Stack[State.Stack.size() - 2].LastSpace =
std::max(CurrentState.LastSpace, CurrentState.Indent) +
Style.ContinuationIndentWidth;
}
}
if ((PreviousNonComment &&
PreviousNonComment->isOneOf(tok::comma, tok::semi) &&
!CurrentState.AvoidBinPacking) ||
Previous.is(TT_BinaryOperator)) {
CurrentState.BreakBeforeParameter = false;
}
if (PreviousNonComment &&
(PreviousNonComment->isOneOf(TT_TemplateCloser, TT_JavaAnnotation) ||
PreviousNonComment->ClosesRequiresClause) &&
Current.NestingLevel == 0) {
CurrentState.BreakBeforeParameter = false;
}
if (NextNonComment->is(tok::question) ||
(PreviousNonComment && PreviousNonComment->is(tok::question))) {
CurrentState.BreakBeforeParameter = true;
}
if (Current.is(TT_BinaryOperator) && Current.CanBreakBefore)
CurrentState.BreakBeforeParameter = false;
if (!DryRun) {
unsigned MaxEmptyLinesToKeep = Style.MaxEmptyLinesToKeep + 1;
if (Current.is(tok::r_brace) && Current.MatchingParen &&
!Current.MatchingParen->Children.empty()) {
MaxEmptyLinesToKeep = 1;
}
unsigned Newlines =
std::max(1u, std::min(Current.NewlinesBefore, MaxEmptyLinesToKeep));
bool ContinuePPDirective =
State.Line->InPPDirective && State.Line->Type != LT_ImportStatement;
Whitespaces.replaceWhitespace(Current, Newlines, State.Column, State.Column,
CurrentState.IsAligned, ContinuePPDirective);
}
if (!Current.isTrailingComment())
CurrentState.LastSpace = State.Column;
if (Current.is(tok::lessless)) {
CurrentState.LastSpace += 3; }
State.StartOfLineLevel = Current.NestingLevel;
State.LowestLevelOnLine = Current.NestingLevel;
bool NestedBlockSpecialCase =
(!Style.isCpp() && Current.is(tok::r_brace) && State.Stack.size() > 1 &&
State.Stack[State.Stack.size() - 2].NestedBlockInlined) ||
(Style.Language == FormatStyle::LK_ObjC && Current.is(tok::r_brace) &&
State.Stack.size() > 1 && !Style.ObjCBreakBeforeNestedBlockParam);
NestedBlockSpecialCase =
NestedBlockSpecialCase ||
(Current.MatchingParen &&
Current.MatchingParen->is(TT_RequiresExpressionLBrace));
if (!NestedBlockSpecialCase)
for (ParenState &PState : llvm::drop_end(State.Stack))
PState.BreakBeforeParameter = true;
if (PreviousNonComment &&
!PreviousNonComment->isOneOf(tok::comma, tok::colon, tok::semi) &&
((PreviousNonComment->isNot(TT_TemplateCloser) &&
!PreviousNonComment->ClosesRequiresClause) ||
Current.NestingLevel != 0) &&
!PreviousNonComment->isOneOf(
TT_BinaryOperator, TT_FunctionAnnotationRParen, TT_JavaAnnotation,
TT_LeadingJavaAnnotation) &&
Current.isNot(TT_BinaryOperator) && !PreviousNonComment->opensScope()) {
CurrentState.BreakBeforeParameter = true;
}
if (PreviousNonComment &&
(PreviousNonComment->isOneOf(tok::l_brace, TT_ArrayInitializerLSquare) ||
opensProtoMessageField(*PreviousNonComment, Style))) {
CurrentState.BreakBeforeClosingBrace = true;
}
if (PreviousNonComment && PreviousNonComment->is(tok::l_paren)) {
CurrentState.BreakBeforeClosingParen =
Style.AlignAfterOpenBracket == FormatStyle::BAS_BlockIndent;
}
if (CurrentState.AvoidBinPacking) {
bool PreviousIsBreakingCtorInitializerColon =
PreviousNonComment && PreviousNonComment->is(TT_CtorInitializerColon) &&
Style.BreakConstructorInitializers == FormatStyle::BCIS_AfterColon;
if (!(Previous.isOneOf(tok::l_paren, tok::l_brace, TT_BinaryOperator) ||
PreviousIsBreakingCtorInitializerColon) ||
(!Style.AllowAllParametersOfDeclarationOnNextLine &&
State.Line->MustBeDeclaration) ||
(!Style.AllowAllArgumentsOnNextLine &&
!State.Line->MustBeDeclaration) ||
(Style.PackConstructorInitializers != FormatStyle::PCIS_NextLine &&
PreviousIsBreakingCtorInitializerColon) ||
Previous.is(TT_DictLiteral)) {
CurrentState.BreakBeforeParameter = true;
}
if (PreviousIsBreakingCtorInitializerColon &&
Style.PackConstructorInitializers == FormatStyle::PCIS_NextLine) {
CurrentState.BreakBeforeParameter = false;
}
}
return Penalty;
}
unsigned ContinuationIndenter::getNewLineColumn(const LineState &State) {
if (!State.NextToken || !State.NextToken->Previous)
return 0;
FormatToken &Current = *State.NextToken;
const auto &CurrentState = State.Stack.back();
if (CurrentState.IsCSharpGenericTypeConstraint &&
Current.isNot(TT_CSharpGenericTypeConstraint)) {
return CurrentState.ColonPos + 2;
}
const FormatToken &Previous = *Current.Previous;
unsigned ContinuationIndent =
std::max(CurrentState.LastSpace, CurrentState.Indent) +
Style.ContinuationIndentWidth;
const FormatToken *PreviousNonComment = Current.getPreviousNonComment();
const FormatToken *NextNonComment = Previous.getNextNonComment();
if (!NextNonComment)
NextNonComment = &Current;
if (Style.Language == FormatStyle::LK_Java &&
Current.isOneOf(Keywords.kw_implements, Keywords.kw_extends)) {
return std::max(CurrentState.LastSpace,
CurrentState.Indent + Style.ContinuationIndentWidth);
}
if (Style.BreakBeforeBraces == FormatStyle::BS_Whitesmiths &&
State.Line->First->is(tok::kw_enum)) {
return (Style.IndentWidth * State.Line->First->IndentLevel) +
Style.IndentWidth;
}
if (NextNonComment->is(tok::l_brace) && NextNonComment->is(BK_Block))
return Current.NestingLevel == 0 ? State.FirstIndent : CurrentState.Indent;
if ((Current.isOneOf(tok::r_brace, tok::r_square) ||
(Current.is(tok::greater) &&
(Style.Language == FormatStyle::LK_Proto ||
Style.Language == FormatStyle::LK_TextProto))) &&
State.Stack.size() > 1) {
if (Current.closesBlockOrBlockTypeList(Style))
return State.Stack[State.Stack.size() - 2].NestedBlockIndent;
if (Current.MatchingParen && Current.MatchingParen->is(BK_BracedInit))
return State.Stack[State.Stack.size() - 2].LastSpace;
return State.FirstIndent;
}
if (Current.is(tok::r_paren) && State.Stack.size() > 1 &&
(!Current.Next ||
Current.Next->isOneOf(tok::semi, tok::kw_const, tok::l_brace))) {
return State.Stack[State.Stack.size() - 2].LastSpace;
}
if (Style.AlignAfterOpenBracket == FormatStyle::BAS_BlockIndent &&
Current.is(tok::r_paren) && State.Stack.size() > 1) {
return State.Stack[State.Stack.size() - 2].LastSpace;
}
if (NextNonComment->is(TT_TemplateString) && NextNonComment->closesScope())
return State.Stack[State.Stack.size() - 2].LastSpace;
if (Current.is(tok::identifier) && Current.Next &&
(Current.Next->is(TT_DictLiteral) ||
((Style.Language == FormatStyle::LK_Proto ||
Style.Language == FormatStyle::LK_TextProto) &&
Current.Next->isOneOf(tok::less, tok::l_brace)))) {
return CurrentState.Indent;
}
if (NextNonComment->is(TT_ObjCStringLiteral) &&
State.StartOfStringLiteral != 0) {
return State.StartOfStringLiteral - 1;
}
if (NextNonComment->isStringLiteral() && State.StartOfStringLiteral != 0)
return State.StartOfStringLiteral;
if (NextNonComment->is(tok::lessless) && CurrentState.FirstLessLess != 0)
return CurrentState.FirstLessLess;
if (NextNonComment->isMemberAccess()) {
if (CurrentState.CallContinuation == 0)
return ContinuationIndent;
return CurrentState.CallContinuation;
}
if (CurrentState.QuestionColumn != 0 &&
((NextNonComment->is(tok::colon) &&
NextNonComment->is(TT_ConditionalExpr)) ||
Previous.is(TT_ConditionalExpr))) {
if (((NextNonComment->is(tok::colon) && NextNonComment->Next &&
!NextNonComment->Next->FakeLParens.empty() &&
NextNonComment->Next->FakeLParens.back() == prec::Conditional) ||
(Previous.is(tok::colon) && !Current.FakeLParens.empty() &&
Current.FakeLParens.back() == prec::Conditional)) &&
!CurrentState.IsWrappedConditional) {
unsigned Indent = CurrentState.Indent;
if (Style.AlignOperands != FormatStyle::OAS_DontAlign)
Indent -= Style.ContinuationIndentWidth;
if (Style.BreakBeforeTernaryOperators && CurrentState.UnindentOperator)
Indent -= 2;
return Indent;
}
return CurrentState.QuestionColumn;
}
if (Previous.is(tok::comma) && CurrentState.VariablePos != 0)
return CurrentState.VariablePos;
if (Current.is(TT_RequiresClause)) {
if (Style.IndentRequiresClause)
return CurrentState.Indent + Style.IndentWidth;
switch (Style.RequiresClausePosition) {
case FormatStyle::RCPS_OwnLine:
case FormatStyle::RCPS_WithFollowing:
return CurrentState.Indent;
default:
break;
}
}
if (NextNonComment->isOneOf(TT_CtorInitializerColon, TT_InheritanceColon,
TT_InheritanceComma)) {
return State.FirstIndent + Style.ConstructorInitializerIndentWidth;
}
if ((PreviousNonComment &&
(PreviousNonComment->ClosesTemplateDeclaration ||
PreviousNonComment->ClosesRequiresClause ||
PreviousNonComment->isOneOf(
TT_AttributeParen, TT_AttributeSquare, TT_FunctionAnnotationRParen,
TT_JavaAnnotation, TT_LeadingJavaAnnotation))) ||
(!Style.IndentWrappedFunctionNames &&
NextNonComment->isOneOf(tok::kw_operator, TT_FunctionDeclarationName))) {
return std::max(CurrentState.LastSpace, CurrentState.Indent);
}
if (NextNonComment->is(TT_SelectorName)) {
if (!CurrentState.ObjCSelectorNameFound) {
unsigned MinIndent = CurrentState.Indent;
if (shouldIndentWrappedSelectorName(Style, State.Line->Type)) {
MinIndent = std::max(MinIndent,
State.FirstIndent + Style.ContinuationIndentWidth);
}
return MinIndent +
std::max(NextNonComment->LongestObjCSelectorName,
NextNonComment->ColumnWidth) -
NextNonComment->ColumnWidth;
}
if (!CurrentState.AlignColons)
return CurrentState.Indent;
if (CurrentState.ColonPos > NextNonComment->ColumnWidth)
return CurrentState.ColonPos - NextNonComment->ColumnWidth;
return CurrentState.Indent;
}
if (NextNonComment->is(tok::colon) && NextNonComment->is(TT_ObjCMethodExpr))
return CurrentState.ColonPos;
if (NextNonComment->is(TT_ArraySubscriptLSquare)) {
if (CurrentState.StartOfArraySubscripts != 0) {
return CurrentState.StartOfArraySubscripts;
} else if (Style.isCSharp()) { return CurrentState.Indent;
}
return ContinuationIndent;
}
if (NextNonComment->is(tok::identifier) && NextNonComment->FakeRParens == 0 &&
NextNonComment->Next && NextNonComment->Next->is(TT_ObjCMethodExpr)) {
return CurrentState.Indent;
}
if (NextNonComment->isOneOf(TT_StartOfName, TT_PointerOrReference) ||
Previous.isOneOf(tok::coloncolon, tok::equal, TT_JsTypeColon)) {
return ContinuationIndent;
}
if (PreviousNonComment && PreviousNonComment->is(tok::colon) &&
PreviousNonComment->isOneOf(TT_ObjCMethodExpr, TT_DictLiteral)) {
return ContinuationIndent;
}
if (NextNonComment->is(TT_CtorInitializerComma))
return CurrentState.Indent;
if (PreviousNonComment && PreviousNonComment->is(TT_CtorInitializerColon) &&
Style.BreakConstructorInitializers == FormatStyle::BCIS_AfterColon) {
return CurrentState.Indent;
}
if (PreviousNonComment && PreviousNonComment->is(TT_InheritanceColon) &&
Style.BreakInheritanceList == FormatStyle::BILS_AfterColon) {
return CurrentState.Indent;
}
if (Previous.is(tok::r_paren) && !Current.isBinaryOperator() &&
!Current.isOneOf(tok::colon, tok::comment)) {
return ContinuationIndent;
}
if (Current.is(TT_ProtoExtensionLSquare))
return CurrentState.Indent;
if (Current.isBinaryOperator() && CurrentState.UnindentOperator) {
return CurrentState.Indent - Current.Tok.getLength() -
Current.SpacesRequiredBefore;
}
if (Current.isOneOf(tok::comment, TT_BlockComment, TT_LineComment) &&
NextNonComment->isBinaryOperator() && CurrentState.UnindentOperator) {
return CurrentState.Indent - NextNonComment->Tok.getLength() -
NextNonComment->SpacesRequiredBefore;
}
if (CurrentState.Indent == State.FirstIndent && PreviousNonComment &&
!PreviousNonComment->isOneOf(tok::r_brace, TT_CtorInitializerComma)) {
return CurrentState.Indent + Style.ContinuationIndentWidth;
}
return CurrentState.Indent;
}
static bool hasNestedBlockInlined(const FormatToken *Previous,
const FormatToken &Current,
const FormatStyle &Style) {
if (Previous->isNot(tok::l_paren))
return true;
if (Previous->ParameterCount > 1)
return true;
return Style.BraceWrapping.BeforeLambdaBody && Current.is(TT_LambdaLSquare);
}
unsigned ContinuationIndenter::moveStateToNextToken(LineState &State,
bool DryRun, bool Newline) {
assert(State.Stack.size());
const FormatToken &Current = *State.NextToken;
auto &CurrentState = State.Stack.back();
if (Current.is(TT_CSharpGenericTypeConstraint))
CurrentState.IsCSharpGenericTypeConstraint = true;
if (Current.isOneOf(tok::comma, TT_BinaryOperator))
CurrentState.NoLineBreakInOperand = false;
if (Current.isOneOf(TT_InheritanceColon, TT_CSharpGenericTypeConstraintColon))
CurrentState.AvoidBinPacking = true;
if (Current.is(tok::lessless) && Current.isNot(TT_OverloadedOperator)) {
if (CurrentState.FirstLessLess == 0)
CurrentState.FirstLessLess = State.Column;
else
CurrentState.LastOperatorWrapped = Newline;
}
if (Current.is(TT_BinaryOperator) && Current.isNot(tok::lessless))
CurrentState.LastOperatorWrapped = Newline;
if (Current.is(TT_ConditionalExpr) && Current.Previous &&
!Current.Previous->is(TT_ConditionalExpr)) {
CurrentState.LastOperatorWrapped = Newline;
}
if (Current.is(TT_ArraySubscriptLSquare) &&
CurrentState.StartOfArraySubscripts == 0) {
CurrentState.StartOfArraySubscripts = State.Column;
}
auto IsWrappedConditional = [](const FormatToken &Tok) {
if (!(Tok.is(TT_ConditionalExpr) && Tok.is(tok::question)))
return false;
if (Tok.MustBreakBefore)
return true;
const FormatToken *Next = Tok.getNextNonComment();
return Next && Next->MustBreakBefore;
};
if (IsWrappedConditional(Current))
CurrentState.IsWrappedConditional = true;
if (Style.BreakBeforeTernaryOperators && Current.is(tok::question))
CurrentState.QuestionColumn = State.Column;
if (!Style.BreakBeforeTernaryOperators && Current.isNot(tok::colon)) {
const FormatToken *Previous = Current.Previous;
while (Previous && Previous->isTrailingComment())
Previous = Previous->Previous;
if (Previous && Previous->is(tok::question))
CurrentState.QuestionColumn = State.Column;
}
if (!Current.opensScope() && !Current.closesScope() &&
!Current.is(TT_PointerOrReference)) {
State.LowestLevelOnLine =
std::min(State.LowestLevelOnLine, Current.NestingLevel);
}
if (Current.isMemberAccess())
CurrentState.StartOfFunctionCall = !Current.NextOperator ? 0 : State.Column;
if (Current.is(TT_SelectorName))
CurrentState.ObjCSelectorNameFound = true;
if (Current.is(TT_CtorInitializerColon) &&
Style.BreakConstructorInitializers != FormatStyle::BCIS_AfterColon) {
CurrentState.Indent = State.Column + (Style.BreakConstructorInitializers ==
FormatStyle::BCIS_BeforeComma
? 0
: 2);
CurrentState.NestedBlockIndent = CurrentState.Indent;
if (Style.PackConstructorInitializers > FormatStyle::PCIS_BinPack) {
CurrentState.AvoidBinPacking = true;
CurrentState.BreakBeforeParameter =
Style.PackConstructorInitializers != FormatStyle::PCIS_NextLine;
} else {
CurrentState.BreakBeforeParameter = false;
}
}
if (Current.is(TT_CtorInitializerColon) &&
Style.BreakConstructorInitializers == FormatStyle::BCIS_AfterColon) {
CurrentState.Indent =
State.FirstIndent + Style.ConstructorInitializerIndentWidth;
CurrentState.NestedBlockIndent = CurrentState.Indent;
if (Style.PackConstructorInitializers > FormatStyle::PCIS_BinPack)
CurrentState.AvoidBinPacking = true;
}
if (Current.is(TT_InheritanceColon)) {
CurrentState.Indent =
State.FirstIndent + Style.ConstructorInitializerIndentWidth;
}
if (Current.isOneOf(TT_BinaryOperator, TT_ConditionalExpr) && Newline)
CurrentState.NestedBlockIndent = State.Column + Current.ColumnWidth + 1;
if (Current.isOneOf(TT_LambdaLSquare, TT_LambdaArrow))
CurrentState.LastSpace = State.Column;
if (Current.is(TT_RequiresExpression))
CurrentState.NestedBlockIndent = State.Column;
const FormatToken *Previous = Current.getPreviousNonComment();
if (Current.isNot(tok::comment) && !Current.ClosesRequiresClause &&
Previous && Previous->isOneOf(tok::l_brace, TT_ArrayInitializerLSquare) &&
!Previous->is(TT_DictLiteral) && State.Stack.size() > 1 &&
!CurrentState.HasMultipleNestedBlocks) {
if (State.Stack[State.Stack.size() - 2].NestedBlockInlined && Newline)
for (ParenState &PState : llvm::drop_end(State.Stack))
PState.NoLineBreak = true;
State.Stack[State.Stack.size() - 2].NestedBlockInlined = false;
}
if (Previous && (Previous->isOneOf(TT_BinaryOperator, TT_ConditionalExpr) ||
(Previous->isOneOf(tok::l_paren, tok::comma, tok::colon) &&
!Previous->isOneOf(TT_DictLiteral, TT_ObjCMethodExpr)))) {
CurrentState.NestedBlockInlined =
!Newline && hasNestedBlockInlined(Previous, Current, Style);
}
moveStatePastFakeLParens(State, Newline);
moveStatePastScopeCloser(State);
bool AllowBreak = !State.Stack.back().NoLineBreak &&
!State.Stack.back().NoLineBreakInOperand;
moveStatePastScopeOpener(State, Newline);
moveStatePastFakeRParens(State);
if (Current.is(TT_ObjCStringLiteral) && State.StartOfStringLiteral == 0)
State.StartOfStringLiteral = State.Column + 1;
if (Current.is(TT_CSharpStringLiteral) && State.StartOfStringLiteral == 0) {
State.StartOfStringLiteral = State.Column + 1;
} else if (Current.isStringLiteral() && State.StartOfStringLiteral == 0) {
State.StartOfStringLiteral = State.Column;
} else if (!Current.isOneOf(tok::comment, tok::identifier, tok::hash) &&
!Current.isStringLiteral()) {
State.StartOfStringLiteral = 0;
}
State.Column += Current.ColumnWidth;
State.NextToken = State.NextToken->Next;
unsigned Penalty =
handleEndOfLine(Current, State, DryRun, AllowBreak, Newline);
if (Current.Role)
Current.Role->formatFromToken(State, this, DryRun);
if (Previous && Previous->Role)
Penalty += Previous->Role->formatAfterToken(State, this, DryRun);
return Penalty;
}
void ContinuationIndenter::moveStatePastFakeLParens(LineState &State,
bool Newline) {
const FormatToken &Current = *State.NextToken;
if (Current.FakeLParens.empty())
return;
const FormatToken *Previous = Current.getPreviousNonComment();
bool SkipFirstExtraIndent =
Previous &&
(Previous->opensScope() ||
Previous->isOneOf(tok::semi, tok::kw_return, TT_RequiresClause) ||
(Previous->getPrecedence() == prec::Assignment &&
Style.AlignOperands != FormatStyle::OAS_DontAlign) ||
Previous->is(TT_ObjCMethodExpr));
for (const auto &PrecedenceLevel : llvm::reverse(Current.FakeLParens)) {
const auto &CurrentState = State.Stack.back();
ParenState NewParenState = CurrentState;
NewParenState.Tok = nullptr;
NewParenState.ContainsLineBreak = false;
NewParenState.LastOperatorWrapped = true;
NewParenState.IsChainedConditional = false;
NewParenState.IsWrappedConditional = false;
NewParenState.UnindentOperator = false;
NewParenState.NoLineBreak =
NewParenState.NoLineBreak || CurrentState.NoLineBreakInOperand;
if (PrecedenceLevel > prec::Comma)
NewParenState.AvoidBinPacking = false;
if (!Current.isTrailingComment() &&
(Style.AlignOperands != FormatStyle::OAS_DontAlign ||
PrecedenceLevel < prec::Assignment) &&
(!Previous || Previous->isNot(tok::kw_return) ||
(Style.Language != FormatStyle::LK_Java && PrecedenceLevel > 0)) &&
(Style.AlignAfterOpenBracket != FormatStyle::BAS_DontAlign ||
PrecedenceLevel != prec::Comma || Current.NestingLevel == 0)) {
NewParenState.Indent = std::max(
std::max(State.Column, NewParenState.Indent), CurrentState.LastSpace);
}
if (Previous &&
(Previous->getPrecedence() == prec::Assignment ||
Previous->isOneOf(tok::kw_return, TT_RequiresClause) ||
(PrecedenceLevel == prec::Conditional && Previous->is(tok::question) &&
Previous->is(TT_ConditionalExpr))) &&
!Newline) {
if (Style.AlignOperands == FormatStyle::OAS_AlignAfterOperator)
NewParenState.UnindentOperator = true;
if (Style.AlignOperands != FormatStyle::OAS_DontAlign)
NewParenState.IsAligned = true;
}
if (PrecedenceLevel > prec::Unknown)
NewParenState.LastSpace = std::max(NewParenState.LastSpace, State.Column);
if (PrecedenceLevel != prec::Conditional && !Current.is(TT_UnaryOperator) &&
Style.AlignAfterOpenBracket != FormatStyle::BAS_DontAlign) {
NewParenState.StartOfFunctionCall = State.Column;
}
if (PrecedenceLevel == prec::Conditional && Previous &&
Previous->is(tok::colon) && Previous->is(TT_ConditionalExpr) &&
&PrecedenceLevel == &Current.FakeLParens.back() &&
!CurrentState.IsWrappedConditional) {
NewParenState.IsChainedConditional = true;
NewParenState.UnindentOperator = State.Stack.back().UnindentOperator;
} else if (PrecedenceLevel == prec::Conditional ||
(!SkipFirstExtraIndent && PrecedenceLevel > prec::Assignment &&
!Current.isTrailingComment())) {
NewParenState.Indent += Style.ContinuationIndentWidth;
}
if ((Previous && !Previous->opensScope()) || PrecedenceLevel != prec::Comma)
NewParenState.BreakBeforeParameter = false;
State.Stack.push_back(NewParenState);
SkipFirstExtraIndent = false;
}
}
void ContinuationIndenter::moveStatePastFakeRParens(LineState &State) {
for (unsigned i = 0, e = State.NextToken->FakeRParens; i != e; ++i) {
unsigned VariablePos = State.Stack.back().VariablePos;
if (State.Stack.size() == 1) {
break;
}
State.Stack.pop_back();
State.Stack.back().VariablePos = VariablePos;
}
if (State.NextToken->ClosesRequiresClause && Style.IndentRequiresClause) {
State.Stack.back().LastSpace -= Style.IndentWidth;
}
}
void ContinuationIndenter::moveStatePastScopeOpener(LineState &State,
bool Newline) {
const FormatToken &Current = *State.NextToken;
if (!Current.opensScope())
return;
const auto &CurrentState = State.Stack.back();
if (Current.isOneOf(tok::less, tok::l_paren) &&
CurrentState.IsCSharpGenericTypeConstraint) {
return;
}
if (Current.MatchingParen && Current.is(BK_Block)) {
moveStateToNewBlock(State);
return;
}
unsigned NewIndent;
unsigned LastSpace = CurrentState.LastSpace;
bool AvoidBinPacking;
bool BreakBeforeParameter = false;
unsigned NestedBlockIndent = std::max(CurrentState.StartOfFunctionCall,
CurrentState.NestedBlockIndent);
if (Current.isOneOf(tok::l_brace, TT_ArrayInitializerLSquare) ||
opensProtoMessageField(Current, Style)) {
if (Current.opensBlockOrBlockTypeList(Style)) {
NewIndent = Style.IndentWidth +
std::min(State.Column, CurrentState.NestedBlockIndent);
} else {
NewIndent = CurrentState.LastSpace + Style.ContinuationIndentWidth;
}
const FormatToken *NextNoComment = Current.getNextNonComment();
bool EndsInComma = Current.MatchingParen &&
Current.MatchingParen->Previous &&
Current.MatchingParen->Previous->is(tok::comma);
AvoidBinPacking = EndsInComma || Current.is(TT_DictLiteral) ||
Style.Language == FormatStyle::LK_Proto ||
Style.Language == FormatStyle::LK_TextProto ||
!Style.BinPackArguments ||
(NextNoComment &&
NextNoComment->isOneOf(TT_DesignatedInitializerPeriod,
TT_DesignatedInitializerLSquare));
BreakBeforeParameter = EndsInComma;
if (Current.ParameterCount > 1)
NestedBlockIndent = std::max(NestedBlockIndent, State.Column + 1);
} else {
NewIndent =
Style.ContinuationIndentWidth +
std::max(CurrentState.LastSpace, CurrentState.StartOfFunctionCall);
if (Current.is(tok::less) && Current.ParentBracket == tok::l_paren) {
NewIndent = std::max(NewIndent, CurrentState.Indent);
LastSpace = std::max(LastSpace, CurrentState.Indent);
}
bool EndsInComma =
Current.MatchingParen &&
Current.MatchingParen->getPreviousNonComment() &&
Current.MatchingParen->getPreviousNonComment()->is(tok::comma);
bool ObjCBinPackProtocolList =
(Style.ObjCBinPackProtocolList == FormatStyle::BPS_Auto &&
Style.BinPackParameters) ||
Style.ObjCBinPackProtocolList == FormatStyle::BPS_Always;
bool BinPackDeclaration =
(State.Line->Type != LT_ObjCDecl && Style.BinPackParameters) ||
(State.Line->Type == LT_ObjCDecl && ObjCBinPackProtocolList);
AvoidBinPacking =
(CurrentState.IsCSharpGenericTypeConstraint) ||
(Style.isJavaScript() && EndsInComma) ||
(State.Line->MustBeDeclaration && !BinPackDeclaration) ||
(!State.Line->MustBeDeclaration && !Style.BinPackArguments) ||
(Style.ExperimentalAutoDetectBinPacking &&
(Current.is(PPK_OnePerLine) ||
(!BinPackInconclusiveFunctions && Current.is(PPK_Inconclusive))));
if (Current.is(TT_ObjCMethodExpr) && Current.MatchingParen &&
Style.ObjCBreakBeforeNestedBlockParam) {
if (Style.ColumnLimit) {
if (getLengthToMatchingParen(Current, State.Stack) + State.Column >
getColumnLimit(State)) {
BreakBeforeParameter = true;
}
} else {
for (const FormatToken *Tok = &Current;
Tok && Tok != Current.MatchingParen; Tok = Tok->Next) {
if (Tok->MustBreakBefore ||
(Tok->CanBreakBefore && Tok->NewlinesBefore > 0)) {
BreakBeforeParameter = true;
break;
}
}
}
}
if (Style.isJavaScript() && EndsInComma)
BreakBeforeParameter = true;
}
bool NoLineBreak =
Current.Children.empty() &&
!Current.isOneOf(TT_DictLiteral, TT_ArrayInitializerLSquare) &&
(CurrentState.NoLineBreak || CurrentState.NoLineBreakInOperand ||
(Current.is(TT_TemplateOpener) &&
CurrentState.ContainsUnwrappedBuilder));
State.Stack.push_back(
ParenState(&Current, NewIndent, LastSpace, AvoidBinPacking, NoLineBreak));
auto &NewState = State.Stack.back();
NewState.NestedBlockIndent = NestedBlockIndent;
NewState.BreakBeforeParameter = BreakBeforeParameter;
NewState.HasMultipleNestedBlocks = (Current.BlockParameterCount > 1);
if (Style.BraceWrapping.BeforeLambdaBody && Current.Next != nullptr &&
Current.is(tok::l_paren)) {
FormatToken const *next = Current.Next;
while (next != nullptr) {
if (next->is(TT_LambdaLSquare)) {
NewState.HasMultipleNestedBlocks = true;
break;
}
next = next->Next;
}
}
NewState.IsInsideObjCArrayLiteral = Current.is(TT_ArrayInitializerLSquare) &&
Current.Previous &&
Current.Previous->is(tok::at);
}
void ContinuationIndenter::moveStatePastScopeCloser(LineState &State) {
const FormatToken &Current = *State.NextToken;
if (!Current.closesScope())
return;
if (State.Stack.size() > 1 &&
(Current.isOneOf(tok::r_paren, tok::r_square, TT_TemplateString) ||
(Current.is(tok::r_brace) && State.NextToken != State.Line->First) ||
State.NextToken->is(TT_TemplateCloser) ||
(Current.is(tok::greater) && Current.is(TT_DictLiteral)))) {
State.Stack.pop_back();
}
auto &CurrentState = State.Stack.back();
if (CurrentState.BreakBeforeParameter && Current.MatchingParen &&
Current.MatchingParen->Previous) {
const FormatToken &CurrentScopeOpener = *Current.MatchingParen->Previous;
if (CurrentScopeOpener.is(TT_ObjCMethodExpr) &&
CurrentScopeOpener.MatchingParen) {
int NecessarySpaceInLine =
getLengthToMatchingParen(CurrentScopeOpener, State.Stack) +
CurrentScopeOpener.TotalLength - Current.TotalLength - 1;
if (State.Column + Current.ColumnWidth + NecessarySpaceInLine <=
Style.ColumnLimit) {
CurrentState.BreakBeforeParameter = false;
}
}
}
if (Current.is(tok::r_square)) {
const FormatToken *NextNonComment = Current.getNextNonComment();
if (NextNonComment && NextNonComment->isNot(tok::l_square))
CurrentState.StartOfArraySubscripts = 0;
}
}
void ContinuationIndenter::moveStateToNewBlock(LineState &State) {
unsigned NestedBlockIndent = State.Stack.back().NestedBlockIndent;
unsigned NewIndent =
NestedBlockIndent + (State.NextToken->is(TT_ObjCBlockLBrace)
? Style.ObjCBlockIndentWidth
: Style.IndentWidth);
State.Stack.push_back(ParenState(State.NextToken, NewIndent,
State.Stack.back().LastSpace,
true,
false));
State.Stack.back().NestedBlockIndent = NestedBlockIndent;
State.Stack.back().BreakBeforeParameter = true;
}
static unsigned getLastLineEndColumn(StringRef Text, unsigned StartColumn,
unsigned TabWidth,
encoding::Encoding Encoding) {
size_t LastNewlinePos = Text.find_last_of("\n");
if (LastNewlinePos == StringRef::npos) {
return StartColumn +
encoding::columnWidthWithTabs(Text, StartColumn, TabWidth, Encoding);
} else {
return encoding::columnWidthWithTabs(Text.substr(LastNewlinePos),
0, TabWidth, Encoding);
}
}
unsigned ContinuationIndenter::reformatRawStringLiteral(
const FormatToken &Current, LineState &State,
const FormatStyle &RawStringStyle, bool DryRun, bool Newline) {
unsigned StartColumn = State.Column - Current.ColumnWidth;
StringRef OldDelimiter = *getRawStringDelimiter(Current.TokenText);
StringRef NewDelimiter =
getCanonicalRawStringDelimiter(Style, RawStringStyle.Language);
if (NewDelimiter.empty())
NewDelimiter = OldDelimiter;
unsigned OldPrefixSize = 3 + OldDelimiter.size();
unsigned OldSuffixSize = 2 + OldDelimiter.size();
std::string RawText = std::string(
Current.TokenText.substr(OldPrefixSize).drop_back(OldSuffixSize));
if (NewDelimiter != OldDelimiter) {
std::string CanonicalDelimiterSuffix = (")" + NewDelimiter + "\"").str();
if (StringRef(RawText).contains(CanonicalDelimiterSuffix))
NewDelimiter = OldDelimiter;
}
unsigned NewPrefixSize = 3 + NewDelimiter.size();
unsigned NewSuffixSize = 2 + NewDelimiter.size();
unsigned FirstStartColumn = StartColumn + NewPrefixSize;
bool ContentStartsOnNewline = Current.TokenText[OldPrefixSize] == '\n';
unsigned CurrentIndent =
(!Newline && Current.Next && Current.Next->is(tok::r_paren))
? State.Stack.back().NestedBlockIndent
: State.Stack.back().Indent;
unsigned NextStartColumn = ContentStartsOnNewline
? CurrentIndent + Style.IndentWidth
: FirstStartColumn;
unsigned LastStartColumn =
Current.NewlinesBefore ? FirstStartColumn - NewPrefixSize : CurrentIndent;
std::pair<tooling::Replacements, unsigned> Fixes = internal::reformat(
RawStringStyle, RawText, {tooling::Range(0, RawText.size())},
FirstStartColumn, NextStartColumn, LastStartColumn, "<stdin>",
nullptr);
auto NewCode = applyAllReplacements(RawText, Fixes.first);
tooling::Replacements NoFixes;
if (!NewCode)
return addMultilineToken(Current, State);
if (!DryRun) {
if (NewDelimiter != OldDelimiter) {
SourceLocation PrefixDelimiterStart =
Current.Tok.getLocation().getLocWithOffset(2);
auto PrefixErr = Whitespaces.addReplacement(tooling::Replacement(
SourceMgr, PrefixDelimiterStart, OldDelimiter.size(), NewDelimiter));
if (PrefixErr) {
llvm::errs()
<< "Failed to update the prefix delimiter of a raw string: "
<< llvm::toString(std::move(PrefixErr)) << "\n";
}
SourceLocation SuffixDelimiterStart =
Current.Tok.getLocation().getLocWithOffset(Current.TokenText.size() -
1 - OldDelimiter.size());
auto SuffixErr = Whitespaces.addReplacement(tooling::Replacement(
SourceMgr, SuffixDelimiterStart, OldDelimiter.size(), NewDelimiter));
if (SuffixErr) {
llvm::errs()
<< "Failed to update the suffix delimiter of a raw string: "
<< llvm::toString(std::move(SuffixErr)) << "\n";
}
}
SourceLocation OriginLoc =
Current.Tok.getLocation().getLocWithOffset(OldPrefixSize);
for (const tooling::Replacement &Fix : Fixes.first) {
auto Err = Whitespaces.addReplacement(tooling::Replacement(
SourceMgr, OriginLoc.getLocWithOffset(Fix.getOffset()),
Fix.getLength(), Fix.getReplacementText()));
if (Err) {
llvm::errs() << "Failed to reformat raw string: "
<< llvm::toString(std::move(Err)) << "\n";
}
}
}
unsigned RawLastLineEndColumn = getLastLineEndColumn(
*NewCode, FirstStartColumn, Style.TabWidth, Encoding);
State.Column = RawLastLineEndColumn + NewSuffixSize;
unsigned PrefixExcessCharacters =
StartColumn + NewPrefixSize > Style.ColumnLimit
? StartColumn + NewPrefixSize - Style.ColumnLimit
: 0;
bool IsMultiline =
ContentStartsOnNewline || (NewCode->find('\n') != std::string::npos);
if (IsMultiline) {
for (ParenState &Paren : State.Stack)
Paren.BreakBeforeParameter = true;
}
return Fixes.second + PrefixExcessCharacters * Style.PenaltyExcessCharacter;
}
unsigned ContinuationIndenter::addMultilineToken(const FormatToken &Current,
LineState &State) {
for (ParenState &Paren : State.Stack)
Paren.BreakBeforeParameter = true;
unsigned ColumnsUsed = State.Column;
State.Column = Current.LastLineColumnWidth;
if (ColumnsUsed > getColumnLimit(State))
return Style.PenaltyExcessCharacter * (ColumnsUsed - getColumnLimit(State));
return 0;
}
unsigned ContinuationIndenter::handleEndOfLine(const FormatToken &Current,
LineState &State, bool DryRun,
bool AllowBreak, bool Newline) {
unsigned Penalty = 0;
auto RawStringStyle = getRawStringStyle(Current, State);
if (RawStringStyle && !Current.Finalized) {
Penalty = reformatRawStringLiteral(Current, State, *RawStringStyle, DryRun,
Newline);
} else if (Current.IsMultiline && Current.isNot(TT_BlockComment)) {
Penalty = addMultilineToken(Current, State);
} else if (State.Line->Type != LT_ImportStatement) {
LineState OriginalState = State;
bool Strict = false;
bool Exceeded = false;
std::tie(Penalty, Exceeded) = breakProtrudingToken(
Current, State, AllowBreak, true, Strict);
if (Exceeded) {
LineState StrictState = OriginalState;
unsigned StrictPenalty =
breakProtrudingToken(Current, StrictState, AllowBreak,
true, true)
.first;
Strict = StrictPenalty <= Penalty;
if (Strict) {
Penalty = StrictPenalty;
State = StrictState;
}
}
if (!DryRun) {
breakProtrudingToken(Current, OriginalState, AllowBreak, false,
Strict);
}
}
if (State.Column > getColumnLimit(State)) {
unsigned ExcessCharacters = State.Column - getColumnLimit(State);
Penalty += Style.PenaltyExcessCharacter * ExcessCharacters;
}
return Penalty;
}
static StringRef getEnclosingFunctionName(const FormatToken &Current) {
auto Tok = Current.getPreviousNonComment();
if (!Tok || !Tok->is(tok::l_paren))
return "";
Tok = Tok->getPreviousNonComment();
if (!Tok)
return "";
if (Tok->is(TT_TemplateCloser)) {
Tok = Tok->MatchingParen;
if (Tok)
Tok = Tok->getPreviousNonComment();
}
if (!Tok || !Tok->is(tok::identifier))
return "";
return Tok->TokenText;
}
llvm::Optional<FormatStyle>
ContinuationIndenter::getRawStringStyle(const FormatToken &Current,
const LineState &State) {
if (!Current.isStringLiteral())
return None;
auto Delimiter = getRawStringDelimiter(Current.TokenText);
if (!Delimiter)
return None;
auto RawStringStyle = RawStringFormats.getDelimiterStyle(*Delimiter);
if (!RawStringStyle && Delimiter->empty()) {
RawStringStyle = RawStringFormats.getEnclosingFunctionStyle(
getEnclosingFunctionName(Current));
}
if (!RawStringStyle)
return None;
RawStringStyle->ColumnLimit = getColumnLimit(State);
return RawStringStyle;
}
std::unique_ptr<BreakableToken>
ContinuationIndenter::createBreakableToken(const FormatToken &Current,
LineState &State, bool AllowBreak) {
unsigned StartColumn = State.Column - Current.ColumnWidth;
if (Current.isStringLiteral()) {
if (Style.Language == FormatStyle::LK_Java || Style.isJavaScript() ||
Style.isCSharp() || Style.isJson() || !Style.BreakStringLiterals ||
!AllowBreak) {
return nullptr;
}
if (State.Line->Type == LT_PreprocessorDirective)
return nullptr;
if (Current.IsUnterminatedLiteral)
return nullptr;
if (State.Stack.back().IsInsideObjCArrayLiteral)
return nullptr;
StringRef Text = Current.TokenText;
StringRef Prefix;
StringRef Postfix;
if ((Text.endswith(Postfix = "\"") &&
(Text.startswith(Prefix = "@\"") || Text.startswith(Prefix = "\"") ||
Text.startswith(Prefix = "u\"") || Text.startswith(Prefix = "U\"") ||
Text.startswith(Prefix = "u8\"") ||
Text.startswith(Prefix = "L\""))) ||
(Text.startswith(Prefix = "_T(\"") && Text.endswith(Postfix = "\")"))) {
unsigned UnbreakableTailLength = (State.NextToken && canBreak(State))
? 0
: Current.UnbreakableTailLength;
return std::make_unique<BreakableStringLiteral>(
Current, StartColumn, Prefix, Postfix, UnbreakableTailLength,
State.Line->InPPDirective, Encoding, Style);
}
} else if (Current.is(TT_BlockComment)) {
if (!Style.ReflowComments ||
switchesFormatting(Current)) {
return nullptr;
}
return std::make_unique<BreakableBlockComment>(
Current, StartColumn, Current.OriginalColumn, !Current.Previous,
State.Line->InPPDirective, Encoding, Style, Whitespaces.useCRLF());
} else if (Current.is(TT_LineComment) &&
(Current.Previous == nullptr ||
Current.Previous->isNot(TT_ImplicitStringLiteral))) {
bool RegularComments = [&]() {
for (const FormatToken *T = &Current; T && T->is(TT_LineComment);
T = T->Next) {
if (!(T->TokenText.startswith("//") || T->TokenText.startswith("#")))
return false;
}
return true;
}();
if (!Style.ReflowComments ||
CommentPragmasRegex.match(Current.TokenText.substr(2)) ||
switchesFormatting(Current) || !RegularComments) {
return nullptr;
}
return std::make_unique<BreakableLineCommentSection>(
Current, StartColumn, false, Encoding, Style);
}
return nullptr;
}
std::pair<unsigned, bool>
ContinuationIndenter::breakProtrudingToken(const FormatToken &Current,
LineState &State, bool AllowBreak,
bool DryRun, bool Strict) {
std::unique_ptr<const BreakableToken> Token =
createBreakableToken(Current, State, AllowBreak);
if (!Token)
return {0, false};
assert(Token->getLineCount() > 0);
unsigned ColumnLimit = getColumnLimit(State);
if (Current.is(TT_LineComment)) {
ColumnLimit = Style.ColumnLimit;
}
if (ColumnLimit == 0) {
ColumnLimit = std::numeric_limits<decltype(ColumnLimit)>::max();
}
if (Current.UnbreakableTailLength >= ColumnLimit)
return {0, false};
unsigned StartColumn = State.Column - Current.ColumnWidth;
unsigned NewBreakPenalty = Current.isStringLiteral()
? Style.PenaltyBreakString
: Style.PenaltyBreakComment;
bool Exceeded = false;
bool BreakInserted = Token->introducesBreakBeforeToken();
bool NewBreakBefore = false;
bool Reflow = false;
unsigned TailOffset = 0;
unsigned ContentStartColumn =
Token->getContentStartColumn(0, false);
unsigned RemainingTokenColumns =
Token->getRemainingLength(0, TailOffset, ContentStartColumn);
if (!DryRun)
Token->adaptStartOfLine(0, Whitespaces);
unsigned ContentIndent = 0;
unsigned Penalty = 0;
LLVM_DEBUG(llvm::dbgs() << "Breaking protruding token at column "
<< StartColumn << ".\n");
for (unsigned LineIndex = 0, EndIndex = Token->getLineCount();
LineIndex != EndIndex; ++LineIndex) {
LLVM_DEBUG(llvm::dbgs()
<< " Line: " << LineIndex << " (Reflow: " << Reflow << ")\n");
NewBreakBefore = false;
bool TryReflow = Reflow;
while (ContentStartColumn + RemainingTokenColumns > ColumnLimit) {
LLVM_DEBUG(llvm::dbgs() << " Over limit, need: "
<< (ContentStartColumn + RemainingTokenColumns)
<< ", space: " << ColumnLimit
<< ", reflown prefix: " << ContentStartColumn
<< ", offset in line: " << TailOffset << "\n");
BreakableToken::Split Split =
Token->getSplit(LineIndex, TailOffset, ColumnLimit,
ContentStartColumn, CommentPragmasRegex);
if (Split.first == StringRef::npos) {
if (LineIndex < EndIndex - 1) {
Penalty += Style.PenaltyExcessCharacter *
(ContentStartColumn + RemainingTokenColumns - ColumnLimit);
}
LLVM_DEBUG(llvm::dbgs() << " No break opportunity.\n");
break;
}
assert(Split.first != 0);
if (Token->supportsReflow()) {
unsigned ToSplitColumns = Token->getRangeLength(
LineIndex, TailOffset, Split.first, ContentStartColumn);
LLVM_DEBUG(llvm::dbgs() << " ToSplit: " << ToSplitColumns << "\n");
BreakableToken::Split NextSplit = Token->getSplit(
LineIndex, TailOffset + Split.first + Split.second, ColumnLimit,
ContentStartColumn + ToSplitColumns + 1, CommentPragmasRegex);
unsigned ToNextSplitColumns = 0;
if (NextSplit.first == StringRef::npos) {
ToNextSplitColumns = Token->getRemainingLength(LineIndex, TailOffset,
ContentStartColumn);
} else {
ToNextSplitColumns = Token->getRangeLength(
LineIndex, TailOffset,
Split.first + Split.second + NextSplit.first, ContentStartColumn);
}
ToNextSplitColumns =
Token->getLengthAfterCompression(ToNextSplitColumns, Split);
LLVM_DEBUG(llvm::dbgs()
<< " ContentStartColumn: " << ContentStartColumn << "\n");
LLVM_DEBUG(llvm::dbgs()
<< " ToNextSplit: " << ToNextSplitColumns << "\n");
bool ContinueOnLine =
ContentStartColumn + ToNextSplitColumns <= ColumnLimit;
unsigned ExcessCharactersPenalty = 0;
if (!ContinueOnLine && !Strict) {
ExcessCharactersPenalty =
(ContentStartColumn + ToNextSplitColumns - ColumnLimit) *
Style.PenaltyExcessCharacter;
LLVM_DEBUG(llvm::dbgs()
<< " Penalty excess: " << ExcessCharactersPenalty
<< "\n break : " << NewBreakPenalty << "\n");
if (ExcessCharactersPenalty < NewBreakPenalty) {
Exceeded = true;
ContinueOnLine = true;
}
}
if (ContinueOnLine) {
LLVM_DEBUG(llvm::dbgs() << " Continuing on line...\n");
TryReflow = true;
if (!DryRun) {
Token->compressWhitespace(LineIndex, TailOffset, Split,
Whitespaces);
}
ContentStartColumn += ToSplitColumns + 1;
Penalty += ExcessCharactersPenalty;
TailOffset += Split.first + Split.second;
RemainingTokenColumns = Token->getRemainingLength(
LineIndex, TailOffset, ContentStartColumn);
continue;
}
}
LLVM_DEBUG(llvm::dbgs() << " Breaking...\n");
if (!Reflow)
ContentIndent = Token->getContentIndent(LineIndex);
LLVM_DEBUG(llvm::dbgs()
<< " ContentIndent: " << ContentIndent << "\n");
ContentStartColumn = ContentIndent + Token->getContentStartColumn(
LineIndex, true);
unsigned NewRemainingTokenColumns = Token->getRemainingLength(
LineIndex, TailOffset + Split.first + Split.second,
ContentStartColumn);
if (NewRemainingTokenColumns == 0) {
ContentIndent = 0;
ContentStartColumn =
Token->getContentStartColumn(LineIndex, true);
NewRemainingTokenColumns = Token->getRemainingLength(
LineIndex, TailOffset + Split.first + Split.second,
ContentStartColumn);
}
if (NewRemainingTokenColumns >= RemainingTokenColumns) {
break;
}
LLVM_DEBUG(llvm::dbgs() << " Breaking at: " << TailOffset + Split.first
<< ", " << Split.second << "\n");
if (!DryRun) {
Token->insertBreak(LineIndex, TailOffset, Split, ContentIndent,
Whitespaces);
}
Penalty += NewBreakPenalty;
TailOffset += Split.first + Split.second;
RemainingTokenColumns = NewRemainingTokenColumns;
BreakInserted = true;
NewBreakBefore = true;
}
if (LineIndex + 1 != EndIndex) {
unsigned NextLineIndex = LineIndex + 1;
if (NewBreakBefore) {
TryReflow = true;
}
if (TryReflow) {
Reflow = false;
ContentStartColumn += RemainingTokenColumns + 1;
BreakableToken::Split SplitBeforeNext =
Token->getReflowSplit(NextLineIndex, CommentPragmasRegex);
LLVM_DEBUG(llvm::dbgs()
<< " Size of reflown text: " << ContentStartColumn
<< "\n Potential reflow split: ");
if (SplitBeforeNext.first != StringRef::npos) {
LLVM_DEBUG(llvm::dbgs() << SplitBeforeNext.first << ", "
<< SplitBeforeNext.second << "\n");
TailOffset = SplitBeforeNext.first + SplitBeforeNext.second;
RemainingTokenColumns = Token->getRemainingLength(
NextLineIndex, TailOffset, ContentStartColumn);
Reflow = true;
if (ContentStartColumn + RemainingTokenColumns > ColumnLimit) {
LLVM_DEBUG(llvm::dbgs()
<< " Over limit after reflow, need: "
<< (ContentStartColumn + RemainingTokenColumns)
<< ", space: " << ColumnLimit
<< ", reflown prefix: " << ContentStartColumn
<< ", offset in line: " << TailOffset << "\n");
BreakableToken::Split Split =
Token->getSplit(NextLineIndex, TailOffset, ColumnLimit,
ContentStartColumn, CommentPragmasRegex);
if (Split.first == StringRef::npos) {
LLVM_DEBUG(llvm::dbgs() << " Did not find later break\n");
Reflow = false;
} else {
unsigned ToSplitColumns = Token->getRangeLength(
NextLineIndex, TailOffset, Split.first, ContentStartColumn);
if (ContentStartColumn + ToSplitColumns > ColumnLimit) {
LLVM_DEBUG(llvm::dbgs() << " Next split protrudes, need: "
<< (ContentStartColumn + ToSplitColumns)
<< ", space: " << ColumnLimit);
unsigned ExcessCharactersPenalty =
(ContentStartColumn + ToSplitColumns - ColumnLimit) *
Style.PenaltyExcessCharacter;
if (NewBreakPenalty < ExcessCharactersPenalty)
Reflow = false;
}
}
}
} else {
LLVM_DEBUG(llvm::dbgs() << "not found.\n");
}
}
if (!Reflow) {
TailOffset = 0;
ContentStartColumn =
Token->getContentStartColumn(NextLineIndex, false);
RemainingTokenColumns = Token->getRemainingLength(
NextLineIndex, TailOffset, ContentStartColumn);
if (!DryRun)
Token->adaptStartOfLine(NextLineIndex, Whitespaces);
} else {
if (NewBreakBefore) {
assert(Penalty >= NewBreakPenalty);
Penalty -= NewBreakPenalty;
}
if (!DryRun)
Token->reflow(NextLineIndex, Whitespaces);
}
}
}
BreakableToken::Split SplitAfterLastLine =
Token->getSplitAfterLastLine(TailOffset);
if (SplitAfterLastLine.first != StringRef::npos) {
LLVM_DEBUG(llvm::dbgs() << "Replacing whitespace after last line.\n");
Penalty += Style.PenaltyExcessCharacter *
(ContentStartColumn + RemainingTokenColumns - ColumnLimit);
if (!DryRun) {
Token->replaceWhitespaceAfterLastLine(TailOffset, SplitAfterLastLine,
Whitespaces);
}
ContentStartColumn =
Token->getContentStartColumn(Token->getLineCount() - 1, true);
RemainingTokenColumns = Token->getRemainingLength(
Token->getLineCount() - 1,
TailOffset + SplitAfterLastLine.first + SplitAfterLastLine.second,
ContentStartColumn);
}
State.Column = ContentStartColumn + RemainingTokenColumns -
Current.UnbreakableTailLength;
if (BreakInserted) {
if (Current.isNot(TT_LineComment))
for (ParenState &Paren : State.Stack)
Paren.BreakBeforeParameter = true;
if (Current.is(TT_BlockComment))
State.NoContinuation = true;
State.Stack.back().LastSpace = StartColumn;
}
Token->updateNextToken(State);
return {Penalty, Exceeded};
}
unsigned ContinuationIndenter::getColumnLimit(const LineState &State) const {
return Style.ColumnLimit - (State.Line->InPPDirective ? 2 : 0);
}
bool ContinuationIndenter::nextIsMultilineString(const LineState &State) {
const FormatToken &Current = *State.NextToken;
if (!Current.isStringLiteral() || Current.is(TT_ImplicitStringLiteral))
return false;
if (Current.TokenText.startswith("R\""))
return false;
if (Current.IsMultiline)
return true;
if (Current.getNextNonComment() &&
Current.getNextNonComment()->isStringLiteral()) {
return true; }
if (Style.ColumnLimit != 0 && Style.BreakStringLiterals &&
State.Column + Current.ColumnWidth + Current.UnbreakableTailLength >
Style.ColumnLimit) {
return true; }
return false;
}
} }