#include "UnwrappedLineFormatter.h"
#include "NamespaceEndCommentsFixer.h"
#include "WhitespaceManager.h"
#include "llvm/Support/Debug.h"
#include <queue>
#define DEBUG_TYPE "format-formatter"
namespace clang {
namespace format {
namespace {
bool startsExternCBlock(const AnnotatedLine &Line) {
const FormatToken *Next = Line.First->getNextNonComment();
const FormatToken *NextNext = Next ? Next->getNextNonComment() : nullptr;
return Line.startsWith(tok::kw_extern) && Next && Next->isStringLiteral() &&
NextNext && NextNext->is(tok::l_brace);
}
bool isRecordLBrace(const FormatToken &Tok) {
return Tok.isOneOf(TT_ClassLBrace, TT_EnumLBrace, TT_RecordLBrace,
TT_StructLBrace, TT_UnionLBrace);
}
class LevelIndentTracker {
public:
LevelIndentTracker(const FormatStyle &Style,
const AdditionalKeywords &Keywords, unsigned StartLevel,
int AdditionalIndent)
: Style(Style), Keywords(Keywords), AdditionalIndent(AdditionalIndent) {
for (unsigned i = 0; i != StartLevel; ++i)
IndentForLevel.push_back(Style.IndentWidth * i + AdditionalIndent);
}
unsigned getIndent() const { return Indent; }
void nextLine(const AnnotatedLine &Line) {
Offset = getIndentOffset(*Line.First);
skipLine(Line, true);
if (Line.InPPDirective) {
unsigned IndentWidth =
(Style.PPIndentWidth >= 0) ? Style.PPIndentWidth : Style.IndentWidth;
Indent = Line.Level * IndentWidth + AdditionalIndent;
} else {
Indent = getIndent(Line.Level);
}
if (static_cast<int>(Indent) + Offset >= 0)
Indent += Offset;
if (Line.First->is(TT_CSharpGenericTypeConstraint))
Indent = Line.Level * Style.IndentWidth + Style.ContinuationIndentWidth;
}
void skipLine(const AnnotatedLine &Line, bool UnknownIndent = false) {
if (Line.Level >= IndentForLevel.size())
IndentForLevel.resize(Line.Level + 1, UnknownIndent ? -1 : Indent);
}
void adjustToUnmodifiedLine(const AnnotatedLine &Line) {
unsigned LevelIndent = Line.First->OriginalColumn;
if (static_cast<int>(LevelIndent) - Offset >= 0)
LevelIndent -= Offset;
assert(Line.Level < IndentForLevel.size());
if ((!Line.First->is(tok::comment) || IndentForLevel[Line.Level] == -1) &&
!Line.InPPDirective) {
IndentForLevel[Line.Level] = LevelIndent;
}
}
private:
int getIndentOffset(const FormatToken &RootToken) {
if (Style.Language == FormatStyle::LK_Java || Style.isJavaScript() ||
Style.isCSharp()) {
return 0;
}
auto IsAccessModifier = [this, &RootToken]() {
if (RootToken.isAccessSpecifier(Style.isCpp())) {
return true;
} else if (RootToken.isObjCAccessSpecifier()) {
return true;
}
else if ((RootToken.isOneOf(Keywords.kw_signals, Keywords.kw_qsignals) &&
RootToken.Next && RootToken.Next->is(tok::colon))) {
return true;
} else if (RootToken.Next &&
RootToken.Next->isOneOf(Keywords.kw_slots,
Keywords.kw_qslots) &&
RootToken.Next->Next && RootToken.Next->Next->is(tok::colon)) {
return true;
}
else if (!RootToken.Next && RootToken.isAccessSpecifier(false)) {
return true;
}
return false;
};
if (IsAccessModifier()) {
return Style.IndentAccessModifiers ? -Style.IndentWidth
: Style.AccessModifierOffset;
}
return 0;
}
unsigned getIndent(unsigned Level) const {
if (IndentForLevel[Level] != -1)
return IndentForLevel[Level];
if (Level == 0)
return 0;
return getIndent(Level - 1) + Style.IndentWidth;
}
const FormatStyle &Style;
const AdditionalKeywords &Keywords;
const unsigned AdditionalIndent;
SmallVector<int> IndentForLevel;
int Offset = 0;
unsigned Indent = 0;
};
const FormatToken *getMatchingNamespaceToken(
const AnnotatedLine *Line,
const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines) {
if (!Line->startsWith(tok::r_brace))
return nullptr;
size_t StartLineIndex = Line->MatchingOpeningBlockLineIndex;
if (StartLineIndex == UnwrappedLine::kInvalidIndex)
return nullptr;
assert(StartLineIndex < AnnotatedLines.size());
return AnnotatedLines[StartLineIndex]->First->getNamespaceToken();
}
StringRef getNamespaceTokenText(const AnnotatedLine *Line) {
const FormatToken *NamespaceToken = Line->First->getNamespaceToken();
return NamespaceToken ? NamespaceToken->TokenText : StringRef();
}
StringRef getMatchingNamespaceTokenText(
const AnnotatedLine *Line,
const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines) {
const FormatToken *NamespaceToken =
getMatchingNamespaceToken(Line, AnnotatedLines);
return NamespaceToken ? NamespaceToken->TokenText : StringRef();
}
class LineJoiner {
public:
LineJoiner(const FormatStyle &Style, const AdditionalKeywords &Keywords,
const SmallVectorImpl<AnnotatedLine *> &Lines)
: Style(Style), Keywords(Keywords), End(Lines.end()), Next(Lines.begin()),
AnnotatedLines(Lines) {}
const AnnotatedLine *getNextMergedLine(bool DryRun,
LevelIndentTracker &IndentTracker) {
if (Next == End)
return nullptr;
const AnnotatedLine *Current = *Next;
IndentTracker.nextLine(*Current);
unsigned MergedLines = tryFitMultipleLinesInOne(IndentTracker, Next, End);
if (MergedLines > 0 && Style.ColumnLimit == 0) {
for (unsigned i = 0; i < MergedLines; ++i)
if (Next[i + 1]->First->NewlinesBefore > 0)
MergedLines = 0;
}
if (!DryRun)
for (unsigned i = 0; i < MergedLines; ++i)
join(*Next[0], *Next[i + 1]);
Next = Next + MergedLines + 1;
return Current;
}
private:
unsigned
tryFitMultipleLinesInOne(LevelIndentTracker &IndentTracker,
SmallVectorImpl<AnnotatedLine *>::const_iterator I,
SmallVectorImpl<AnnotatedLine *>::const_iterator E) {
const unsigned Indent = IndentTracker.getIndent();
if (I + 1 == E)
return 0;
const AnnotatedLine *TheLine = *I;
if (TheLine->Last->is(TT_LineComment))
return 0;
const auto &NextLine = *I[1];
if (NextLine.Type == LT_Invalid || NextLine.First->MustBreakBefore)
return 0;
if (TheLine->InPPDirective &&
(!NextLine.InPPDirective || NextLine.First->HasUnescapedNewline)) {
return 0;
}
if (Style.ColumnLimit > 0 && Indent > Style.ColumnLimit)
return 0;
unsigned Limit =
Style.ColumnLimit == 0 ? UINT_MAX : Style.ColumnLimit - Indent;
Limit = TheLine->Last->TotalLength > Limit
? 0
: Limit - TheLine->Last->TotalLength;
if (TheLine->Last->is(TT_FunctionLBrace) &&
TheLine->First == TheLine->Last &&
!Style.BraceWrapping.SplitEmptyFunction &&
NextLine.First->is(tok::r_brace)) {
return tryMergeSimpleBlock(I, E, Limit);
}
const auto *PreviousLine = I != AnnotatedLines.begin() ? I[-1] : nullptr;
if (PreviousLine && TheLine->Last->is(tok::l_brace) &&
TheLine->First == TheLine->Last) {
bool EmptyBlock = NextLine.First->is(tok::r_brace);
const FormatToken *Tok = PreviousLine->First;
if (Tok && Tok->is(tok::comment))
Tok = Tok->getNextNonComment();
if (Tok && Tok->getNamespaceToken()) {
return !Style.BraceWrapping.SplitEmptyNamespace && EmptyBlock
? tryMergeSimpleBlock(I, E, Limit)
: 0;
}
if (Tok && Tok->is(tok::kw_typedef))
Tok = Tok->getNextNonComment();
if (Tok && Tok->isOneOf(tok::kw_class, tok::kw_struct, tok::kw_union,
tok::kw_extern, Keywords.kw_interface)) {
return !Style.BraceWrapping.SplitEmptyRecord && EmptyBlock
? tryMergeSimpleBlock(I, E, Limit)
: 0;
}
if (Tok && Tok->is(tok::kw_template) &&
Style.BraceWrapping.SplitEmptyRecord && EmptyBlock) {
return 0;
}
}
auto ShouldMergeShortFunctions = [this, &I, &NextLine, PreviousLine,
TheLine]() {
if (Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_All)
return true;
if (Style.AllowShortFunctionsOnASingleLine >= FormatStyle::SFS_Empty &&
NextLine.First->is(tok::r_brace)) {
return true;
}
if (Style.AllowShortFunctionsOnASingleLine &
FormatStyle::SFS_InlineOnly) {
if (Style.isJavaScript() && TheLine->Last->is(TT_FunctionLBrace))
return true;
if (TheLine->Level != 0) {
if (!PreviousLine)
return false;
const AnnotatedLine *Line = nullptr;
for (auto J = I - 1; J >= AnnotatedLines.begin(); --J) {
assert(*J);
if (!(*J)->InPPDirective && !(*J)->isComment() &&
(*J)->Level < TheLine->Level) {
Line = *J;
break;
}
}
if (!Line)
return false;
const FormatToken *LastNonComment = Line->Last;
assert(LastNonComment);
if (LastNonComment->is(tok::comment)) {
LastNonComment = LastNonComment->getPreviousNonComment();
assert(LastNonComment);
}
return isRecordLBrace(*LastNonComment);
}
}
return false;
};
bool MergeShortFunctions = ShouldMergeShortFunctions();
const FormatToken *FirstNonComment = TheLine->First;
if (FirstNonComment->is(tok::comment)) {
FirstNonComment = FirstNonComment->getNextNonComment();
if (!FirstNonComment)
return 0;
}
if (Style.CompactNamespaces) {
if (auto nsToken = TheLine->First->getNamespaceToken()) {
int i = 0;
unsigned closingLine = TheLine->MatchingClosingBlockLineIndex - 1;
for (; I + 1 + i != E &&
nsToken->TokenText == getNamespaceTokenText(I[i + 1]) &&
closingLine == I[i + 1]->MatchingClosingBlockLineIndex &&
I[i + 1]->Last->TotalLength < Limit;
i++, --closingLine) {
IndentTracker.skipLine(*I[i + 1]);
Limit -= I[i + 1]->Last->TotalLength;
}
return i;
}
if (auto nsToken = getMatchingNamespaceToken(TheLine, AnnotatedLines)) {
int i = 0;
unsigned openingLine = TheLine->MatchingOpeningBlockLineIndex - 1;
for (; I + 1 + i != E &&
nsToken->TokenText ==
getMatchingNamespaceTokenText(I[i + 1], AnnotatedLines) &&
openingLine == I[i + 1]->MatchingOpeningBlockLineIndex;
i++, --openingLine) {
I[i + 1]->First->SpacesRequiredBefore = !I[i]->Last->is(tok::r_brace);
IndentTracker.nextLine(*I[i + 1]);
}
return i;
}
}
if (TheLine->Last->is(TT_FunctionLBrace) && TheLine->First != TheLine->Last)
return MergeShortFunctions ? tryMergeSimpleBlock(I, E, Limit) : 0;
if (TheLine->Last->is(tok::l_brace) && FirstNonComment != TheLine->Last &&
FirstNonComment->isOneOf(tok::kw_if, tok::kw_while, tok::kw_for,
TT_ForEachMacro)) {
return Style.AllowShortBlocksOnASingleLine != FormatStyle::SBS_Never
? tryMergeSimpleBlock(I, E, Limit)
: 0;
}
if (NextLine.First->is(tok::l_brace)) {
if ((TheLine->First->isOneOf(tok::kw_if, tok::kw_else, tok::kw_while,
tok::kw_for, tok::kw_switch, tok::kw_try,
tok::kw_do, TT_ForEachMacro) ||
(TheLine->First->is(tok::r_brace) && TheLine->First->Next &&
TheLine->First->Next->isOneOf(tok::kw_else, tok::kw_catch))) &&
Style.BraceWrapping.AfterControlStatement ==
FormatStyle::BWACS_MultiLine) {
return (Style.ColumnLimit == 0 || TheLine->Level * Style.IndentWidth +
TheLine->Last->TotalLength <=
Style.ColumnLimit)
? 1
: 0;
}
if (TheLine->First->isOneOf(tok::kw_if, tok::kw_else, tok::kw_while,
tok::kw_for, TT_ForEachMacro)) {
return (Style.BraceWrapping.AfterControlStatement ==
FormatStyle::BWACS_Always)
? tryMergeSimpleBlock(I, E, Limit)
: 0;
}
if (TheLine->First->isOneOf(tok::kw_else, tok::kw_catch) &&
Style.BraceWrapping.AfterControlStatement ==
FormatStyle::BWACS_MultiLine) {
return (Style.ColumnLimit == 0 ||
TheLine->Last->TotalLength <= Style.ColumnLimit)
? 1
: 0;
}
}
if (PreviousLine && TheLine->First->is(tok::l_brace)) {
switch (PreviousLine->First->Tok.getKind()) {
case tok::at:
if (PreviousLine->First->Next) {
tok::ObjCKeywordKind kwId =
PreviousLine->First->Next->Tok.getObjCKeywordID();
if (kwId == tok::objc_autoreleasepool ||
kwId == tok::objc_synchronized) {
return 0;
}
}
break;
case tok::kw_case:
case tok::kw_default:
return 0;
default:
break;
}
}
if (PreviousLine && Style.BraceWrapping.SplitEmptyRecord &&
TheLine->Last->is(tok::l_brace) && PreviousLine->Last) {
const FormatToken *Previous = PreviousLine->Last;
if (Previous) {
if (Previous->is(tok::comment))
Previous = Previous->getPreviousNonComment();
if (Previous) {
if (Previous->is(tok::greater) && !PreviousLine->InPPDirective)
return 0;
if (Previous->is(tok::identifier)) {
const FormatToken *PreviousPrevious =
Previous->getPreviousNonComment();
if (PreviousPrevious &&
PreviousPrevious->isOneOf(tok::kw_class, tok::kw_struct)) {
return 0;
}
}
}
}
}
if (TheLine->Last->is(tok::l_brace)) {
bool ShouldMerge = false;
if (TheLine->Last->is(TT_EnumLBrace)) {
ShouldMerge = Style.AllowShortEnumsOnASingleLine;
} else if (TheLine->Last->isOneOf(TT_ClassLBrace, TT_StructLBrace)) {
ShouldMerge = !Style.BraceWrapping.AfterClass ||
(NextLine.First->is(tok::r_brace) &&
!Style.BraceWrapping.SplitEmptyRecord);
} else {
assert(TheLine->InPPDirective ||
!TheLine->First->isOneOf(tok::kw_class, tok::kw_enum,
tok::kw_struct));
ShouldMerge = !Style.BraceWrapping.AfterFunction ||
(NextLine.First->is(tok::r_brace) &&
!Style.BraceWrapping.SplitEmptyFunction);
}
return ShouldMerge ? tryMergeSimpleBlock(I, E, Limit) : 0;
}
if (NextLine.First->is(TT_FunctionLBrace) &&
Style.BraceWrapping.AfterFunction) {
if (NextLine.Last->is(TT_LineComment))
return 0;
if (Limit <= 2 || (Style.ColumnLimit == 0 && containsMustBreak(TheLine)))
return 0;
Limit -= 2;
unsigned MergedLines = 0;
if (MergeShortFunctions ||
(Style.AllowShortFunctionsOnASingleLine >= FormatStyle::SFS_Empty &&
NextLine.First == NextLine.Last && I + 2 != E &&
I[2]->First->is(tok::r_brace))) {
MergedLines = tryMergeSimpleBlock(I + 1, E, Limit);
if (MergedLines > 0)
++MergedLines;
}
return MergedLines;
}
auto IsElseLine = [&TheLine]() -> bool {
const FormatToken *First = TheLine->First;
if (First->is(tok::kw_else))
return true;
return First->is(tok::r_brace) && First->Next &&
First->Next->is(tok::kw_else);
};
if (TheLine->First->is(tok::kw_if) ||
(IsElseLine() && (Style.AllowShortIfStatementsOnASingleLine ==
FormatStyle::SIS_AllIfsAndElse))) {
return Style.AllowShortIfStatementsOnASingleLine
? tryMergeSimpleControlStatement(I, E, Limit)
: 0;
}
if (TheLine->First->isOneOf(tok::kw_for, tok::kw_while, tok::kw_do,
TT_ForEachMacro)) {
return Style.AllowShortLoopsOnASingleLine
? tryMergeSimpleControlStatement(I, E, Limit)
: 0;
}
if (TheLine->First->isOneOf(tok::kw_case, tok::kw_default)) {
return Style.AllowShortCaseLabelsOnASingleLine
? tryMergeShortCaseLabels(I, E, Limit)
: 0;
}
if (TheLine->InPPDirective &&
(TheLine->First->HasUnescapedNewline || TheLine->First->IsFirst)) {
return tryMergeSimplePPDirective(I, E, Limit);
}
return 0;
}
unsigned
tryMergeSimplePPDirective(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
SmallVectorImpl<AnnotatedLine *>::const_iterator E,
unsigned Limit) {
if (Limit == 0)
return 0;
if (I + 2 != E && I[2]->InPPDirective && !I[2]->First->HasUnescapedNewline)
return 0;
if (1 + I[1]->Last->TotalLength > Limit)
return 0;
return 1;
}
unsigned tryMergeSimpleControlStatement(
SmallVectorImpl<AnnotatedLine *>::const_iterator I,
SmallVectorImpl<AnnotatedLine *>::const_iterator E, unsigned Limit) {
if (Limit == 0)
return 0;
if (Style.BraceWrapping.AfterControlStatement ==
FormatStyle::BWACS_Always &&
I[1]->First->is(tok::l_brace) &&
Style.AllowShortBlocksOnASingleLine == FormatStyle::SBS_Never) {
return 0;
}
if (I[1]->InPPDirective != (*I)->InPPDirective ||
(I[1]->InPPDirective && I[1]->First->HasUnescapedNewline)) {
return 0;
}
Limit = limitConsideringMacros(I + 1, E, Limit);
AnnotatedLine &Line = **I;
if (!Line.First->is(tok::kw_do) && !Line.First->is(tok::kw_else) &&
!Line.Last->is(tok::kw_else) && Line.Last->isNot(tok::r_paren)) {
return 0;
}
if (Line.First->is(tok::kw_do) && !Line.Last->is(tok::kw_do))
return 0;
if (1 + I[1]->Last->TotalLength > Limit)
return 0;
if (I[1]->First->isOneOf(tok::semi, tok::kw_if, tok::kw_for, tok::kw_while,
TT_ForEachMacro, TT_LineComment)) {
return 0;
}
if (Style.AllowShortIfStatementsOnASingleLine ==
FormatStyle::SIS_WithoutElse) {
if (I + 2 != E && Line.startsWith(tok::kw_if) &&
I[2]->First->is(tok::kw_else)) {
return 0;
}
}
return 1;
}
unsigned
tryMergeShortCaseLabels(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
SmallVectorImpl<AnnotatedLine *>::const_iterator E,
unsigned Limit) {
if (Limit == 0 || I + 1 == E ||
I[1]->First->isOneOf(tok::kw_case, tok::kw_default)) {
return 0;
}
if (I[0]->Last->is(tok::l_brace) || I[1]->First->is(tok::l_brace))
return 0;
unsigned NumStmts = 0;
unsigned Length = 0;
bool EndsWithComment = false;
bool InPPDirective = I[0]->InPPDirective;
const unsigned Level = I[0]->Level;
for (; NumStmts < 3; ++NumStmts) {
if (I + 1 + NumStmts == E)
break;
const AnnotatedLine *Line = I[1 + NumStmts];
if (Line->InPPDirective != InPPDirective)
break;
if (Line->First->isOneOf(tok::kw_case, tok::kw_default, tok::r_brace))
break;
if (Line->First->isOneOf(tok::kw_if, tok::kw_for, tok::kw_switch,
tok::kw_while) ||
EndsWithComment) {
return 0;
}
if (Line->First->is(tok::comment)) {
if (Level != Line->Level)
return 0;
SmallVectorImpl<AnnotatedLine *>::const_iterator J = I + 2 + NumStmts;
for (; J != E; ++J) {
Line = *J;
if (Line->InPPDirective != InPPDirective)
break;
if (Line->First->isOneOf(tok::kw_case, tok::kw_default, tok::r_brace))
break;
if (Line->First->isNot(tok::comment) || Level != Line->Level)
return 0;
}
break;
}
if (Line->Last->is(tok::comment))
EndsWithComment = true;
Length += I[1 + NumStmts]->Last->TotalLength + 1; }
if (NumStmts == 0 || NumStmts == 3 || Length > Limit)
return 0;
return NumStmts;
}
unsigned
tryMergeSimpleBlock(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
SmallVectorImpl<AnnotatedLine *>::const_iterator E,
unsigned Limit) {
if (I[1]->Type == LT_PreprocessorDirective)
return 0;
AnnotatedLine &Line = **I;
if (Style.Language != FormatStyle::LK_Java &&
Line.First->isOneOf(tok::at, tok::minus, tok::plus)) {
return 0;
}
if (Line.First->is(tok::kw_case) ||
(Line.First->Next && Line.First->Next->is(tok::kw_else))) {
return 0;
}
if (Line.First->is(tok::kw_default)) {
const FormatToken *Tok = Line.First->getNextNonComment();
if (Tok && Tok->is(tok::colon))
return 0;
}
if (Line.First->isOneOf(tok::kw_if, tok::kw_else, tok::kw_while, tok::kw_do,
tok::kw_try, tok::kw___try, tok::kw_catch,
tok::kw___finally, tok::kw_for, TT_ForEachMacro,
tok::r_brace, Keywords.kw___except)) {
if (Style.AllowShortBlocksOnASingleLine == FormatStyle::SBS_Never)
return 0;
if (Style.AllowShortBlocksOnASingleLine == FormatStyle::SBS_Empty &&
!I[1]->First->is(tok::r_brace)) {
return 0;
}
if (!Style.AllowShortIfStatementsOnASingleLine &&
Line.First->isOneOf(tok::kw_if, tok::kw_else) &&
!Style.BraceWrapping.AfterControlStatement &&
!I[1]->First->is(tok::r_brace)) {
return 0;
}
if (!Style.AllowShortIfStatementsOnASingleLine &&
Line.First->isOneOf(tok::kw_if, tok::kw_else) &&
Style.BraceWrapping.AfterControlStatement ==
FormatStyle::BWACS_Always &&
I + 2 != E && !I[2]->First->is(tok::r_brace)) {
return 0;
}
if (!Style.AllowShortLoopsOnASingleLine &&
Line.First->isOneOf(tok::kw_while, tok::kw_do, tok::kw_for,
TT_ForEachMacro) &&
!Style.BraceWrapping.AfterControlStatement &&
!I[1]->First->is(tok::r_brace)) {
return 0;
}
if (!Style.AllowShortLoopsOnASingleLine &&
Line.First->isOneOf(tok::kw_while, tok::kw_do, tok::kw_for,
TT_ForEachMacro) &&
Style.BraceWrapping.AfterControlStatement ==
FormatStyle::BWACS_Always &&
I + 2 != E && !I[2]->First->is(tok::r_brace)) {
return 0;
}
if (Line.First->isOneOf(tok::kw_try, tok::kw___try, tok::kw_catch,
Keywords.kw___except, tok::kw___finally)) {
return 0;
}
}
if (Line.Last->is(tok::l_brace)) {
FormatToken *Tok = I[1]->First;
auto ShouldMerge = [Tok]() {
if (Tok->isNot(tok::r_brace) || Tok->MustBreakBefore)
return false;
const FormatToken *Next = Tok->getNextNonComment();
return !Next || Next->is(tok::semi);
};
if (ShouldMerge()) {
Tok->SpacesRequiredBefore = Style.SpaceInEmptyBlock ? 1 : 0;
Tok->CanBreakBefore = true;
return 1;
} else if (Limit != 0 && !Line.startsWithNamespace() &&
!startsExternCBlock(Line)) {
if (isRecordLBrace(*Line.Last))
return 0;
if (I + 2 == E || I[2]->Type == LT_Invalid)
return 0;
Limit = limitConsideringMacros(I + 2, E, Limit);
if (!nextTwoLinesFitInto(I, Limit))
return 0;
if (I[1]->Last->is(TT_LineComment))
return 0;
do {
if (Tok->is(tok::l_brace) && Tok->isNot(BK_BracedInit))
return 0;
Tok = Tok->Next;
} while (Tok);
Tok = I[2]->First;
if (Tok->isNot(tok::r_brace))
return 0;
if (Tok->Next && Tok->Next->is(tok::kw_else))
return 0;
if (Line.First == Line.Last && Line.First->isNot(TT_FunctionLBrace) &&
Style.BraceWrapping.AfterControlStatement ==
FormatStyle::BWACS_MultiLine) {
return 0;
}
return 2;
}
} else if (I[1]->First->is(tok::l_brace)) {
if (I[1]->Last->is(TT_LineComment))
return 0;
if (Limit <= 2 || (Style.ColumnLimit == 0 && containsMustBreak(*I)))
return 0;
Limit -= 2;
unsigned MergedLines = 0;
if (Style.AllowShortBlocksOnASingleLine != FormatStyle::SBS_Never ||
(I[1]->First == I[1]->Last && I + 2 != E &&
I[2]->First->is(tok::r_brace))) {
MergedLines = tryMergeSimpleBlock(I + 1, E, Limit);
if (MergedLines > 0)
++MergedLines;
}
return MergedLines;
}
return 0;
}
unsigned
limitConsideringMacros(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
SmallVectorImpl<AnnotatedLine *>::const_iterator E,
unsigned Limit) {
if (I[0]->InPPDirective && I + 1 != E &&
!I[1]->First->HasUnescapedNewline && !I[1]->First->is(tok::eof)) {
return Limit < 2 ? 0 : Limit - 2;
}
return Limit;
}
bool nextTwoLinesFitInto(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
unsigned Limit) {
if (I[1]->First->MustBreakBefore || I[2]->First->MustBreakBefore)
return false;
return 1 + I[1]->Last->TotalLength + 1 + I[2]->Last->TotalLength <= Limit;
}
bool containsMustBreak(const AnnotatedLine *Line) {
for (const FormatToken *Tok = Line->First; Tok; Tok = Tok->Next)
if (Tok->MustBreakBefore)
return true;
return false;
}
void join(AnnotatedLine &A, const AnnotatedLine &B) {
assert(!A.Last->Next);
assert(!B.First->Previous);
if (B.Affected)
A.Affected = true;
A.Last->Next = B.First;
B.First->Previous = A.Last;
B.First->CanBreakBefore = true;
unsigned LengthA = A.Last->TotalLength + B.First->SpacesRequiredBefore;
for (FormatToken *Tok = B.First; Tok; Tok = Tok->Next) {
Tok->TotalLength += LengthA;
A.Last = Tok;
}
}
const FormatStyle &Style;
const AdditionalKeywords &Keywords;
const SmallVectorImpl<AnnotatedLine *>::const_iterator End;
SmallVectorImpl<AnnotatedLine *>::const_iterator Next;
const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines;
};
static void markFinalized(FormatToken *Tok) {
for (; Tok; Tok = Tok->Next) {
Tok->Finalized = true;
for (AnnotatedLine *Child : Tok->Children)
markFinalized(Child->First);
}
}
#ifndef NDEBUG
static void printLineState(const LineState &State) {
llvm::dbgs() << "State: ";
for (const ParenState &P : State.Stack) {
llvm::dbgs() << (P.Tok ? P.Tok->TokenText : "F") << "|" << P.Indent << "|"
<< P.LastSpace << "|" << P.NestedBlockIndent << " ";
}
llvm::dbgs() << State.NextToken->TokenText << "\n";
}
#endif
class LineFormatter {
public:
LineFormatter(ContinuationIndenter *Indenter, WhitespaceManager *Whitespaces,
const FormatStyle &Style,
UnwrappedLineFormatter *BlockFormatter)
: Indenter(Indenter), Whitespaces(Whitespaces), Style(Style),
BlockFormatter(BlockFormatter) {}
virtual ~LineFormatter() {}
virtual unsigned formatLine(const AnnotatedLine &Line, unsigned FirstIndent,
unsigned FirstStartColumn, bool DryRun) = 0;
protected:
bool formatChildren(LineState &State, bool NewLine, bool DryRun,
unsigned &Penalty) {
const FormatToken *LBrace = State.NextToken->getPreviousNonComment();
FormatToken &Previous = *State.NextToken->Previous;
if (!LBrace || LBrace->isNot(tok::l_brace) || LBrace->isNot(BK_Block) ||
Previous.Children.size() == 0) {
return true;
}
if (NewLine) {
const ParenState &P = State.Stack.back();
int AdditionalIndent =
P.Indent - Previous.Children[0]->Level * Style.IndentWidth;
if (Style.LambdaBodyIndentation == FormatStyle::LBI_OuterScope &&
P.NestedBlockIndent == P.LastSpace) {
if (State.NextToken->MatchingParen &&
State.NextToken->MatchingParen->is(TT_LambdaLBrace)) {
State.Stack.pop_back();
}
if (LBrace->is(TT_LambdaLBrace))
AdditionalIndent = 0;
}
Penalty +=
BlockFormatter->format(Previous.Children, DryRun, AdditionalIndent,
true);
return true;
}
if (Previous.Children[0]->First->MustBreakBefore)
return false;
if (Previous.is(tok::comment))
return false;
if (Previous.Children.size() > 1)
return false;
const AnnotatedLine *Child = Previous.Children[0];
if (Child->Last->isTrailingComment())
return false;
if (Style.ColumnLimit > 0 &&
Child->Last->TotalLength + State.Column + 2 > Style.ColumnLimit) {
return false;
}
if (!DryRun) {
Whitespaces->replaceWhitespace(
*Child->First, 0, 1,
State.Column, false,
State.Line->InPPDirective);
}
Penalty +=
formatLine(*Child, State.Column + 1, 0, DryRun);
State.Column += 1 + Child->Last->TotalLength;
return true;
}
ContinuationIndenter *Indenter;
private:
WhitespaceManager *Whitespaces;
const FormatStyle &Style;
UnwrappedLineFormatter *BlockFormatter;
};
class NoColumnLimitLineFormatter : public LineFormatter {
public:
NoColumnLimitLineFormatter(ContinuationIndenter *Indenter,
WhitespaceManager *Whitespaces,
const FormatStyle &Style,
UnwrappedLineFormatter *BlockFormatter)
: LineFormatter(Indenter, Whitespaces, Style, BlockFormatter) {}
unsigned formatLine(const AnnotatedLine &Line, unsigned FirstIndent,
unsigned FirstStartColumn, bool DryRun) override {
assert(!DryRun);
LineState State = Indenter->getInitialState(FirstIndent, FirstStartColumn,
&Line, false);
while (State.NextToken) {
bool Newline =
Indenter->mustBreak(State) ||
(Indenter->canBreak(State) && State.NextToken->NewlinesBefore > 0);
unsigned Penalty = 0;
formatChildren(State, Newline, false, Penalty);
Indenter->addTokenToState(State, Newline, false);
}
return 0;
}
};
class NoLineBreakFormatter : public LineFormatter {
public:
NoLineBreakFormatter(ContinuationIndenter *Indenter,
WhitespaceManager *Whitespaces, const FormatStyle &Style,
UnwrappedLineFormatter *BlockFormatter)
: LineFormatter(Indenter, Whitespaces, Style, BlockFormatter) {}
unsigned formatLine(const AnnotatedLine &Line, unsigned FirstIndent,
unsigned FirstStartColumn, bool DryRun) override {
unsigned Penalty = 0;
LineState State =
Indenter->getInitialState(FirstIndent, FirstStartColumn, &Line, DryRun);
while (State.NextToken) {
formatChildren(State, false, DryRun, Penalty);
Indenter->addTokenToState(
State, State.NextToken->MustBreakBefore, DryRun);
}
return Penalty;
}
};
class OptimizingLineFormatter : public LineFormatter {
public:
OptimizingLineFormatter(ContinuationIndenter *Indenter,
WhitespaceManager *Whitespaces,
const FormatStyle &Style,
UnwrappedLineFormatter *BlockFormatter)
: LineFormatter(Indenter, Whitespaces, Style, BlockFormatter) {}
unsigned formatLine(const AnnotatedLine &Line, unsigned FirstIndent,
unsigned FirstStartColumn, bool DryRun) override {
LineState State =
Indenter->getInitialState(FirstIndent, FirstStartColumn, &Line, DryRun);
if (State.Line->Type == LT_ObjCMethodDecl)
State.Stack.back().BreakBeforeParameter = true;
return analyzeSolutionSpace(State, DryRun);
}
private:
struct CompareLineStatePointers {
bool operator()(LineState *obj1, LineState *obj2) const {
return *obj1 < *obj2;
}
};
typedef std::pair<unsigned, unsigned> OrderedPenalty;
struct StateNode {
StateNode(const LineState &State, bool NewLine, StateNode *Previous)
: State(State), NewLine(NewLine), Previous(Previous) {}
LineState State;
bool NewLine;
StateNode *Previous;
};
typedef std::pair<OrderedPenalty, StateNode *> QueueItem;
typedef std::priority_queue<QueueItem, SmallVector<QueueItem>,
std::greater<QueueItem>>
QueueType;
unsigned analyzeSolutionSpace(LineState &InitialState, bool DryRun) {
std::set<LineState *, CompareLineStatePointers> Seen;
unsigned Count = 0;
QueueType Queue;
StateNode *RootNode =
new (Allocator.Allocate()) StateNode(InitialState, false, nullptr);
Queue.push(QueueItem(OrderedPenalty(0, Count), RootNode));
++Count;
unsigned Penalty = 0;
while (!Queue.empty()) {
if (Count > 25000000)
return 0;
Penalty = Queue.top().first.first;
StateNode *Node = Queue.top().second;
if (!Node->State.NextToken) {
LLVM_DEBUG(llvm::dbgs()
<< "\n---\nPenalty for line: " << Penalty << "\n");
break;
}
Queue.pop();
if (Count > 50000)
Node->State.IgnoreStackForComparison = true;
if (!Seen.insert(&Node->State).second) {
continue;
}
FormatDecision LastFormat = Node->State.NextToken->getDecision();
if (LastFormat == FD_Unformatted || LastFormat == FD_Continue)
addNextStateToQueue(Penalty, Node, false, &Count, &Queue);
if (LastFormat == FD_Unformatted || LastFormat == FD_Break)
addNextStateToQueue(Penalty, Node, true, &Count, &Queue);
}
if (Queue.empty()) {
LLVM_DEBUG(llvm::dbgs() << "Could not find a solution.\n");
return 0;
}
if (!DryRun)
reconstructPath(InitialState, Queue.top().second);
LLVM_DEBUG(llvm::dbgs()
<< "Total number of analyzed states: " << Count << "\n");
LLVM_DEBUG(llvm::dbgs() << "---\n");
return Penalty;
}
void addNextStateToQueue(unsigned Penalty, StateNode *PreviousNode,
bool NewLine, unsigned *Count, QueueType *Queue) {
if (NewLine && !Indenter->canBreak(PreviousNode->State))
return;
if (!NewLine && Indenter->mustBreak(PreviousNode->State))
return;
StateNode *Node = new (Allocator.Allocate())
StateNode(PreviousNode->State, NewLine, PreviousNode);
if (!formatChildren(Node->State, NewLine, true, Penalty))
return;
Penalty += Indenter->addTokenToState(Node->State, NewLine, true);
Queue->push(QueueItem(OrderedPenalty(Penalty, *Count), Node));
++(*Count);
}
void reconstructPath(LineState &State, StateNode *Best) {
llvm::SmallVector<StateNode *> Path;
while (Best->Previous) {
Path.push_back(Best);
Best = Best->Previous;
}
for (const auto &Node : llvm::reverse(Path)) {
unsigned Penalty = 0;
formatChildren(State, Node->NewLine, false, Penalty);
Penalty += Indenter->addTokenToState(State, Node->NewLine, false);
LLVM_DEBUG({
printLineState(Node->Previous->State);
if (Node->NewLine) {
llvm::dbgs() << "Penalty for placing "
<< Node->Previous->State.NextToken->Tok.getName()
<< " on a new line: " << Penalty << "\n";
}
});
}
}
llvm::SpecificBumpPtrAllocator<StateNode> Allocator;
};
}
unsigned UnwrappedLineFormatter::format(
const SmallVectorImpl<AnnotatedLine *> &Lines, bool DryRun,
int AdditionalIndent, bool FixBadIndentation, unsigned FirstStartColumn,
unsigned NextStartColumn, unsigned LastStartColumn) {
LineJoiner Joiner(Style, Keywords, Lines);
std::pair<const SmallVectorImpl<AnnotatedLine *> *, unsigned> CacheKey(
&Lines, AdditionalIndent);
auto CacheIt = PenaltyCache.find(CacheKey);
if (DryRun && CacheIt != PenaltyCache.end())
return CacheIt->second;
assert(!Lines.empty());
unsigned Penalty = 0;
LevelIndentTracker IndentTracker(Style, Keywords, Lines[0]->Level,
AdditionalIndent);
const AnnotatedLine *PrevPrevLine = nullptr;
const AnnotatedLine *PreviousLine = nullptr;
const AnnotatedLine *NextLine = nullptr;
unsigned RangeMinLevel = UINT_MAX;
bool FirstLine = true;
for (const AnnotatedLine *Line =
Joiner.getNextMergedLine(DryRun, IndentTracker);
Line; PrevPrevLine = PreviousLine, PreviousLine = Line, Line = NextLine,
FirstLine = false) {
assert(Line->First);
const AnnotatedLine &TheLine = *Line;
unsigned Indent = IndentTracker.getIndent();
bool PreviousRBrace =
PreviousLine && PreviousLine->startsWith(tok::r_brace);
bool ContinueFormatting =
TheLine.Level > RangeMinLevel ||
(TheLine.Level == RangeMinLevel && !PreviousRBrace &&
!TheLine.startsWith(tok::r_brace));
bool FixIndentation = (FixBadIndentation || ContinueFormatting) &&
Indent != TheLine.First->OriginalColumn;
bool ShouldFormat = TheLine.Affected || FixIndentation;
if (ShouldFormat && TheLine.Type == LT_Invalid && Status) {
Status->FormatComplete = false;
Status->Line =
SourceMgr.getSpellingLineNumber(TheLine.First->Tok.getLocation());
}
if (ShouldFormat && TheLine.Type != LT_Invalid) {
if (!DryRun) {
bool LastLine = TheLine.First->is(tok::eof);
formatFirstToken(TheLine, PreviousLine, PrevPrevLine, Lines, Indent,
LastLine ? LastStartColumn : NextStartColumn + Indent);
}
NextLine = Joiner.getNextMergedLine(DryRun, IndentTracker);
unsigned ColumnLimit = getColumnLimit(TheLine.InPPDirective, NextLine);
bool FitsIntoOneLine =
TheLine.Last->TotalLength + Indent <= ColumnLimit ||
(TheLine.Type == LT_ImportStatement &&
(!Style.isJavaScript() || !Style.JavaScriptWrapImports)) ||
(Style.isCSharp() &&
TheLine.InPPDirective); if (Style.ColumnLimit == 0) {
NoColumnLimitLineFormatter(Indenter, Whitespaces, Style, this)
.formatLine(TheLine, NextStartColumn + Indent,
FirstLine ? FirstStartColumn : 0, DryRun);
} else if (FitsIntoOneLine) {
Penalty += NoLineBreakFormatter(Indenter, Whitespaces, Style, this)
.formatLine(TheLine, NextStartColumn + Indent,
FirstLine ? FirstStartColumn : 0, DryRun);
} else {
Penalty += OptimizingLineFormatter(Indenter, Whitespaces, Style, this)
.formatLine(TheLine, NextStartColumn + Indent,
FirstLine ? FirstStartColumn : 0, DryRun);
}
RangeMinLevel = std::min(RangeMinLevel, TheLine.Level);
} else {
if (TheLine.ChildrenAffected) {
for (const FormatToken *Tok = TheLine.First; Tok; Tok = Tok->Next)
if (!Tok->Children.empty())
format(Tok->Children, DryRun);
}
bool StartsNewLine =
TheLine.First->NewlinesBefore > 0 || TheLine.First->IsFirst;
if (StartsNewLine)
IndentTracker.adjustToUnmodifiedLine(TheLine);
if (!DryRun) {
bool ReformatLeadingWhitespace =
StartsNewLine && ((PreviousLine && PreviousLine->Affected) ||
TheLine.LeadingEmptyLinesAffected);
if (ReformatLeadingWhitespace) {
formatFirstToken(TheLine, PreviousLine, PrevPrevLine, Lines,
TheLine.First->OriginalColumn,
TheLine.First->OriginalColumn);
} else {
Whitespaces->addUntouchableToken(*TheLine.First,
TheLine.InPPDirective);
}
for (FormatToken *Tok = TheLine.First->Next; Tok; Tok = Tok->Next)
Whitespaces->addUntouchableToken(*Tok, TheLine.InPPDirective);
}
NextLine = Joiner.getNextMergedLine(DryRun, IndentTracker);
RangeMinLevel = UINT_MAX;
}
if (!DryRun)
markFinalized(TheLine.First);
}
PenaltyCache[CacheKey] = Penalty;
return Penalty;
}
void UnwrappedLineFormatter::formatFirstToken(
const AnnotatedLine &Line, const AnnotatedLine *PreviousLine,
const AnnotatedLine *PrevPrevLine,
const SmallVectorImpl<AnnotatedLine *> &Lines, unsigned Indent,
unsigned NewlineIndent) {
FormatToken &RootToken = *Line.First;
if (RootToken.is(tok::eof)) {
unsigned Newlines = std::min(RootToken.NewlinesBefore, 1u);
unsigned TokenIndent = Newlines ? NewlineIndent : 0;
Whitespaces->replaceWhitespace(RootToken, Newlines, TokenIndent,
TokenIndent);
return;
}
unsigned Newlines =
std::min(RootToken.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1);
if (RootToken.is(tok::r_brace) &&
(!RootToken.Next ||
(RootToken.Next->is(tok::semi) && !RootToken.Next->Next)) &&
!getNamespaceToken(&Line, Lines)) {
Newlines = std::min(Newlines, 1u);
}
if (PreviousLine == nullptr && Line.Level > 0)
Newlines = std::min(Newlines, 1u);
if (Newlines == 0 && !RootToken.IsFirst)
Newlines = 1;
if (RootToken.IsFirst && !RootToken.HasUnescapedNewline)
Newlines = 0;
if (!Style.KeepEmptyLinesAtTheStartOfBlocks && PreviousLine &&
PreviousLine->Last->is(tok::l_brace) &&
!PreviousLine->startsWithNamespace() &&
!(PrevPrevLine && PrevPrevLine->startsWithNamespace() &&
PreviousLine->startsWith(tok::l_brace)) &&
!startsExternCBlock(*PreviousLine)) {
Newlines = 1;
}
if (PreviousLine && RootToken.isAccessSpecifier()) {
switch (Style.EmptyLineBeforeAccessModifier) {
case FormatStyle::ELBAMS_Never:
if (Newlines > 1)
Newlines = 1;
break;
case FormatStyle::ELBAMS_Leave:
Newlines = std::max(RootToken.NewlinesBefore, 1u);
break;
case FormatStyle::ELBAMS_LogicalBlock:
if (PreviousLine->Last->isOneOf(tok::semi, tok::r_brace) && Newlines <= 1)
Newlines = 2;
if (PreviousLine->First->isAccessSpecifier())
Newlines = 1; break;
case FormatStyle::ELBAMS_Always: {
const FormatToken *previousToken;
if (PreviousLine->Last->is(tok::comment))
previousToken = PreviousLine->Last->getPreviousNonComment();
else
previousToken = PreviousLine->Last;
if ((!previousToken || !previousToken->is(tok::l_brace)) && Newlines <= 1)
Newlines = 2;
} break;
}
}
if (PreviousLine && PreviousLine->First->isAccessSpecifier() &&
(!PreviousLine->InPPDirective || !RootToken.HasUnescapedNewline)) {
if (!RootToken.isAccessSpecifier()) {
switch (Style.EmptyLineAfterAccessModifier) {
case FormatStyle::ELAAMS_Never:
Newlines = 1;
break;
case FormatStyle::ELAAMS_Leave:
Newlines = std::max(Newlines, 1u);
break;
case FormatStyle::ELAAMS_Always:
if (RootToken.is(tok::r_brace)) Newlines = 1u;
else
Newlines = std::max(Newlines, 2u);
break;
}
}
}
if (Newlines)
Indent = NewlineIndent;
if (!Style.isJavaScript() &&
Style.IndentPPDirectives != FormatStyle::PPDIS_BeforeHash &&
(Line.Type == LT_PreprocessorDirective ||
Line.Type == LT_ImportStatement)) {
Indent = 0;
}
Whitespaces->replaceWhitespace(RootToken, Newlines, Indent, Indent,
false,
Line.InPPDirective &&
!RootToken.HasUnescapedNewline);
}
unsigned
UnwrappedLineFormatter::getColumnLimit(bool InPPDirective,
const AnnotatedLine *NextLine) const {
bool ContinuesPPDirective =
InPPDirective &&
(!NextLine ||
(NextLine->InPPDirective &&
!NextLine->First->HasUnescapedNewline));
return Style.ColumnLimit - (ContinuesPPDirective ? 2 : 0);
}
} }