Path: blob/main/contrib/llvm-project/clang/lib/Format/BreakableToken.cpp
35233 views
//===--- BreakableToken.cpp - Format C++ code -----------------------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//7///8/// \file9/// Contains implementation of BreakableToken class and classes derived10/// from it.11///12//===----------------------------------------------------------------------===//1314#include "BreakableToken.h"15#include "ContinuationIndenter.h"16#include "clang/Basic/CharInfo.h"17#include "clang/Format/Format.h"18#include "llvm/ADT/STLExtras.h"19#include "llvm/Support/Debug.h"20#include <algorithm>2122#define DEBUG_TYPE "format-token-breaker"2324namespace clang {25namespace format {2627static constexpr StringRef Blanks = " \t\v\f\r";28static bool IsBlank(char C) {29switch (C) {30case ' ':31case '\t':32case '\v':33case '\f':34case '\r':35return true;36default:37return false;38}39}4041static StringRef getLineCommentIndentPrefix(StringRef Comment,42const FormatStyle &Style) {43static constexpr StringRef KnownCStylePrefixes[] = {"///<", "//!<", "///",44"//!", "//:", "//"};45static constexpr StringRef KnownTextProtoPrefixes[] = {"####", "###", "##",46"//", "#"};47ArrayRef<StringRef> KnownPrefixes(KnownCStylePrefixes);48if (Style.Language == FormatStyle::LK_TextProto)49KnownPrefixes = KnownTextProtoPrefixes;5051assert(52llvm::is_sorted(KnownPrefixes, [](StringRef Lhs, StringRef Rhs) noexcept {53return Lhs.size() > Rhs.size();54}));5556for (StringRef KnownPrefix : KnownPrefixes) {57if (Comment.starts_with(KnownPrefix)) {58const auto PrefixLength =59Comment.find_first_not_of(' ', KnownPrefix.size());60return Comment.substr(0, PrefixLength);61}62}63return {};64}6566static BreakableToken::Split67getCommentSplit(StringRef Text, unsigned ContentStartColumn,68unsigned ColumnLimit, unsigned TabWidth,69encoding::Encoding Encoding, const FormatStyle &Style,70bool DecorationEndsWithStar = false) {71LLVM_DEBUG(llvm::dbgs() << "Comment split: \"" << Text72<< "\", Column limit: " << ColumnLimit73<< ", Content start: " << ContentStartColumn << "\n");74if (ColumnLimit <= ContentStartColumn + 1)75return BreakableToken::Split(StringRef::npos, 0);7677unsigned MaxSplit = ColumnLimit - ContentStartColumn + 1;78unsigned MaxSplitBytes = 0;7980for (unsigned NumChars = 0;81NumChars < MaxSplit && MaxSplitBytes < Text.size();) {82unsigned BytesInChar =83encoding::getCodePointNumBytes(Text[MaxSplitBytes], Encoding);84NumChars += encoding::columnWidthWithTabs(85Text.substr(MaxSplitBytes, BytesInChar), ContentStartColumn + NumChars,86TabWidth, Encoding);87MaxSplitBytes += BytesInChar;88}8990// In JavaScript, some @tags can be followed by {, and machinery that parses91// these comments will fail to understand the comment if followed by a line92// break. So avoid ever breaking before a {.93if (Style.isJavaScript()) {94StringRef::size_type SpaceOffset =95Text.find_first_of(Blanks, MaxSplitBytes);96if (SpaceOffset != StringRef::npos && SpaceOffset + 1 < Text.size() &&97Text[SpaceOffset + 1] == '{') {98MaxSplitBytes = SpaceOffset + 1;99}100}101102StringRef::size_type SpaceOffset = Text.find_last_of(Blanks, MaxSplitBytes);103104static const auto kNumberedListRegexp = llvm::Regex("^[1-9][0-9]?\\.");105// Some spaces are unacceptable to break on, rewind past them.106while (SpaceOffset != StringRef::npos) {107// If a line-comment ends with `\`, the next line continues the comment,108// whether or not it starts with `//`. This is confusing and triggers109// -Wcomment.110// Avoid introducing multiline comments by not allowing a break right111// after '\'.112if (Style.isCpp()) {113StringRef::size_type LastNonBlank =114Text.find_last_not_of(Blanks, SpaceOffset);115if (LastNonBlank != StringRef::npos && Text[LastNonBlank] == '\\') {116SpaceOffset = Text.find_last_of(Blanks, LastNonBlank);117continue;118}119}120121// Do not split before a number followed by a dot: this would be interpreted122// as a numbered list, which would prevent re-flowing in subsequent passes.123if (kNumberedListRegexp.match(Text.substr(SpaceOffset).ltrim(Blanks))) {124SpaceOffset = Text.find_last_of(Blanks, SpaceOffset);125continue;126}127128// Avoid ever breaking before a @tag or a { in JavaScript.129if (Style.isJavaScript() && SpaceOffset + 1 < Text.size() &&130(Text[SpaceOffset + 1] == '{' || Text[SpaceOffset + 1] == '@')) {131SpaceOffset = Text.find_last_of(Blanks, SpaceOffset);132continue;133}134135break;136}137138if (SpaceOffset == StringRef::npos ||139// Don't break at leading whitespace.140Text.find_last_not_of(Blanks, SpaceOffset) == StringRef::npos) {141// Make sure that we don't break at leading whitespace that142// reaches past MaxSplit.143StringRef::size_type FirstNonWhitespace = Text.find_first_not_of(Blanks);144if (FirstNonWhitespace == StringRef::npos) {145// If the comment is only whitespace, we cannot split.146return BreakableToken::Split(StringRef::npos, 0);147}148SpaceOffset = Text.find_first_of(149Blanks, std::max<unsigned>(MaxSplitBytes, FirstNonWhitespace));150}151if (SpaceOffset != StringRef::npos && SpaceOffset != 0) {152// adaptStartOfLine will break after lines starting with /** if the comment153// is broken anywhere. Avoid emitting this break twice here.154// Example: in /** longtextcomesherethatbreaks */ (with ColumnLimit 20) will155// insert a break after /**, so this code must not insert the same break.156if (SpaceOffset == 1 && Text[SpaceOffset - 1] == '*')157return BreakableToken::Split(StringRef::npos, 0);158StringRef BeforeCut = Text.substr(0, SpaceOffset).rtrim(Blanks);159StringRef AfterCut = Text.substr(SpaceOffset);160// Don't trim the leading blanks if it would create a */ after the break.161if (!DecorationEndsWithStar || AfterCut.size() <= 1 || AfterCut[1] != '/')162AfterCut = AfterCut.ltrim(Blanks);163return BreakableToken::Split(BeforeCut.size(),164AfterCut.begin() - BeforeCut.end());165}166return BreakableToken::Split(StringRef::npos, 0);167}168169static BreakableToken::Split170getStringSplit(StringRef Text, unsigned UsedColumns, unsigned ColumnLimit,171unsigned TabWidth, encoding::Encoding Encoding) {172// FIXME: Reduce unit test case.173if (Text.empty())174return BreakableToken::Split(StringRef::npos, 0);175if (ColumnLimit <= UsedColumns)176return BreakableToken::Split(StringRef::npos, 0);177unsigned MaxSplit = ColumnLimit - UsedColumns;178StringRef::size_type SpaceOffset = 0;179StringRef::size_type SlashOffset = 0;180StringRef::size_type WordStartOffset = 0;181StringRef::size_type SplitPoint = 0;182for (unsigned Chars = 0;;) {183unsigned Advance;184if (Text[0] == '\\') {185Advance = encoding::getEscapeSequenceLength(Text);186Chars += Advance;187} else {188Advance = encoding::getCodePointNumBytes(Text[0], Encoding);189Chars += encoding::columnWidthWithTabs(190Text.substr(0, Advance), UsedColumns + Chars, TabWidth, Encoding);191}192193if (Chars > MaxSplit || Text.size() <= Advance)194break;195196if (IsBlank(Text[0]))197SpaceOffset = SplitPoint;198if (Text[0] == '/')199SlashOffset = SplitPoint;200if (Advance == 1 && !isAlphanumeric(Text[0]))201WordStartOffset = SplitPoint;202203SplitPoint += Advance;204Text = Text.substr(Advance);205}206207if (SpaceOffset != 0)208return BreakableToken::Split(SpaceOffset + 1, 0);209if (SlashOffset != 0)210return BreakableToken::Split(SlashOffset + 1, 0);211if (WordStartOffset != 0)212return BreakableToken::Split(WordStartOffset + 1, 0);213if (SplitPoint != 0)214return BreakableToken::Split(SplitPoint, 0);215return BreakableToken::Split(StringRef::npos, 0);216}217218bool switchesFormatting(const FormatToken &Token) {219assert((Token.is(TT_BlockComment) || Token.is(TT_LineComment)) &&220"formatting regions are switched by comment tokens");221StringRef Content = Token.TokenText.substr(2).ltrim();222return Content.starts_with("clang-format on") ||223Content.starts_with("clang-format off");224}225226unsigned227BreakableToken::getLengthAfterCompression(unsigned RemainingTokenColumns,228Split Split) const {229// Example: consider the content230// lala lala231// - RemainingTokenColumns is the original number of columns, 10;232// - Split is (4, 2), denoting the two spaces between the two words;233//234// We compute the number of columns when the split is compressed into a single235// space, like:236// lala lala237//238// FIXME: Correctly measure the length of whitespace in Split.second so it239// works with tabs.240return RemainingTokenColumns + 1 - Split.second;241}242243unsigned BreakableStringLiteral::getLineCount() const { return 1; }244245unsigned BreakableStringLiteral::getRangeLength(unsigned LineIndex,246unsigned Offset,247StringRef::size_type Length,248unsigned StartColumn) const {249llvm_unreachable("Getting the length of a part of the string literal "250"indicates that the code tries to reflow it.");251}252253unsigned254BreakableStringLiteral::getRemainingLength(unsigned LineIndex, unsigned Offset,255unsigned StartColumn) const {256return UnbreakableTailLength + Postfix.size() +257encoding::columnWidthWithTabs(Line.substr(Offset), StartColumn,258Style.TabWidth, Encoding);259}260261unsigned BreakableStringLiteral::getContentStartColumn(unsigned LineIndex,262bool Break) const {263return StartColumn + Prefix.size();264}265266BreakableStringLiteral::BreakableStringLiteral(267const FormatToken &Tok, unsigned StartColumn, StringRef Prefix,268StringRef Postfix, unsigned UnbreakableTailLength, bool InPPDirective,269encoding::Encoding Encoding, const FormatStyle &Style)270: BreakableToken(Tok, InPPDirective, Encoding, Style),271StartColumn(StartColumn), Prefix(Prefix), Postfix(Postfix),272UnbreakableTailLength(UnbreakableTailLength) {273assert(Tok.TokenText.starts_with(Prefix) && Tok.TokenText.ends_with(Postfix));274Line = Tok.TokenText.substr(275Prefix.size(), Tok.TokenText.size() - Prefix.size() - Postfix.size());276}277278BreakableToken::Split BreakableStringLiteral::getSplit(279unsigned LineIndex, unsigned TailOffset, unsigned ColumnLimit,280unsigned ContentStartColumn, const llvm::Regex &CommentPragmasRegex) const {281return getStringSplit(Line.substr(TailOffset), ContentStartColumn,282ColumnLimit - Postfix.size(), Style.TabWidth, Encoding);283}284285void BreakableStringLiteral::insertBreak(unsigned LineIndex,286unsigned TailOffset, Split Split,287unsigned ContentIndent,288WhitespaceManager &Whitespaces) const {289Whitespaces.replaceWhitespaceInToken(290Tok, Prefix.size() + TailOffset + Split.first, Split.second, Postfix,291Prefix, InPPDirective, 1, StartColumn);292}293294BreakableStringLiteralUsingOperators::BreakableStringLiteralUsingOperators(295const FormatToken &Tok, QuoteStyleType QuoteStyle, bool UnindentPlus,296unsigned StartColumn, unsigned UnbreakableTailLength, bool InPPDirective,297encoding::Encoding Encoding, const FormatStyle &Style)298: BreakableStringLiteral(299Tok, StartColumn, /*Prefix=*/QuoteStyle == SingleQuotes ? "'"300: QuoteStyle == AtDoubleQuotes ? "@\""301: "\"",302/*Postfix=*/QuoteStyle == SingleQuotes ? "'" : "\"",303UnbreakableTailLength, InPPDirective, Encoding, Style),304BracesNeeded(Tok.isNot(TT_StringInConcatenation)),305QuoteStyle(QuoteStyle) {306// Find the replacement text for inserting braces and quotes and line breaks.307// We don't create an allocated string concatenated from parts here because it308// has to outlive the BreakableStringliteral object. The brace replacements309// include a quote so that WhitespaceManager can tell it apart from whitespace310// replacements between the string and surrounding tokens.311312// The option is not implemented in JavaScript.313bool SignOnNewLine =314!Style.isJavaScript() &&315Style.BreakBeforeBinaryOperators != FormatStyle::BOS_None;316317if (Style.isVerilog()) {318// In Verilog, all strings are quoted by double quotes, joined by commas,319// and wrapped in braces. The comma is always before the newline.320assert(QuoteStyle == DoubleQuotes);321LeftBraceQuote = Style.Cpp11BracedListStyle ? "{\"" : "{ \"";322RightBraceQuote = Style.Cpp11BracedListStyle ? "\"}" : "\" }";323Postfix = "\",";324Prefix = "\"";325} else {326// The plus sign may be on either line. And also C# and JavaScript have327// several quoting styles.328if (QuoteStyle == SingleQuotes) {329LeftBraceQuote = Style.SpacesInParensOptions.Other ? "( '" : "('";330RightBraceQuote = Style.SpacesInParensOptions.Other ? "' )" : "')";331Postfix = SignOnNewLine ? "'" : "' +";332Prefix = SignOnNewLine ? "+ '" : "'";333} else {334if (QuoteStyle == AtDoubleQuotes) {335LeftBraceQuote = Style.SpacesInParensOptions.Other ? "( @" : "(@";336Prefix = SignOnNewLine ? "+ @\"" : "@\"";337} else {338LeftBraceQuote = Style.SpacesInParensOptions.Other ? "( \"" : "(\"";339Prefix = SignOnNewLine ? "+ \"" : "\"";340}341RightBraceQuote = Style.SpacesInParensOptions.Other ? "\" )" : "\")";342Postfix = SignOnNewLine ? "\"" : "\" +";343}344}345346// Following lines are indented by the width of the brace and space if any.347ContinuationIndent = BracesNeeded ? LeftBraceQuote.size() - 1 : 0;348// The plus sign may need to be unindented depending on the style.349// FIXME: Add support for DontAlign.350if (!Style.isVerilog() && SignOnNewLine && !BracesNeeded && UnindentPlus &&351Style.AlignOperands == FormatStyle::OAS_AlignAfterOperator) {352ContinuationIndent -= 2;353}354}355356unsigned BreakableStringLiteralUsingOperators::getRemainingLength(357unsigned LineIndex, unsigned Offset, unsigned StartColumn) const {358return UnbreakableTailLength + (BracesNeeded ? RightBraceQuote.size() : 1) +359encoding::columnWidthWithTabs(Line.substr(Offset), StartColumn,360Style.TabWidth, Encoding);361}362363unsigned364BreakableStringLiteralUsingOperators::getContentStartColumn(unsigned LineIndex,365bool Break) const {366return std::max(3670,368static_cast<int>(StartColumn) +369(Break ? ContinuationIndent + static_cast<int>(Prefix.size())370: (BracesNeeded ? static_cast<int>(LeftBraceQuote.size()) - 1371: 0) +372(QuoteStyle == AtDoubleQuotes ? 2 : 1)));373}374375void BreakableStringLiteralUsingOperators::insertBreak(376unsigned LineIndex, unsigned TailOffset, Split Split,377unsigned ContentIndent, WhitespaceManager &Whitespaces) const {378Whitespaces.replaceWhitespaceInToken(379Tok, /*Offset=*/(QuoteStyle == AtDoubleQuotes ? 2 : 1) + TailOffset +380Split.first,381/*ReplaceChars=*/Split.second, /*PreviousPostfix=*/Postfix,382/*CurrentPrefix=*/Prefix, InPPDirective, /*NewLines=*/1,383/*Spaces=*/384std::max(0, static_cast<int>(StartColumn) + ContinuationIndent));385}386387void BreakableStringLiteralUsingOperators::updateAfterBroken(388WhitespaceManager &Whitespaces) const {389// Add the braces required for breaking the token if they are needed.390if (!BracesNeeded)391return;392393// To add a brace or parenthesis, we replace the quote (or the at sign) with a394// brace and another quote. This is because the rest of the program requires395// one replacement for each source range. If we replace the empty strings396// around the string, it may conflict with whitespace replacements between the397// string and adjacent tokens.398Whitespaces.replaceWhitespaceInToken(399Tok, /*Offset=*/0, /*ReplaceChars=*/1, /*PreviousPostfix=*/"",400/*CurrentPrefix=*/LeftBraceQuote, InPPDirective, /*NewLines=*/0,401/*Spaces=*/0);402Whitespaces.replaceWhitespaceInToken(403Tok, /*Offset=*/Tok.TokenText.size() - 1, /*ReplaceChars=*/1,404/*PreviousPostfix=*/RightBraceQuote,405/*CurrentPrefix=*/"", InPPDirective, /*NewLines=*/0, /*Spaces=*/0);406}407408BreakableComment::BreakableComment(const FormatToken &Token,409unsigned StartColumn, bool InPPDirective,410encoding::Encoding Encoding,411const FormatStyle &Style)412: BreakableToken(Token, InPPDirective, Encoding, Style),413StartColumn(StartColumn) {}414415unsigned BreakableComment::getLineCount() const { return Lines.size(); }416417BreakableToken::Split418BreakableComment::getSplit(unsigned LineIndex, unsigned TailOffset,419unsigned ColumnLimit, unsigned ContentStartColumn,420const llvm::Regex &CommentPragmasRegex) const {421// Don't break lines matching the comment pragmas regex.422if (CommentPragmasRegex.match(Content[LineIndex]))423return Split(StringRef::npos, 0);424return getCommentSplit(Content[LineIndex].substr(TailOffset),425ContentStartColumn, ColumnLimit, Style.TabWidth,426Encoding, Style);427}428429void BreakableComment::compressWhitespace(430unsigned LineIndex, unsigned TailOffset, Split Split,431WhitespaceManager &Whitespaces) const {432StringRef Text = Content[LineIndex].substr(TailOffset);433// Text is relative to the content line, but Whitespaces operates relative to434// the start of the corresponding token, so compute the start of the Split435// that needs to be compressed into a single space relative to the start of436// its token.437unsigned BreakOffsetInToken =438Text.data() - tokenAt(LineIndex).TokenText.data() + Split.first;439unsigned CharsToRemove = Split.second;440Whitespaces.replaceWhitespaceInToken(441tokenAt(LineIndex), BreakOffsetInToken, CharsToRemove, "", "",442/*InPPDirective=*/false, /*Newlines=*/0, /*Spaces=*/1);443}444445const FormatToken &BreakableComment::tokenAt(unsigned LineIndex) const {446return Tokens[LineIndex] ? *Tokens[LineIndex] : Tok;447}448449static bool mayReflowContent(StringRef Content) {450Content = Content.trim(Blanks);451// Lines starting with '@' or '\' commonly have special meaning.452// Lines starting with '-', '-#', '+' or '*' are bulleted/numbered lists.453bool hasSpecialMeaningPrefix = false;454for (StringRef Prefix :455{"@", "\\", "TODO", "FIXME", "XXX", "-# ", "- ", "+ ", "* "}) {456if (Content.starts_with(Prefix)) {457hasSpecialMeaningPrefix = true;458break;459}460}461462// Numbered lists may also start with a number followed by '.'463// To avoid issues if a line starts with a number which is actually the end464// of a previous line, we only consider numbers with up to 2 digits.465static const auto kNumberedListRegexp = llvm::Regex("^[1-9][0-9]?\\. ");466hasSpecialMeaningPrefix =467hasSpecialMeaningPrefix || kNumberedListRegexp.match(Content);468469// Simple heuristic for what to reflow: content should contain at least two470// characters and either the first or second character must be471// non-punctuation.472return Content.size() >= 2 && !hasSpecialMeaningPrefix &&473!Content.ends_with("\\") &&474// Note that this is UTF-8 safe, since if isPunctuation(Content[0]) is475// true, then the first code point must be 1 byte long.476(!isPunctuation(Content[0]) || !isPunctuation(Content[1]));477}478479BreakableBlockComment::BreakableBlockComment(480const FormatToken &Token, unsigned StartColumn,481unsigned OriginalStartColumn, bool FirstInLine, bool InPPDirective,482encoding::Encoding Encoding, const FormatStyle &Style, bool UseCRLF)483: BreakableComment(Token, StartColumn, InPPDirective, Encoding, Style),484DelimitersOnNewline(false),485UnbreakableTailLength(Token.UnbreakableTailLength) {486assert(Tok.is(TT_BlockComment) &&487"block comment section must start with a block comment");488489StringRef TokenText(Tok.TokenText);490assert(TokenText.starts_with("/*") && TokenText.ends_with("*/"));491TokenText.substr(2, TokenText.size() - 4)492.split(Lines, UseCRLF ? "\r\n" : "\n");493494int IndentDelta = StartColumn - OriginalStartColumn;495Content.resize(Lines.size());496Content[0] = Lines[0];497ContentColumn.resize(Lines.size());498// Account for the initial '/*'.499ContentColumn[0] = StartColumn + 2;500Tokens.resize(Lines.size());501for (size_t i = 1; i < Lines.size(); ++i)502adjustWhitespace(i, IndentDelta);503504// Align decorations with the column of the star on the first line,505// that is one column after the start "/*".506DecorationColumn = StartColumn + 1;507508// Account for comment decoration patterns like this:509//510// /*511// ** blah blah blah512// */513if (Lines.size() >= 2 && Content[1].starts_with("**") &&514static_cast<unsigned>(ContentColumn[1]) == StartColumn) {515DecorationColumn = StartColumn;516}517518Decoration = "* ";519if (Lines.size() == 1 && !FirstInLine) {520// Comments for which FirstInLine is false can start on arbitrary column,521// and available horizontal space can be too small to align consecutive522// lines with the first one.523// FIXME: We could, probably, align them to current indentation level, but524// now we just wrap them without stars.525Decoration = "";526}527for (size_t i = 1, e = Content.size(); i < e && !Decoration.empty(); ++i) {528const StringRef &Text = Content[i];529if (i + 1 == e) {530// If the last line is empty, the closing "*/" will have a star.531if (Text.empty())532break;533} else if (!Text.empty() && Decoration.starts_with(Text)) {534continue;535}536while (!Text.starts_with(Decoration))537Decoration = Decoration.drop_back(1);538}539540LastLineNeedsDecoration = true;541IndentAtLineBreak = ContentColumn[0] + 1;542for (size_t i = 1, e = Lines.size(); i < e; ++i) {543if (Content[i].empty()) {544if (i + 1 == e) {545// Empty last line means that we already have a star as a part of the546// trailing */. We also need to preserve whitespace, so that */ is547// correctly indented.548LastLineNeedsDecoration = false;549// Align the star in the last '*/' with the stars on the previous lines.550if (e >= 2 && !Decoration.empty())551ContentColumn[i] = DecorationColumn;552} else if (Decoration.empty()) {553// For all other lines, set the start column to 0 if they're empty, so554// we do not insert trailing whitespace anywhere.555ContentColumn[i] = 0;556}557continue;558}559560// The first line already excludes the star.561// The last line excludes the star if LastLineNeedsDecoration is false.562// For all other lines, adjust the line to exclude the star and563// (optionally) the first whitespace.564unsigned DecorationSize = Decoration.starts_with(Content[i])565? Content[i].size()566: Decoration.size();567if (DecorationSize)568ContentColumn[i] = DecorationColumn + DecorationSize;569Content[i] = Content[i].substr(DecorationSize);570if (!Decoration.starts_with(Content[i])) {571IndentAtLineBreak =572std::min<int>(IndentAtLineBreak, std::max(0, ContentColumn[i]));573}574}575IndentAtLineBreak = std::max<unsigned>(IndentAtLineBreak, Decoration.size());576577// Detect a multiline jsdoc comment and set DelimitersOnNewline in that case.578if (Style.isJavaScript() || Style.Language == FormatStyle::LK_Java) {579if ((Lines[0] == "*" || Lines[0].starts_with("* ")) && Lines.size() > 1) {580// This is a multiline jsdoc comment.581DelimitersOnNewline = true;582} else if (Lines[0].starts_with("* ") && Lines.size() == 1) {583// Detect a long single-line comment, like:584// /** long long long */585// Below, '2' is the width of '*/'.586unsigned EndColumn =587ContentColumn[0] +588encoding::columnWidthWithTabs(Lines[0], ContentColumn[0],589Style.TabWidth, Encoding) +5902;591DelimitersOnNewline = EndColumn > Style.ColumnLimit;592}593}594595LLVM_DEBUG({596llvm::dbgs() << "IndentAtLineBreak " << IndentAtLineBreak << "\n";597llvm::dbgs() << "DelimitersOnNewline " << DelimitersOnNewline << "\n";598for (size_t i = 0; i < Lines.size(); ++i) {599llvm::dbgs() << i << " |" << Content[i] << "| "600<< "CC=" << ContentColumn[i] << "| "601<< "IN=" << (Content[i].data() - Lines[i].data()) << "\n";602}603});604}605606BreakableToken::Split BreakableBlockComment::getSplit(607unsigned LineIndex, unsigned TailOffset, unsigned ColumnLimit,608unsigned ContentStartColumn, const llvm::Regex &CommentPragmasRegex) const {609// Don't break lines matching the comment pragmas regex.610if (CommentPragmasRegex.match(Content[LineIndex]))611return Split(StringRef::npos, 0);612return getCommentSplit(Content[LineIndex].substr(TailOffset),613ContentStartColumn, ColumnLimit, Style.TabWidth,614Encoding, Style, Decoration.ends_with("*"));615}616617void BreakableBlockComment::adjustWhitespace(unsigned LineIndex,618int IndentDelta) {619// When in a preprocessor directive, the trailing backslash in a block comment620// is not needed, but can serve a purpose of uniformity with necessary escaped621// newlines outside the comment. In this case we remove it here before622// trimming the trailing whitespace. The backslash will be re-added later when623// inserting a line break.624size_t EndOfPreviousLine = Lines[LineIndex - 1].size();625if (InPPDirective && Lines[LineIndex - 1].ends_with("\\"))626--EndOfPreviousLine;627628// Calculate the end of the non-whitespace text in the previous line.629EndOfPreviousLine =630Lines[LineIndex - 1].find_last_not_of(Blanks, EndOfPreviousLine);631if (EndOfPreviousLine == StringRef::npos)632EndOfPreviousLine = 0;633else634++EndOfPreviousLine;635// Calculate the start of the non-whitespace text in the current line.636size_t StartOfLine = Lines[LineIndex].find_first_not_of(Blanks);637if (StartOfLine == StringRef::npos)638StartOfLine = Lines[LineIndex].size();639640StringRef Whitespace = Lines[LineIndex].substr(0, StartOfLine);641// Adjust Lines to only contain relevant text.642size_t PreviousContentOffset =643Content[LineIndex - 1].data() - Lines[LineIndex - 1].data();644Content[LineIndex - 1] = Lines[LineIndex - 1].substr(645PreviousContentOffset, EndOfPreviousLine - PreviousContentOffset);646Content[LineIndex] = Lines[LineIndex].substr(StartOfLine);647648// Adjust the start column uniformly across all lines.649ContentColumn[LineIndex] =650encoding::columnWidthWithTabs(Whitespace, 0, Style.TabWidth, Encoding) +651IndentDelta;652}653654unsigned BreakableBlockComment::getRangeLength(unsigned LineIndex,655unsigned Offset,656StringRef::size_type Length,657unsigned StartColumn) const {658return encoding::columnWidthWithTabs(659Content[LineIndex].substr(Offset, Length), StartColumn, Style.TabWidth,660Encoding);661}662663unsigned BreakableBlockComment::getRemainingLength(unsigned LineIndex,664unsigned Offset,665unsigned StartColumn) const {666unsigned LineLength =667UnbreakableTailLength +668getRangeLength(LineIndex, Offset, StringRef::npos, StartColumn);669if (LineIndex + 1 == Lines.size()) {670LineLength += 2;671// We never need a decoration when breaking just the trailing "*/" postfix.672bool HasRemainingText = Offset < Content[LineIndex].size();673if (!HasRemainingText) {674bool HasDecoration = Lines[LineIndex].ltrim().starts_with(Decoration);675if (HasDecoration)676LineLength -= Decoration.size();677}678}679return LineLength;680}681682unsigned BreakableBlockComment::getContentStartColumn(unsigned LineIndex,683bool Break) const {684if (Break)685return IndentAtLineBreak;686return std::max(0, ContentColumn[LineIndex]);687}688689const llvm::StringSet<>690BreakableBlockComment::ContentIndentingJavadocAnnotations = {691"@param", "@return", "@returns", "@throws", "@type", "@template",692"@see", "@deprecated", "@define", "@exports", "@mods", "@private",693};694695unsigned BreakableBlockComment::getContentIndent(unsigned LineIndex) const {696if (Style.Language != FormatStyle::LK_Java && !Style.isJavaScript())697return 0;698// The content at LineIndex 0 of a comment like:699// /** line 0 */700// is "* line 0", so we need to skip over the decoration in that case.701StringRef ContentWithNoDecoration = Content[LineIndex];702if (LineIndex == 0 && ContentWithNoDecoration.starts_with("*"))703ContentWithNoDecoration = ContentWithNoDecoration.substr(1).ltrim(Blanks);704StringRef FirstWord = ContentWithNoDecoration.substr(7050, ContentWithNoDecoration.find_first_of(Blanks));706if (ContentIndentingJavadocAnnotations.contains(FirstWord))707return Style.ContinuationIndentWidth;708return 0;709}710711void BreakableBlockComment::insertBreak(unsigned LineIndex, unsigned TailOffset,712Split Split, unsigned ContentIndent,713WhitespaceManager &Whitespaces) const {714StringRef Text = Content[LineIndex].substr(TailOffset);715StringRef Prefix = Decoration;716// We need this to account for the case when we have a decoration "* " for all717// the lines except for the last one, where the star in "*/" acts as a718// decoration.719unsigned LocalIndentAtLineBreak = IndentAtLineBreak;720if (LineIndex + 1 == Lines.size() &&721Text.size() == Split.first + Split.second) {722// For the last line we need to break before "*/", but not to add "* ".723Prefix = "";724if (LocalIndentAtLineBreak >= 2)725LocalIndentAtLineBreak -= 2;726}727// The split offset is from the beginning of the line. Convert it to an offset728// from the beginning of the token text.729unsigned BreakOffsetInToken =730Text.data() - tokenAt(LineIndex).TokenText.data() + Split.first;731unsigned CharsToRemove = Split.second;732assert(LocalIndentAtLineBreak >= Prefix.size());733std::string PrefixWithTrailingIndent = std::string(Prefix);734PrefixWithTrailingIndent.append(ContentIndent, ' ');735Whitespaces.replaceWhitespaceInToken(736tokenAt(LineIndex), BreakOffsetInToken, CharsToRemove, "",737PrefixWithTrailingIndent, InPPDirective, /*Newlines=*/1,738/*Spaces=*/LocalIndentAtLineBreak + ContentIndent -739PrefixWithTrailingIndent.size());740}741742BreakableToken::Split BreakableBlockComment::getReflowSplit(743unsigned LineIndex, const llvm::Regex &CommentPragmasRegex) const {744if (!mayReflow(LineIndex, CommentPragmasRegex))745return Split(StringRef::npos, 0);746747// If we're reflowing into a line with content indent, only reflow the next748// line if its starting whitespace matches the content indent.749size_t Trimmed = Content[LineIndex].find_first_not_of(Blanks);750if (LineIndex) {751unsigned PreviousContentIndent = getContentIndent(LineIndex - 1);752if (PreviousContentIndent && Trimmed != StringRef::npos &&753Trimmed != PreviousContentIndent) {754return Split(StringRef::npos, 0);755}756}757758return Split(0, Trimmed != StringRef::npos ? Trimmed : 0);759}760761bool BreakableBlockComment::introducesBreakBeforeToken() const {762// A break is introduced when we want delimiters on newline.763return DelimitersOnNewline &&764Lines[0].substr(1).find_first_not_of(Blanks) != StringRef::npos;765}766767void BreakableBlockComment::reflow(unsigned LineIndex,768WhitespaceManager &Whitespaces) const {769StringRef TrimmedContent = Content[LineIndex].ltrim(Blanks);770// Here we need to reflow.771assert(Tokens[LineIndex - 1] == Tokens[LineIndex] &&772"Reflowing whitespace within a token");773// This is the offset of the end of the last line relative to the start of774// the token text in the token.775unsigned WhitespaceOffsetInToken = Content[LineIndex - 1].data() +776Content[LineIndex - 1].size() -777tokenAt(LineIndex).TokenText.data();778unsigned WhitespaceLength = TrimmedContent.data() -779tokenAt(LineIndex).TokenText.data() -780WhitespaceOffsetInToken;781Whitespaces.replaceWhitespaceInToken(782tokenAt(LineIndex), WhitespaceOffsetInToken,783/*ReplaceChars=*/WhitespaceLength, /*PreviousPostfix=*/"",784/*CurrentPrefix=*/ReflowPrefix, InPPDirective, /*Newlines=*/0,785/*Spaces=*/0);786}787788void BreakableBlockComment::adaptStartOfLine(789unsigned LineIndex, WhitespaceManager &Whitespaces) const {790if (LineIndex == 0) {791if (DelimitersOnNewline) {792// Since we're breaking at index 1 below, the break position and the793// break length are the same.794// Note: this works because getCommentSplit is careful never to split at795// the beginning of a line.796size_t BreakLength = Lines[0].substr(1).find_first_not_of(Blanks);797if (BreakLength != StringRef::npos) {798insertBreak(LineIndex, 0, Split(1, BreakLength), /*ContentIndent=*/0,799Whitespaces);800}801}802return;803}804// Here no reflow with the previous line will happen.805// Fix the decoration of the line at LineIndex.806StringRef Prefix = Decoration;807if (Content[LineIndex].empty()) {808if (LineIndex + 1 == Lines.size()) {809if (!LastLineNeedsDecoration) {810// If the last line was empty, we don't need a prefix, as the */ will811// line up with the decoration (if it exists).812Prefix = "";813}814} else if (!Decoration.empty()) {815// For other empty lines, if we do have a decoration, adapt it to not816// contain a trailing whitespace.817Prefix = Prefix.substr(0, 1);818}819} else if (ContentColumn[LineIndex] == 1) {820// This line starts immediately after the decorating *.821Prefix = Prefix.substr(0, 1);822}823// This is the offset of the end of the last line relative to the start of the824// token text in the token.825unsigned WhitespaceOffsetInToken = Content[LineIndex - 1].data() +826Content[LineIndex - 1].size() -827tokenAt(LineIndex).TokenText.data();828unsigned WhitespaceLength = Content[LineIndex].data() -829tokenAt(LineIndex).TokenText.data() -830WhitespaceOffsetInToken;831Whitespaces.replaceWhitespaceInToken(832tokenAt(LineIndex), WhitespaceOffsetInToken, WhitespaceLength, "", Prefix,833InPPDirective, /*Newlines=*/1, ContentColumn[LineIndex] - Prefix.size());834}835836BreakableToken::Split837BreakableBlockComment::getSplitAfterLastLine(unsigned TailOffset) const {838if (DelimitersOnNewline) {839// Replace the trailing whitespace of the last line with a newline.840// In case the last line is empty, the ending '*/' is already on its own841// line.842StringRef Line = Content.back().substr(TailOffset);843StringRef TrimmedLine = Line.rtrim(Blanks);844if (!TrimmedLine.empty())845return Split(TrimmedLine.size(), Line.size() - TrimmedLine.size());846}847return Split(StringRef::npos, 0);848}849850bool BreakableBlockComment::mayReflow(851unsigned LineIndex, const llvm::Regex &CommentPragmasRegex) const {852// Content[LineIndex] may exclude the indent after the '*' decoration. In that853// case, we compute the start of the comment pragma manually.854StringRef IndentContent = Content[LineIndex];855if (Lines[LineIndex].ltrim(Blanks).starts_with("*"))856IndentContent = Lines[LineIndex].ltrim(Blanks).substr(1);857return LineIndex > 0 && !CommentPragmasRegex.match(IndentContent) &&858mayReflowContent(Content[LineIndex]) && !Tok.Finalized &&859!switchesFormatting(tokenAt(LineIndex));860}861862BreakableLineCommentSection::BreakableLineCommentSection(863const FormatToken &Token, unsigned StartColumn, bool InPPDirective,864encoding::Encoding Encoding, const FormatStyle &Style)865: BreakableComment(Token, StartColumn, InPPDirective, Encoding, Style) {866assert(Tok.is(TT_LineComment) &&867"line comment section must start with a line comment");868FormatToken *LineTok = nullptr;869const int Minimum = Style.SpacesInLineCommentPrefix.Minimum;870// How many spaces we changed in the first line of the section, this will be871// applied in all following lines872int FirstLineSpaceChange = 0;873for (const FormatToken *CurrentTok = &Tok;874CurrentTok && CurrentTok->is(TT_LineComment);875CurrentTok = CurrentTok->Next) {876LastLineTok = LineTok;877StringRef TokenText(CurrentTok->TokenText);878assert((TokenText.starts_with("//") || TokenText.starts_with("#")) &&879"unsupported line comment prefix, '//' and '#' are supported");880size_t FirstLineIndex = Lines.size();881TokenText.split(Lines, "\n");882Content.resize(Lines.size());883ContentColumn.resize(Lines.size());884PrefixSpaceChange.resize(Lines.size());885Tokens.resize(Lines.size());886Prefix.resize(Lines.size());887OriginalPrefix.resize(Lines.size());888for (size_t i = FirstLineIndex, e = Lines.size(); i < e; ++i) {889Lines[i] = Lines[i].ltrim(Blanks);890StringRef IndentPrefix = getLineCommentIndentPrefix(Lines[i], Style);891OriginalPrefix[i] = IndentPrefix;892const int SpacesInPrefix = llvm::count(IndentPrefix, ' ');893894// This lambda also considers multibyte character that is not handled in895// functions like isPunctuation provided by CharInfo.896const auto NoSpaceBeforeFirstCommentChar = [&]() {897assert(Lines[i].size() > IndentPrefix.size());898const char FirstCommentChar = Lines[i][IndentPrefix.size()];899const unsigned FirstCharByteSize =900encoding::getCodePointNumBytes(FirstCommentChar, Encoding);901if (encoding::columnWidth(902Lines[i].substr(IndentPrefix.size(), FirstCharByteSize),903Encoding) != 1) {904return false;905}906// In C-like comments, add a space before #. For example this is useful907// to preserve the relative indentation when commenting out code with908// #includes.909//910// In languages using # as the comment leader such as proto, don't911// add a space to support patterns like:912// #########913// # section914// #########915if (FirstCommentChar == '#' && !TokenText.starts_with("#"))916return false;917return FirstCommentChar == '\\' || isPunctuation(FirstCommentChar) ||918isHorizontalWhitespace(FirstCommentChar);919};920921// On the first line of the comment section we calculate how many spaces922// are to be added or removed, all lines after that just get only the923// change and we will not look at the maximum anymore. Additionally to the924// actual first line, we calculate that when the non space Prefix changes,925// e.g. from "///" to "//".926if (i == 0 || OriginalPrefix[i].rtrim(Blanks) !=927OriginalPrefix[i - 1].rtrim(Blanks)) {928if (SpacesInPrefix < Minimum && Lines[i].size() > IndentPrefix.size() &&929!NoSpaceBeforeFirstCommentChar()) {930FirstLineSpaceChange = Minimum - SpacesInPrefix;931} else if (static_cast<unsigned>(SpacesInPrefix) >932Style.SpacesInLineCommentPrefix.Maximum) {933FirstLineSpaceChange =934Style.SpacesInLineCommentPrefix.Maximum - SpacesInPrefix;935} else {936FirstLineSpaceChange = 0;937}938}939940if (Lines[i].size() != IndentPrefix.size()) {941PrefixSpaceChange[i] = FirstLineSpaceChange;942943if (SpacesInPrefix + PrefixSpaceChange[i] < Minimum) {944PrefixSpaceChange[i] +=945Minimum - (SpacesInPrefix + PrefixSpaceChange[i]);946}947948assert(Lines[i].size() > IndentPrefix.size());949const auto FirstNonSpace = Lines[i][IndentPrefix.size()];950const bool IsFormatComment = LineTok && switchesFormatting(*LineTok);951const bool LineRequiresLeadingSpace =952!NoSpaceBeforeFirstCommentChar() ||953(FirstNonSpace == '}' && FirstLineSpaceChange != 0);954const bool AllowsSpaceChange =955!IsFormatComment &&956(SpacesInPrefix != 0 || LineRequiresLeadingSpace);957958if (PrefixSpaceChange[i] > 0 && AllowsSpaceChange) {959Prefix[i] = IndentPrefix.str();960Prefix[i].append(PrefixSpaceChange[i], ' ');961} else if (PrefixSpaceChange[i] < 0 && AllowsSpaceChange) {962Prefix[i] = IndentPrefix963.drop_back(std::min<std::size_t>(964-PrefixSpaceChange[i], SpacesInPrefix))965.str();966} else {967Prefix[i] = IndentPrefix.str();968}969} else {970// If the IndentPrefix is the whole line, there is no content and we971// drop just all space972Prefix[i] = IndentPrefix.drop_back(SpacesInPrefix).str();973}974975Tokens[i] = LineTok;976Content[i] = Lines[i].substr(IndentPrefix.size());977ContentColumn[i] =978StartColumn + encoding::columnWidthWithTabs(Prefix[i], StartColumn,979Style.TabWidth, Encoding);980981// Calculate the end of the non-whitespace text in this line.982size_t EndOfLine = Content[i].find_last_not_of(Blanks);983if (EndOfLine == StringRef::npos)984EndOfLine = Content[i].size();985else986++EndOfLine;987Content[i] = Content[i].substr(0, EndOfLine);988}989LineTok = CurrentTok->Next;990if (CurrentTok->Next && !CurrentTok->Next->ContinuesLineCommentSection) {991// A line comment section needs to broken by a line comment that is992// preceded by at least two newlines. Note that we put this break here993// instead of breaking at a previous stage during parsing, since that994// would split the contents of the enum into two unwrapped lines in this995// example, which is undesirable:996// enum A {997// a, // comment about a998//999// // comment about b1000// b1001// };1002//1003// FIXME: Consider putting separate line comment sections as children to1004// the unwrapped line instead.1005break;1006}1007}1008}10091010unsigned1011BreakableLineCommentSection::getRangeLength(unsigned LineIndex, unsigned Offset,1012StringRef::size_type Length,1013unsigned StartColumn) const {1014return encoding::columnWidthWithTabs(1015Content[LineIndex].substr(Offset, Length), StartColumn, Style.TabWidth,1016Encoding);1017}10181019unsigned1020BreakableLineCommentSection::getContentStartColumn(unsigned LineIndex,1021bool /*Break*/) const {1022return ContentColumn[LineIndex];1023}10241025void BreakableLineCommentSection::insertBreak(1026unsigned LineIndex, unsigned TailOffset, Split Split,1027unsigned ContentIndent, WhitespaceManager &Whitespaces) const {1028StringRef Text = Content[LineIndex].substr(TailOffset);1029// Compute the offset of the split relative to the beginning of the token1030// text.1031unsigned BreakOffsetInToken =1032Text.data() - tokenAt(LineIndex).TokenText.data() + Split.first;1033unsigned CharsToRemove = Split.second;1034Whitespaces.replaceWhitespaceInToken(1035tokenAt(LineIndex), BreakOffsetInToken, CharsToRemove, "",1036Prefix[LineIndex], InPPDirective, /*Newlines=*/1,1037/*Spaces=*/ContentColumn[LineIndex] - Prefix[LineIndex].size());1038}10391040BreakableComment::Split BreakableLineCommentSection::getReflowSplit(1041unsigned LineIndex, const llvm::Regex &CommentPragmasRegex) const {1042if (!mayReflow(LineIndex, CommentPragmasRegex))1043return Split(StringRef::npos, 0);10441045size_t Trimmed = Content[LineIndex].find_first_not_of(Blanks);10461047// In a line comment section each line is a separate token; thus, after a1048// split we replace all whitespace before the current line comment token1049// (which does not need to be included in the split), plus the start of the1050// line up to where the content starts.1051return Split(0, Trimmed != StringRef::npos ? Trimmed : 0);1052}10531054void BreakableLineCommentSection::reflow(unsigned LineIndex,1055WhitespaceManager &Whitespaces) const {1056if (LineIndex > 0 && Tokens[LineIndex] != Tokens[LineIndex - 1]) {1057// Reflow happens between tokens. Replace the whitespace between the1058// tokens by the empty string.1059Whitespaces.replaceWhitespace(1060*Tokens[LineIndex], /*Newlines=*/0, /*Spaces=*/0,1061/*StartOfTokenColumn=*/StartColumn, /*IsAligned=*/true,1062/*InPPDirective=*/false);1063} else if (LineIndex > 0) {1064// In case we're reflowing after the '\' in:1065//1066// // line comment \1067// // line 21068//1069// the reflow happens inside the single comment token (it is a single line1070// comment with an unescaped newline).1071// Replace the whitespace between the '\' and '//' with the empty string.1072//1073// Offset points to after the '\' relative to start of the token.1074unsigned Offset = Lines[LineIndex - 1].data() +1075Lines[LineIndex - 1].size() -1076tokenAt(LineIndex - 1).TokenText.data();1077// WhitespaceLength is the number of chars between the '\' and the '//' on1078// the next line.1079unsigned WhitespaceLength =1080Lines[LineIndex].data() - tokenAt(LineIndex).TokenText.data() - Offset;1081Whitespaces.replaceWhitespaceInToken(*Tokens[LineIndex], Offset,1082/*ReplaceChars=*/WhitespaceLength,1083/*PreviousPostfix=*/"",1084/*CurrentPrefix=*/"",1085/*InPPDirective=*/false,1086/*Newlines=*/0,1087/*Spaces=*/0);1088}1089// Replace the indent and prefix of the token with the reflow prefix.1090unsigned Offset =1091Lines[LineIndex].data() - tokenAt(LineIndex).TokenText.data();1092unsigned WhitespaceLength =1093Content[LineIndex].data() - Lines[LineIndex].data();1094Whitespaces.replaceWhitespaceInToken(*Tokens[LineIndex], Offset,1095/*ReplaceChars=*/WhitespaceLength,1096/*PreviousPostfix=*/"",1097/*CurrentPrefix=*/ReflowPrefix,1098/*InPPDirective=*/false,1099/*Newlines=*/0,1100/*Spaces=*/0);1101}11021103void BreakableLineCommentSection::adaptStartOfLine(1104unsigned LineIndex, WhitespaceManager &Whitespaces) const {1105// If this is the first line of a token, we need to inform Whitespace Manager1106// about it: either adapt the whitespace range preceding it, or mark it as an1107// untouchable token.1108// This happens for instance here:1109// // line 1 \1110// // line 21111if (LineIndex > 0 && Tokens[LineIndex] != Tokens[LineIndex - 1]) {1112// This is the first line for the current token, but no reflow with the1113// previous token is necessary. However, we still may need to adjust the1114// start column. Note that ContentColumn[LineIndex] is the expected1115// content column after a possible update to the prefix, hence the prefix1116// length change is included.1117unsigned LineColumn =1118ContentColumn[LineIndex] -1119(Content[LineIndex].data() - Lines[LineIndex].data()) +1120(OriginalPrefix[LineIndex].size() - Prefix[LineIndex].size());11211122// We always want to create a replacement instead of adding an untouchable1123// token, even if LineColumn is the same as the original column of the1124// token. This is because WhitespaceManager doesn't align trailing1125// comments if they are untouchable.1126Whitespaces.replaceWhitespace(*Tokens[LineIndex],1127/*Newlines=*/1,1128/*Spaces=*/LineColumn,1129/*StartOfTokenColumn=*/LineColumn,1130/*IsAligned=*/true,1131/*InPPDirective=*/false);1132}1133if (OriginalPrefix[LineIndex] != Prefix[LineIndex]) {1134// Adjust the prefix if necessary.1135const auto SpacesToRemove = -std::min(PrefixSpaceChange[LineIndex], 0);1136const auto SpacesToAdd = std::max(PrefixSpaceChange[LineIndex], 0);1137Whitespaces.replaceWhitespaceInToken(1138tokenAt(LineIndex), OriginalPrefix[LineIndex].size() - SpacesToRemove,1139/*ReplaceChars=*/SpacesToRemove, "", "", /*InPPDirective=*/false,1140/*Newlines=*/0, /*Spaces=*/SpacesToAdd);1141}1142}11431144void BreakableLineCommentSection::updateNextToken(LineState &State) const {1145if (LastLineTok)1146State.NextToken = LastLineTok->Next;1147}11481149bool BreakableLineCommentSection::mayReflow(1150unsigned LineIndex, const llvm::Regex &CommentPragmasRegex) const {1151// Line comments have the indent as part of the prefix, so we need to1152// recompute the start of the line.1153StringRef IndentContent = Content[LineIndex];1154if (Lines[LineIndex].starts_with("//"))1155IndentContent = Lines[LineIndex].substr(2);1156// FIXME: Decide whether we want to reflow non-regular indents:1157// Currently, we only reflow when the OriginalPrefix[LineIndex] matches the1158// OriginalPrefix[LineIndex-1]. That means we don't reflow1159// // text that protrudes1160// // into text with different indent1161// We do reflow in that case in block comments.1162return LineIndex > 0 && !CommentPragmasRegex.match(IndentContent) &&1163mayReflowContent(Content[LineIndex]) && !Tok.Finalized &&1164!switchesFormatting(tokenAt(LineIndex)) &&1165OriginalPrefix[LineIndex] == OriginalPrefix[LineIndex - 1];1166}11671168} // namespace format1169} // namespace clang117011711172