#include "BreakableToken.h"
#include "ContinuationIndenter.h"
#include "clang/Basic/CharInfo.h"
#include "clang/Format/Format.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/Support/Debug.h"
#include <algorithm>
#define DEBUG_TYPE "format-token-breaker"
namespace clang {
namespace format {
static constexpr StringRef Blanks = " \t\v\f\r";
static bool IsBlank(char C) {
switch (C) {
case ' ':
case '\t':
case '\v':
case '\f':
case '\r':
return true;
default:
return false;
}
}
static StringRef getLineCommentIndentPrefix(StringRef Comment,
const FormatStyle &Style) {
static constexpr StringRef KnownCStylePrefixes[] = {"///<", "//!<", "///",
"//!", "//:", "//"};
static constexpr StringRef KnownTextProtoPrefixes[] = {"####", "###", "##",
"//", "#"};
ArrayRef<StringRef> KnownPrefixes(KnownCStylePrefixes);
if (Style.Language == FormatStyle::LK_TextProto)
KnownPrefixes = KnownTextProtoPrefixes;
assert(std::is_sorted(KnownPrefixes.begin(), KnownPrefixes.end(),
[](StringRef Lhs, StringRef Rhs) noexcept {
return Lhs.size() > Rhs.size();
}));
for (StringRef KnownPrefix : KnownPrefixes) {
if (Comment.startswith(KnownPrefix)) {
const auto PrefixLength =
Comment.find_first_not_of(' ', KnownPrefix.size());
return Comment.substr(0, PrefixLength);
}
}
return {};
}
static BreakableToken::Split
getCommentSplit(StringRef Text, unsigned ContentStartColumn,
unsigned ColumnLimit, unsigned TabWidth,
encoding::Encoding Encoding, const FormatStyle &Style,
bool DecorationEndsWithStar = false) {
LLVM_DEBUG(llvm::dbgs() << "Comment split: \"" << Text
<< "\", Column limit: " << ColumnLimit
<< ", Content start: " << ContentStartColumn << "\n");
if (ColumnLimit <= ContentStartColumn + 1)
return BreakableToken::Split(StringRef::npos, 0);
unsigned MaxSplit = ColumnLimit - ContentStartColumn + 1;
unsigned MaxSplitBytes = 0;
for (unsigned NumChars = 0;
NumChars < MaxSplit && MaxSplitBytes < Text.size();) {
unsigned BytesInChar =
encoding::getCodePointNumBytes(Text[MaxSplitBytes], Encoding);
NumChars +=
encoding::columnWidthWithTabs(Text.substr(MaxSplitBytes, BytesInChar),
ContentStartColumn, TabWidth, Encoding);
MaxSplitBytes += BytesInChar;
}
if (Style.isJavaScript()) {
StringRef::size_type SpaceOffset =
Text.find_first_of(Blanks, MaxSplitBytes);
if (SpaceOffset != StringRef::npos && SpaceOffset + 1 < Text.size() &&
Text[SpaceOffset + 1] == '{') {
MaxSplitBytes = SpaceOffset + 1;
}
}
StringRef::size_type SpaceOffset = Text.find_last_of(Blanks, MaxSplitBytes);
static const auto kNumberedListRegexp = llvm::Regex("^[1-9][0-9]?\\.");
while (SpaceOffset != StringRef::npos) {
if (Style.isCpp()) {
StringRef::size_type LastNonBlank =
Text.find_last_not_of(Blanks, SpaceOffset);
if (LastNonBlank != StringRef::npos && Text[LastNonBlank] == '\\') {
SpaceOffset = Text.find_last_of(Blanks, LastNonBlank);
continue;
}
}
if (kNumberedListRegexp.match(Text.substr(SpaceOffset).ltrim(Blanks))) {
SpaceOffset = Text.find_last_of(Blanks, SpaceOffset);
continue;
}
if (Style.isJavaScript() && SpaceOffset + 1 < Text.size() &&
(Text[SpaceOffset + 1] == '{' || Text[SpaceOffset + 1] == '@')) {
SpaceOffset = Text.find_last_of(Blanks, SpaceOffset);
continue;
}
break;
}
if (SpaceOffset == StringRef::npos ||
Text.find_last_not_of(Blanks, SpaceOffset) == StringRef::npos) {
StringRef::size_type FirstNonWhitespace = Text.find_first_not_of(Blanks);
if (FirstNonWhitespace == StringRef::npos) {
return BreakableToken::Split(StringRef::npos, 0);
}
SpaceOffset = Text.find_first_of(
Blanks, std::max<unsigned>(MaxSplitBytes, FirstNonWhitespace));
}
if (SpaceOffset != StringRef::npos && SpaceOffset != 0) {
if (SpaceOffset == 1 && Text[SpaceOffset - 1] == '*')
return BreakableToken::Split(StringRef::npos, 0);
StringRef BeforeCut = Text.substr(0, SpaceOffset).rtrim(Blanks);
StringRef AfterCut = Text.substr(SpaceOffset);
if (!DecorationEndsWithStar || AfterCut.size() <= 1 || AfterCut[1] != '/')
AfterCut = AfterCut.ltrim(Blanks);
return BreakableToken::Split(BeforeCut.size(),
AfterCut.begin() - BeforeCut.end());
}
return BreakableToken::Split(StringRef::npos, 0);
}
static BreakableToken::Split
getStringSplit(StringRef Text, unsigned UsedColumns, unsigned ColumnLimit,
unsigned TabWidth, encoding::Encoding Encoding) {
if (Text.empty())
return BreakableToken::Split(StringRef::npos, 0);
if (ColumnLimit <= UsedColumns)
return BreakableToken::Split(StringRef::npos, 0);
unsigned MaxSplit = ColumnLimit - UsedColumns;
StringRef::size_type SpaceOffset = 0;
StringRef::size_type SlashOffset = 0;
StringRef::size_type WordStartOffset = 0;
StringRef::size_type SplitPoint = 0;
for (unsigned Chars = 0;;) {
unsigned Advance;
if (Text[0] == '\\') {
Advance = encoding::getEscapeSequenceLength(Text);
Chars += Advance;
} else {
Advance = encoding::getCodePointNumBytes(Text[0], Encoding);
Chars += encoding::columnWidthWithTabs(
Text.substr(0, Advance), UsedColumns + Chars, TabWidth, Encoding);
}
if (Chars > MaxSplit || Text.size() <= Advance)
break;
if (IsBlank(Text[0]))
SpaceOffset = SplitPoint;
if (Text[0] == '/')
SlashOffset = SplitPoint;
if (Advance == 1 && !isAlphanumeric(Text[0]))
WordStartOffset = SplitPoint;
SplitPoint += Advance;
Text = Text.substr(Advance);
}
if (SpaceOffset != 0)
return BreakableToken::Split(SpaceOffset + 1, 0);
if (SlashOffset != 0)
return BreakableToken::Split(SlashOffset + 1, 0);
if (WordStartOffset != 0)
return BreakableToken::Split(WordStartOffset + 1, 0);
if (SplitPoint != 0)
return BreakableToken::Split(SplitPoint, 0);
return BreakableToken::Split(StringRef::npos, 0);
}
bool switchesFormatting(const FormatToken &Token) {
assert((Token.is(TT_BlockComment) || Token.is(TT_LineComment)) &&
"formatting regions are switched by comment tokens");
StringRef Content = Token.TokenText.substr(2).ltrim();
return Content.startswith("clang-format on") ||
Content.startswith("clang-format off");
}
unsigned
BreakableToken::getLengthAfterCompression(unsigned RemainingTokenColumns,
Split Split) const {
return RemainingTokenColumns + 1 - Split.second;
}
unsigned BreakableStringLiteral::getLineCount() const { return 1; }
unsigned BreakableStringLiteral::getRangeLength(unsigned LineIndex,
unsigned Offset,
StringRef::size_type Length,
unsigned StartColumn) const {
llvm_unreachable("Getting the length of a part of the string literal "
"indicates that the code tries to reflow it.");
}
unsigned
BreakableStringLiteral::getRemainingLength(unsigned LineIndex, unsigned Offset,
unsigned StartColumn) const {
return UnbreakableTailLength + Postfix.size() +
encoding::columnWidthWithTabs(Line.substr(Offset), StartColumn,
Style.TabWidth, Encoding);
}
unsigned BreakableStringLiteral::getContentStartColumn(unsigned LineIndex,
bool Break) const {
return StartColumn + Prefix.size();
}
BreakableStringLiteral::BreakableStringLiteral(
const FormatToken &Tok, unsigned StartColumn, StringRef Prefix,
StringRef Postfix, unsigned UnbreakableTailLength, bool InPPDirective,
encoding::Encoding Encoding, const FormatStyle &Style)
: BreakableToken(Tok, InPPDirective, Encoding, Style),
StartColumn(StartColumn), Prefix(Prefix), Postfix(Postfix),
UnbreakableTailLength(UnbreakableTailLength) {
assert(Tok.TokenText.startswith(Prefix) && Tok.TokenText.endswith(Postfix));
Line = Tok.TokenText.substr(
Prefix.size(), Tok.TokenText.size() - Prefix.size() - Postfix.size());
}
BreakableToken::Split BreakableStringLiteral::getSplit(
unsigned LineIndex, unsigned TailOffset, unsigned ColumnLimit,
unsigned ContentStartColumn, const llvm::Regex &CommentPragmasRegex) const {
return getStringSplit(Line.substr(TailOffset), ContentStartColumn,
ColumnLimit - Postfix.size(), Style.TabWidth, Encoding);
}
void BreakableStringLiteral::insertBreak(unsigned LineIndex,
unsigned TailOffset, Split Split,
unsigned ContentIndent,
WhitespaceManager &Whitespaces) const {
Whitespaces.replaceWhitespaceInToken(
Tok, Prefix.size() + TailOffset + Split.first, Split.second, Postfix,
Prefix, InPPDirective, 1, StartColumn);
}
BreakableComment::BreakableComment(const FormatToken &Token,
unsigned StartColumn, bool InPPDirective,
encoding::Encoding Encoding,
const FormatStyle &Style)
: BreakableToken(Token, InPPDirective, Encoding, Style),
StartColumn(StartColumn) {}
unsigned BreakableComment::getLineCount() const { return Lines.size(); }
BreakableToken::Split
BreakableComment::getSplit(unsigned LineIndex, unsigned TailOffset,
unsigned ColumnLimit, unsigned ContentStartColumn,
const llvm::Regex &CommentPragmasRegex) const {
if (CommentPragmasRegex.match(Content[LineIndex]))
return Split(StringRef::npos, 0);
return getCommentSplit(Content[LineIndex].substr(TailOffset),
ContentStartColumn, ColumnLimit, Style.TabWidth,
Encoding, Style);
}
void BreakableComment::compressWhitespace(
unsigned LineIndex, unsigned TailOffset, Split Split,
WhitespaceManager &Whitespaces) const {
StringRef Text = Content[LineIndex].substr(TailOffset);
unsigned BreakOffsetInToken =
Text.data() - tokenAt(LineIndex).TokenText.data() + Split.first;
unsigned CharsToRemove = Split.second;
Whitespaces.replaceWhitespaceInToken(
tokenAt(LineIndex), BreakOffsetInToken, CharsToRemove, "", "",
false, 0, 1);
}
const FormatToken &BreakableComment::tokenAt(unsigned LineIndex) const {
return Tokens[LineIndex] ? *Tokens[LineIndex] : Tok;
}
static bool mayReflowContent(StringRef Content) {
Content = Content.trim(Blanks);
bool hasSpecialMeaningPrefix = false;
for (StringRef Prefix :
{"@", "TODO", "FIXME", "XXX", "-# ", "- ", "+ ", "* "}) {
if (Content.startswith(Prefix)) {
hasSpecialMeaningPrefix = true;
break;
}
}
static const auto kNumberedListRegexp = llvm::Regex("^[1-9][0-9]?\\. ");
hasSpecialMeaningPrefix =
hasSpecialMeaningPrefix || kNumberedListRegexp.match(Content);
return Content.size() >= 2 && !hasSpecialMeaningPrefix &&
!Content.endswith("\\") &&
(!isPunctuation(Content[0]) || !isPunctuation(Content[1]));
}
BreakableBlockComment::BreakableBlockComment(
const FormatToken &Token, unsigned StartColumn,
unsigned OriginalStartColumn, bool FirstInLine, bool InPPDirective,
encoding::Encoding Encoding, const FormatStyle &Style, bool UseCRLF)
: BreakableComment(Token, StartColumn, InPPDirective, Encoding, Style),
DelimitersOnNewline(false),
UnbreakableTailLength(Token.UnbreakableTailLength) {
assert(Tok.is(TT_BlockComment) &&
"block comment section must start with a block comment");
StringRef TokenText(Tok.TokenText);
assert(TokenText.startswith("/*") && TokenText.endswith("*/"));
TokenText.substr(2, TokenText.size() - 4)
.split(Lines, UseCRLF ? "\r\n" : "\n");
int IndentDelta = StartColumn - OriginalStartColumn;
Content.resize(Lines.size());
Content[0] = Lines[0];
ContentColumn.resize(Lines.size());
ContentColumn[0] = StartColumn + 2;
Tokens.resize(Lines.size());
for (size_t i = 1; i < Lines.size(); ++i)
adjustWhitespace(i, IndentDelta);
DecorationColumn = StartColumn + 1;
if (Lines.size() >= 2 && Content[1].startswith("**") &&
static_cast<unsigned>(ContentColumn[1]) == StartColumn) {
DecorationColumn = StartColumn;
}
Decoration = "* ";
if (Lines.size() == 1 && !FirstInLine) {
Decoration = "";
}
for (size_t i = 1, e = Content.size(); i < e && !Decoration.empty(); ++i) {
const StringRef &Text = Content[i];
if (i + 1 == e) {
if (Text.empty())
break;
} else if (!Text.empty() && Decoration.startswith(Text)) {
continue;
}
while (!Text.startswith(Decoration))
Decoration = Decoration.drop_back(1);
}
LastLineNeedsDecoration = true;
IndentAtLineBreak = ContentColumn[0] + 1;
for (size_t i = 1, e = Lines.size(); i < e; ++i) {
if (Content[i].empty()) {
if (i + 1 == e) {
LastLineNeedsDecoration = false;
if (e >= 2 && !Decoration.empty())
ContentColumn[i] = DecorationColumn;
} else if (Decoration.empty()) {
ContentColumn[i] = 0;
}
continue;
}
unsigned DecorationSize = Decoration.startswith(Content[i])
? Content[i].size()
: Decoration.size();
if (DecorationSize)
ContentColumn[i] = DecorationColumn + DecorationSize;
Content[i] = Content[i].substr(DecorationSize);
if (!Decoration.startswith(Content[i])) {
IndentAtLineBreak =
std::min<int>(IndentAtLineBreak, std::max(0, ContentColumn[i]));
}
}
IndentAtLineBreak = std::max<unsigned>(IndentAtLineBreak, Decoration.size());
if (Style.isJavaScript() || Style.Language == FormatStyle::LK_Java) {
if ((Lines[0] == "*" || Lines[0].startswith("* ")) && Lines.size() > 1) {
DelimitersOnNewline = true;
} else if (Lines[0].startswith("* ") && Lines.size() == 1) {
unsigned EndColumn =
ContentColumn[0] +
encoding::columnWidthWithTabs(Lines[0], ContentColumn[0],
Style.TabWidth, Encoding) +
2;
DelimitersOnNewline = EndColumn > Style.ColumnLimit;
}
}
LLVM_DEBUG({
llvm::dbgs() << "IndentAtLineBreak " << IndentAtLineBreak << "\n";
llvm::dbgs() << "DelimitersOnNewline " << DelimitersOnNewline << "\n";
for (size_t i = 0; i < Lines.size(); ++i) {
llvm::dbgs() << i << " |" << Content[i] << "| "
<< "CC=" << ContentColumn[i] << "| "
<< "IN=" << (Content[i].data() - Lines[i].data()) << "\n";
}
});
}
BreakableToken::Split BreakableBlockComment::getSplit(
unsigned LineIndex, unsigned TailOffset, unsigned ColumnLimit,
unsigned ContentStartColumn, const llvm::Regex &CommentPragmasRegex) const {
if (CommentPragmasRegex.match(Content[LineIndex]))
return Split(StringRef::npos, 0);
return getCommentSplit(Content[LineIndex].substr(TailOffset),
ContentStartColumn, ColumnLimit, Style.TabWidth,
Encoding, Style, Decoration.endswith("*"));
}
void BreakableBlockComment::adjustWhitespace(unsigned LineIndex,
int IndentDelta) {
size_t EndOfPreviousLine = Lines[LineIndex - 1].size();
if (InPPDirective && Lines[LineIndex - 1].endswith("\\"))
--EndOfPreviousLine;
EndOfPreviousLine =
Lines[LineIndex - 1].find_last_not_of(Blanks, EndOfPreviousLine);
if (EndOfPreviousLine == StringRef::npos)
EndOfPreviousLine = 0;
else
++EndOfPreviousLine;
size_t StartOfLine = Lines[LineIndex].find_first_not_of(Blanks);
if (StartOfLine == StringRef::npos)
StartOfLine = Lines[LineIndex].size();
StringRef Whitespace = Lines[LineIndex].substr(0, StartOfLine);
size_t PreviousContentOffset =
Content[LineIndex - 1].data() - Lines[LineIndex - 1].data();
Content[LineIndex - 1] = Lines[LineIndex - 1].substr(
PreviousContentOffset, EndOfPreviousLine - PreviousContentOffset);
Content[LineIndex] = Lines[LineIndex].substr(StartOfLine);
ContentColumn[LineIndex] =
encoding::columnWidthWithTabs(Whitespace, 0, Style.TabWidth, Encoding) +
IndentDelta;
}
unsigned BreakableBlockComment::getRangeLength(unsigned LineIndex,
unsigned Offset,
StringRef::size_type Length,
unsigned StartColumn) const {
return encoding::columnWidthWithTabs(
Content[LineIndex].substr(Offset, Length), StartColumn, Style.TabWidth,
Encoding);
}
unsigned BreakableBlockComment::getRemainingLength(unsigned LineIndex,
unsigned Offset,
unsigned StartColumn) const {
unsigned LineLength =
UnbreakableTailLength +
getRangeLength(LineIndex, Offset, StringRef::npos, StartColumn);
if (LineIndex + 1 == Lines.size()) {
LineLength += 2;
bool HasRemainingText = Offset < Content[LineIndex].size();
if (!HasRemainingText) {
bool HasDecoration = Lines[LineIndex].ltrim().startswith(Decoration);
if (HasDecoration)
LineLength -= Decoration.size();
}
}
return LineLength;
}
unsigned BreakableBlockComment::getContentStartColumn(unsigned LineIndex,
bool Break) const {
if (Break)
return IndentAtLineBreak;
return std::max(0, ContentColumn[LineIndex]);
}
const llvm::StringSet<>
BreakableBlockComment::ContentIndentingJavadocAnnotations = {
"@param", "@return", "@returns", "@throws", "@type", "@template",
"@see", "@deprecated", "@define", "@exports", "@mods", "@private",
};
unsigned BreakableBlockComment::getContentIndent(unsigned LineIndex) const {
if (Style.Language != FormatStyle::LK_Java && !Style.isJavaScript())
return 0;
StringRef ContentWithNoDecoration = Content[LineIndex];
if (LineIndex == 0 && ContentWithNoDecoration.startswith("*"))
ContentWithNoDecoration = ContentWithNoDecoration.substr(1).ltrim(Blanks);
StringRef FirstWord = ContentWithNoDecoration.substr(
0, ContentWithNoDecoration.find_first_of(Blanks));
if (ContentIndentingJavadocAnnotations.find(FirstWord) !=
ContentIndentingJavadocAnnotations.end()) {
return Style.ContinuationIndentWidth;
}
return 0;
}
void BreakableBlockComment::insertBreak(unsigned LineIndex, unsigned TailOffset,
Split Split, unsigned ContentIndent,
WhitespaceManager &Whitespaces) const {
StringRef Text = Content[LineIndex].substr(TailOffset);
StringRef Prefix = Decoration;
unsigned LocalIndentAtLineBreak = IndentAtLineBreak;
if (LineIndex + 1 == Lines.size() &&
Text.size() == Split.first + Split.second) {
Prefix = "";
if (LocalIndentAtLineBreak >= 2)
LocalIndentAtLineBreak -= 2;
}
unsigned BreakOffsetInToken =
Text.data() - tokenAt(LineIndex).TokenText.data() + Split.first;
unsigned CharsToRemove = Split.second;
assert(LocalIndentAtLineBreak >= Prefix.size());
std::string PrefixWithTrailingIndent = std::string(Prefix);
PrefixWithTrailingIndent.append(ContentIndent, ' ');
Whitespaces.replaceWhitespaceInToken(
tokenAt(LineIndex), BreakOffsetInToken, CharsToRemove, "",
PrefixWithTrailingIndent, InPPDirective, 1,
LocalIndentAtLineBreak + ContentIndent -
PrefixWithTrailingIndent.size());
}
BreakableToken::Split BreakableBlockComment::getReflowSplit(
unsigned LineIndex, const llvm::Regex &CommentPragmasRegex) const {
if (!mayReflow(LineIndex, CommentPragmasRegex))
return Split(StringRef::npos, 0);
size_t Trimmed = Content[LineIndex].find_first_not_of(Blanks);
if (LineIndex) {
unsigned PreviousContentIndent = getContentIndent(LineIndex - 1);
if (PreviousContentIndent && Trimmed != StringRef::npos &&
Trimmed != PreviousContentIndent) {
return Split(StringRef::npos, 0);
}
}
return Split(0, Trimmed != StringRef::npos ? Trimmed : 0);
}
bool BreakableBlockComment::introducesBreakBeforeToken() const {
return DelimitersOnNewline &&
Lines[0].substr(1).find_first_not_of(Blanks) != StringRef::npos;
}
void BreakableBlockComment::reflow(unsigned LineIndex,
WhitespaceManager &Whitespaces) const {
StringRef TrimmedContent = Content[LineIndex].ltrim(Blanks);
assert(Tokens[LineIndex - 1] == Tokens[LineIndex] &&
"Reflowing whitespace within a token");
unsigned WhitespaceOffsetInToken = Content[LineIndex - 1].data() +
Content[LineIndex - 1].size() -
tokenAt(LineIndex).TokenText.data();
unsigned WhitespaceLength = TrimmedContent.data() -
tokenAt(LineIndex).TokenText.data() -
WhitespaceOffsetInToken;
Whitespaces.replaceWhitespaceInToken(
tokenAt(LineIndex), WhitespaceOffsetInToken,
WhitespaceLength, "",
ReflowPrefix, InPPDirective, 0,
0);
}
void BreakableBlockComment::adaptStartOfLine(
unsigned LineIndex, WhitespaceManager &Whitespaces) const {
if (LineIndex == 0) {
if (DelimitersOnNewline) {
size_t BreakLength = Lines[0].substr(1).find_first_not_of(Blanks);
if (BreakLength != StringRef::npos) {
insertBreak(LineIndex, 0, Split(1, BreakLength), 0,
Whitespaces);
}
}
return;
}
StringRef Prefix = Decoration;
if (Content[LineIndex].empty()) {
if (LineIndex + 1 == Lines.size()) {
if (!LastLineNeedsDecoration) {
Prefix = "";
}
} else if (!Decoration.empty()) {
Prefix = Prefix.substr(0, 1);
}
} else if (ContentColumn[LineIndex] == 1) {
Prefix = Prefix.substr(0, 1);
}
unsigned WhitespaceOffsetInToken = Content[LineIndex - 1].data() +
Content[LineIndex - 1].size() -
tokenAt(LineIndex).TokenText.data();
unsigned WhitespaceLength = Content[LineIndex].data() -
tokenAt(LineIndex).TokenText.data() -
WhitespaceOffsetInToken;
Whitespaces.replaceWhitespaceInToken(
tokenAt(LineIndex), WhitespaceOffsetInToken, WhitespaceLength, "", Prefix,
InPPDirective, 1, ContentColumn[LineIndex] - Prefix.size());
}
BreakableToken::Split
BreakableBlockComment::getSplitAfterLastLine(unsigned TailOffset) const {
if (DelimitersOnNewline) {
StringRef Line = Content.back().substr(TailOffset);
StringRef TrimmedLine = Line.rtrim(Blanks);
if (!TrimmedLine.empty())
return Split(TrimmedLine.size(), Line.size() - TrimmedLine.size());
}
return Split(StringRef::npos, 0);
}
bool BreakableBlockComment::mayReflow(
unsigned LineIndex, const llvm::Regex &CommentPragmasRegex) const {
StringRef IndentContent = Content[LineIndex];
if (Lines[LineIndex].ltrim(Blanks).startswith("*"))
IndentContent = Lines[LineIndex].ltrim(Blanks).substr(1);
return LineIndex > 0 && !CommentPragmasRegex.match(IndentContent) &&
mayReflowContent(Content[LineIndex]) && !Tok.Finalized &&
!switchesFormatting(tokenAt(LineIndex));
}
BreakableLineCommentSection::BreakableLineCommentSection(
const FormatToken &Token, unsigned StartColumn, bool InPPDirective,
encoding::Encoding Encoding, const FormatStyle &Style)
: BreakableComment(Token, StartColumn, InPPDirective, Encoding, Style) {
assert(Tok.is(TT_LineComment) &&
"line comment section must start with a line comment");
FormatToken *LineTok = nullptr;
const int Minimum = Style.SpacesInLineCommentPrefix.Minimum;
int FirstLineSpaceChange = 0;
for (const FormatToken *CurrentTok = &Tok;
CurrentTok && CurrentTok->is(TT_LineComment);
CurrentTok = CurrentTok->Next) {
LastLineTok = LineTok;
StringRef TokenText(CurrentTok->TokenText);
assert((TokenText.startswith("//") || TokenText.startswith("#")) &&
"unsupported line comment prefix, '//' and '#' are supported");
size_t FirstLineIndex = Lines.size();
TokenText.split(Lines, "\n");
Content.resize(Lines.size());
ContentColumn.resize(Lines.size());
PrefixSpaceChange.resize(Lines.size());
Tokens.resize(Lines.size());
Prefix.resize(Lines.size());
OriginalPrefix.resize(Lines.size());
for (size_t i = FirstLineIndex, e = Lines.size(); i < e; ++i) {
Lines[i] = Lines[i].ltrim(Blanks);
StringRef IndentPrefix = getLineCommentIndentPrefix(Lines[i], Style);
OriginalPrefix[i] = IndentPrefix;
const int SpacesInPrefix = llvm::count(IndentPrefix, ' ');
const auto NoSpaceBeforeFirstCommentChar = [&]() {
assert(Lines[i].size() > IndentPrefix.size());
const char FirstCommentChar = Lines[i][IndentPrefix.size()];
const unsigned FirstCharByteSize =
encoding::getCodePointNumBytes(FirstCommentChar, Encoding);
if (encoding::columnWidth(
Lines[i].substr(IndentPrefix.size(), FirstCharByteSize),
Encoding) != 1) {
return false;
}
if (FirstCommentChar == '#' && !TokenText.startswith("#"))
return false;
return FirstCommentChar == '\\' || isPunctuation(FirstCommentChar) ||
isHorizontalWhitespace(FirstCommentChar);
};
if (i == 0 || OriginalPrefix[i].rtrim(Blanks) !=
OriginalPrefix[i - 1].rtrim(Blanks)) {
if (SpacesInPrefix < Minimum && Lines[i].size() > IndentPrefix.size() &&
!NoSpaceBeforeFirstCommentChar()) {
FirstLineSpaceChange = Minimum - SpacesInPrefix;
} else if (static_cast<unsigned>(SpacesInPrefix) >
Style.SpacesInLineCommentPrefix.Maximum) {
FirstLineSpaceChange =
Style.SpacesInLineCommentPrefix.Maximum - SpacesInPrefix;
} else {
FirstLineSpaceChange = 0;
}
}
if (Lines[i].size() != IndentPrefix.size()) {
PrefixSpaceChange[i] = FirstLineSpaceChange;
if (SpacesInPrefix + PrefixSpaceChange[i] < Minimum) {
PrefixSpaceChange[i] +=
Minimum - (SpacesInPrefix + PrefixSpaceChange[i]);
}
assert(Lines[i].size() > IndentPrefix.size());
const auto FirstNonSpace = Lines[i][IndentPrefix.size()];
const bool IsFormatComment = LineTok && switchesFormatting(*LineTok);
const bool LineRequiresLeadingSpace =
!NoSpaceBeforeFirstCommentChar() ||
(FirstNonSpace == '}' && FirstLineSpaceChange != 0);
const bool AllowsSpaceChange =
!IsFormatComment &&
(SpacesInPrefix != 0 || LineRequiresLeadingSpace);
if (PrefixSpaceChange[i] > 0 && AllowsSpaceChange) {
Prefix[i] = IndentPrefix.str();
Prefix[i].append(PrefixSpaceChange[i], ' ');
} else if (PrefixSpaceChange[i] < 0 && AllowsSpaceChange) {
Prefix[i] = IndentPrefix
.drop_back(std::min<std::size_t>(
-PrefixSpaceChange[i], SpacesInPrefix))
.str();
} else {
Prefix[i] = IndentPrefix.str();
}
} else {
Prefix[i] = IndentPrefix.drop_back(SpacesInPrefix).str();
}
Tokens[i] = LineTok;
Content[i] = Lines[i].substr(IndentPrefix.size());
ContentColumn[i] =
StartColumn + encoding::columnWidthWithTabs(Prefix[i], StartColumn,
Style.TabWidth, Encoding);
size_t EndOfLine = Content[i].find_last_not_of(Blanks);
if (EndOfLine == StringRef::npos)
EndOfLine = Content[i].size();
else
++EndOfLine;
Content[i] = Content[i].substr(0, EndOfLine);
}
LineTok = CurrentTok->Next;
if (CurrentTok->Next && !CurrentTok->Next->ContinuesLineCommentSection) {
break;
}
}
}
unsigned
BreakableLineCommentSection::getRangeLength(unsigned LineIndex, unsigned Offset,
StringRef::size_type Length,
unsigned StartColumn) const {
return encoding::columnWidthWithTabs(
Content[LineIndex].substr(Offset, Length), StartColumn, Style.TabWidth,
Encoding);
}
unsigned
BreakableLineCommentSection::getContentStartColumn(unsigned LineIndex,
bool ) const {
return ContentColumn[LineIndex];
}
void BreakableLineCommentSection::insertBreak(
unsigned LineIndex, unsigned TailOffset, Split Split,
unsigned ContentIndent, WhitespaceManager &Whitespaces) const {
StringRef Text = Content[LineIndex].substr(TailOffset);
unsigned BreakOffsetInToken =
Text.data() - tokenAt(LineIndex).TokenText.data() + Split.first;
unsigned CharsToRemove = Split.second;
Whitespaces.replaceWhitespaceInToken(
tokenAt(LineIndex), BreakOffsetInToken, CharsToRemove, "",
Prefix[LineIndex], InPPDirective, 1,
ContentColumn[LineIndex] - Prefix[LineIndex].size());
}
BreakableComment::Split BreakableLineCommentSection::getReflowSplit(
unsigned LineIndex, const llvm::Regex &CommentPragmasRegex) const {
if (!mayReflow(LineIndex, CommentPragmasRegex))
return Split(StringRef::npos, 0);
size_t Trimmed = Content[LineIndex].find_first_not_of(Blanks);
return Split(0, Trimmed != StringRef::npos ? Trimmed : 0);
}
void BreakableLineCommentSection::reflow(unsigned LineIndex,
WhitespaceManager &Whitespaces) const {
if (LineIndex > 0 && Tokens[LineIndex] != Tokens[LineIndex - 1]) {
Whitespaces.replaceWhitespace(
*Tokens[LineIndex], 0, 0,
StartColumn, true,
false);
} else if (LineIndex > 0) {
unsigned Offset = Lines[LineIndex - 1].data() +
Lines[LineIndex - 1].size() -
tokenAt(LineIndex - 1).TokenText.data();
unsigned WhitespaceLength =
Lines[LineIndex].data() - tokenAt(LineIndex).TokenText.data() - Offset;
Whitespaces.replaceWhitespaceInToken(*Tokens[LineIndex], Offset,
WhitespaceLength,
"",
"",
false,
0,
0);
}
unsigned Offset =
Lines[LineIndex].data() - tokenAt(LineIndex).TokenText.data();
unsigned WhitespaceLength =
Content[LineIndex].data() - Lines[LineIndex].data();
Whitespaces.replaceWhitespaceInToken(*Tokens[LineIndex], Offset,
WhitespaceLength,
"",
ReflowPrefix,
false,
0,
0);
}
void BreakableLineCommentSection::adaptStartOfLine(
unsigned LineIndex, WhitespaceManager &Whitespaces) const {
if (LineIndex > 0 && Tokens[LineIndex] != Tokens[LineIndex - 1]) {
unsigned LineColumn =
ContentColumn[LineIndex] -
(Content[LineIndex].data() - Lines[LineIndex].data()) +
(OriginalPrefix[LineIndex].size() - Prefix[LineIndex].size());
Whitespaces.replaceWhitespace(*Tokens[LineIndex],
1,
LineColumn,
LineColumn,
true,
false);
}
if (OriginalPrefix[LineIndex] != Prefix[LineIndex]) {
const auto SpacesToRemove = -std::min(PrefixSpaceChange[LineIndex], 0);
const auto SpacesToAdd = std::max(PrefixSpaceChange[LineIndex], 0);
Whitespaces.replaceWhitespaceInToken(
tokenAt(LineIndex), OriginalPrefix[LineIndex].size() - SpacesToRemove,
SpacesToRemove, "", "", false,
0, SpacesToAdd);
}
}
void BreakableLineCommentSection::updateNextToken(LineState &State) const {
if (LastLineTok)
State.NextToken = LastLineTok->Next;
}
bool BreakableLineCommentSection::mayReflow(
unsigned LineIndex, const llvm::Regex &CommentPragmasRegex) const {
StringRef IndentContent = Content[LineIndex];
if (Lines[LineIndex].startswith("//"))
IndentContent = Lines[LineIndex].substr(2);
return LineIndex > 0 && !CommentPragmasRegex.match(IndentContent) &&
mayReflowContent(Content[LineIndex]) && !Tok.Finalized &&
!switchesFormatting(tokenAt(LineIndex)) &&
OriginalPrefix[LineIndex] == OriginalPrefix[LineIndex - 1];
}
} }