Home | History | Annotate | Line # | Download | only in Format
BreakableToken.cpp revision 1.1
      1 //===--- BreakableToken.cpp - Format C++ code -----------------------------===//
      2 //
      3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
      4 // See https://llvm.org/LICENSE.txt for license information.
      5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
      6 //
      7 //===----------------------------------------------------------------------===//
      8 ///
      9 /// \file
     10 /// Contains implementation of BreakableToken class and classes derived
     11 /// from it.
     12 ///
     13 //===----------------------------------------------------------------------===//
     14 
     15 #include "BreakableToken.h"
     16 #include "ContinuationIndenter.h"
     17 #include "clang/Basic/CharInfo.h"
     18 #include "clang/Format/Format.h"
     19 #include "llvm/ADT/STLExtras.h"
     20 #include "llvm/Support/Debug.h"
     21 #include <algorithm>
     22 
     23 #define DEBUG_TYPE "format-token-breaker"
     24 
     25 namespace clang {
     26 namespace format {
     27 
     28 static const char *const Blanks = " \t\v\f\r";
     29 static bool IsBlank(char C) {
     30   switch (C) {
     31   case ' ':
     32   case '\t':
     33   case '\v':
     34   case '\f':
     35   case '\r':
     36     return true;
     37   default:
     38     return false;
     39   }
     40 }
     41 
     42 static StringRef getLineCommentIndentPrefix(StringRef Comment,
     43                                             const FormatStyle &Style) {
     44   static const char *const KnownCStylePrefixes[] = {"///<", "//!<", "///", "//",
     45                                                     "//!"};
     46   static const char *const KnownTextProtoPrefixes[] = {"//", "#", "##", "###",
     47                                                        "####"};
     48   ArrayRef<const char *> KnownPrefixes(KnownCStylePrefixes);
     49   if (Style.Language == FormatStyle::LK_TextProto)
     50     KnownPrefixes = KnownTextProtoPrefixes;
     51 
     52   StringRef LongestPrefix;
     53   for (StringRef KnownPrefix : KnownPrefixes) {
     54     if (Comment.startswith(KnownPrefix)) {
     55       size_t PrefixLength = KnownPrefix.size();
     56       while (PrefixLength < Comment.size() && Comment[PrefixLength] == ' ')
     57         ++PrefixLength;
     58       if (PrefixLength > LongestPrefix.size())
     59         LongestPrefix = Comment.substr(0, PrefixLength);
     60     }
     61   }
     62   return LongestPrefix;
     63 }
     64 
     65 static BreakableToken::Split
     66 getCommentSplit(StringRef Text, unsigned ContentStartColumn,
     67                 unsigned ColumnLimit, unsigned TabWidth,
     68                 encoding::Encoding Encoding, const FormatStyle &Style,
     69                 bool DecorationEndsWithStar = false) {
     70   LLVM_DEBUG(llvm::dbgs() << "Comment split: \"" << Text
     71                           << "\", Column limit: " << ColumnLimit
     72                           << ", Content start: " << ContentStartColumn << "\n");
     73   if (ColumnLimit <= ContentStartColumn + 1)
     74     return BreakableToken::Split(StringRef::npos, 0);
     75 
     76   unsigned MaxSplit = ColumnLimit - ContentStartColumn + 1;
     77   unsigned MaxSplitBytes = 0;
     78 
     79   for (unsigned NumChars = 0;
     80        NumChars < MaxSplit && MaxSplitBytes < Text.size();) {
     81     unsigned BytesInChar =
     82         encoding::getCodePointNumBytes(Text[MaxSplitBytes], Encoding);
     83     NumChars +=
     84         encoding::columnWidthWithTabs(Text.substr(MaxSplitBytes, BytesInChar),
     85                                       ContentStartColumn, TabWidth, Encoding);
     86     MaxSplitBytes += BytesInChar;
     87   }
     88 
     89   StringRef::size_type SpaceOffset = Text.find_last_of(Blanks, MaxSplitBytes);
     90 
     91   static auto *const kNumberedListRegexp = new llvm::Regex("^[1-9][0-9]?\\.");
     92   while (SpaceOffset != StringRef::npos) {
     93     // Do not split before a number followed by a dot: this would be interpreted
     94     // as a numbered list, which would prevent re-flowing in subsequent passes.
     95     if (kNumberedListRegexp->match(Text.substr(SpaceOffset).ltrim(Blanks)))
     96       SpaceOffset = Text.find_last_of(Blanks, SpaceOffset);
     97     // In JavaScript, some @tags can be followed by {, and machinery that parses
     98     // these comments will fail to understand the comment if followed by a line
     99     // break. So avoid ever breaking before a {.
    100     else if (Style.Language == FormatStyle::LK_JavaScript &&
    101              SpaceOffset + 1 < Text.size() && Text[SpaceOffset + 1] == '{')
    102       SpaceOffset = Text.find_last_of(Blanks, SpaceOffset);
    103     else
    104       break;
    105   }
    106 
    107   if (SpaceOffset == StringRef::npos ||
    108       // Don't break at leading whitespace.
    109       Text.find_last_not_of(Blanks, SpaceOffset) == StringRef::npos) {
    110     // Make sure that we don't break at leading whitespace that
    111     // reaches past MaxSplit.
    112     StringRef::size_type FirstNonWhitespace = Text.find_first_not_of(Blanks);
    113     if (FirstNonWhitespace == StringRef::npos)
    114       // If the comment is only whitespace, we cannot split.
    115       return BreakableToken::Split(StringRef::npos, 0);
    116     SpaceOffset = Text.find_first_of(
    117         Blanks, std::max<unsigned>(MaxSplitBytes, FirstNonWhitespace));
    118   }
    119   if (SpaceOffset != StringRef::npos && SpaceOffset != 0) {
    120     // adaptStartOfLine will break after lines starting with /** if the comment
    121     // is broken anywhere. Avoid emitting this break twice here.
    122     // Example: in /** longtextcomesherethatbreaks */ (with ColumnLimit 20) will
    123     // insert a break after /**, so this code must not insert the same break.
    124     if (SpaceOffset == 1 && Text[SpaceOffset - 1] == '*')
    125       return BreakableToken::Split(StringRef::npos, 0);
    126     StringRef BeforeCut = Text.substr(0, SpaceOffset).rtrim(Blanks);
    127     StringRef AfterCut = Text.substr(SpaceOffset);
    128     // Don't trim the leading blanks if it would create a */ after the break.
    129     if (!DecorationEndsWithStar || AfterCut.size() <= 1 || AfterCut[1] != '/')
    130       AfterCut = AfterCut.ltrim(Blanks);
    131     return BreakableToken::Split(BeforeCut.size(),
    132                                  AfterCut.begin() - BeforeCut.end());
    133   }
    134   return BreakableToken::Split(StringRef::npos, 0);
    135 }
    136 
    137 static BreakableToken::Split
    138 getStringSplit(StringRef Text, unsigned UsedColumns, unsigned ColumnLimit,
    139                unsigned TabWidth, encoding::Encoding Encoding) {
    140   // FIXME: Reduce unit test case.
    141   if (Text.empty())
    142     return BreakableToken::Split(StringRef::npos, 0);
    143   if (ColumnLimit <= UsedColumns)
    144     return BreakableToken::Split(StringRef::npos, 0);
    145   unsigned MaxSplit = ColumnLimit - UsedColumns;
    146   StringRef::size_type SpaceOffset = 0;
    147   StringRef::size_type SlashOffset = 0;
    148   StringRef::size_type WordStartOffset = 0;
    149   StringRef::size_type SplitPoint = 0;
    150   for (unsigned Chars = 0;;) {
    151     unsigned Advance;
    152     if (Text[0] == '\\') {
    153       Advance = encoding::getEscapeSequenceLength(Text);
    154       Chars += Advance;
    155     } else {
    156       Advance = encoding::getCodePointNumBytes(Text[0], Encoding);
    157       Chars += encoding::columnWidthWithTabs(
    158           Text.substr(0, Advance), UsedColumns + Chars, TabWidth, Encoding);
    159     }
    160 
    161     if (Chars > MaxSplit || Text.size() <= Advance)
    162       break;
    163 
    164     if (IsBlank(Text[0]))
    165       SpaceOffset = SplitPoint;
    166     if (Text[0] == '/')
    167       SlashOffset = SplitPoint;
    168     if (Advance == 1 && !isAlphanumeric(Text[0]))
    169       WordStartOffset = SplitPoint;
    170 
    171     SplitPoint += Advance;
    172     Text = Text.substr(Advance);
    173   }
    174 
    175   if (SpaceOffset != 0)
    176     return BreakableToken::Split(SpaceOffset + 1, 0);
    177   if (SlashOffset != 0)
    178     return BreakableToken::Split(SlashOffset + 1, 0);
    179   if (WordStartOffset != 0)
    180     return BreakableToken::Split(WordStartOffset + 1, 0);
    181   if (SplitPoint != 0)
    182     return BreakableToken::Split(SplitPoint, 0);
    183   return BreakableToken::Split(StringRef::npos, 0);
    184 }
    185 
    186 bool switchesFormatting(const FormatToken &Token) {
    187   assert((Token.is(TT_BlockComment) || Token.is(TT_LineComment)) &&
    188          "formatting regions are switched by comment tokens");
    189   StringRef Content = Token.TokenText.substr(2).ltrim();
    190   return Content.startswith("clang-format on") ||
    191          Content.startswith("clang-format off");
    192 }
    193 
    194 unsigned
    195 BreakableToken::getLengthAfterCompression(unsigned RemainingTokenColumns,
    196                                           Split Split) const {
    197   // Example: consider the content
    198   // lala  lala
    199   // - RemainingTokenColumns is the original number of columns, 10;
    200   // - Split is (4, 2), denoting the two spaces between the two words;
    201   //
    202   // We compute the number of columns when the split is compressed into a single
    203   // space, like:
    204   // lala lala
    205   //
    206   // FIXME: Correctly measure the length of whitespace in Split.second so it
    207   // works with tabs.
    208   return RemainingTokenColumns + 1 - Split.second;
    209 }
    210 
    211 unsigned BreakableStringLiteral::getLineCount() const { return 1; }
    212 
    213 unsigned BreakableStringLiteral::getRangeLength(unsigned LineIndex,
    214                                                 unsigned Offset,
    215                                                 StringRef::size_type Length,
    216                                                 unsigned StartColumn) const {
    217   llvm_unreachable("Getting the length of a part of the string literal "
    218                    "indicates that the code tries to reflow it.");
    219 }
    220 
    221 unsigned
    222 BreakableStringLiteral::getRemainingLength(unsigned LineIndex, unsigned Offset,
    223                                            unsigned StartColumn) const {
    224   return UnbreakableTailLength + Postfix.size() +
    225          encoding::columnWidthWithTabs(Line.substr(Offset, StringRef::npos),
    226                                        StartColumn, Style.TabWidth, Encoding);
    227 }
    228 
    229 unsigned BreakableStringLiteral::getContentStartColumn(unsigned LineIndex,
    230                                                        bool Break) const {
    231   return StartColumn + Prefix.size();
    232 }
    233 
    234 BreakableStringLiteral::BreakableStringLiteral(
    235     const FormatToken &Tok, unsigned StartColumn, StringRef Prefix,
    236     StringRef Postfix, unsigned UnbreakableTailLength, bool InPPDirective,
    237     encoding::Encoding Encoding, const FormatStyle &Style)
    238     : BreakableToken(Tok, InPPDirective, Encoding, Style),
    239       StartColumn(StartColumn), Prefix(Prefix), Postfix(Postfix),
    240       UnbreakableTailLength(UnbreakableTailLength) {
    241   assert(Tok.TokenText.startswith(Prefix) && Tok.TokenText.endswith(Postfix));
    242   Line = Tok.TokenText.substr(
    243       Prefix.size(), Tok.TokenText.size() - Prefix.size() - Postfix.size());
    244 }
    245 
    246 BreakableToken::Split BreakableStringLiteral::getSplit(
    247     unsigned LineIndex, unsigned TailOffset, unsigned ColumnLimit,
    248     unsigned ContentStartColumn, llvm::Regex &CommentPragmasRegex) const {
    249   return getStringSplit(Line.substr(TailOffset), ContentStartColumn,
    250                         ColumnLimit - Postfix.size(), Style.TabWidth, Encoding);
    251 }
    252 
    253 void BreakableStringLiteral::insertBreak(unsigned LineIndex,
    254                                          unsigned TailOffset, Split Split,
    255                                          unsigned ContentIndent,
    256                                          WhitespaceManager &Whitespaces) const {
    257   Whitespaces.replaceWhitespaceInToken(
    258       Tok, Prefix.size() + TailOffset + Split.first, Split.second, Postfix,
    259       Prefix, InPPDirective, 1, StartColumn);
    260 }
    261 
    262 BreakableComment::BreakableComment(const FormatToken &Token,
    263                                    unsigned StartColumn, bool InPPDirective,
    264                                    encoding::Encoding Encoding,
    265                                    const FormatStyle &Style)
    266     : BreakableToken(Token, InPPDirective, Encoding, Style),
    267       StartColumn(StartColumn) {}
    268 
    269 unsigned BreakableComment::getLineCount() const { return Lines.size(); }
    270 
    271 BreakableToken::Split
    272 BreakableComment::getSplit(unsigned LineIndex, unsigned TailOffset,
    273                            unsigned ColumnLimit, unsigned ContentStartColumn,
    274                            llvm::Regex &CommentPragmasRegex) const {
    275   // Don't break lines matching the comment pragmas regex.
    276   if (CommentPragmasRegex.match(Content[LineIndex]))
    277     return Split(StringRef::npos, 0);
    278   return getCommentSplit(Content[LineIndex].substr(TailOffset),
    279                          ContentStartColumn, ColumnLimit, Style.TabWidth,
    280                          Encoding, Style);
    281 }
    282 
    283 void BreakableComment::compressWhitespace(
    284     unsigned LineIndex, unsigned TailOffset, Split Split,
    285     WhitespaceManager &Whitespaces) const {
    286   StringRef Text = Content[LineIndex].substr(TailOffset);
    287   // Text is relative to the content line, but Whitespaces operates relative to
    288   // the start of the corresponding token, so compute the start of the Split
    289   // that needs to be compressed into a single space relative to the start of
    290   // its token.
    291   unsigned BreakOffsetInToken =
    292       Text.data() - tokenAt(LineIndex).TokenText.data() + Split.first;
    293   unsigned CharsToRemove = Split.second;
    294   Whitespaces.replaceWhitespaceInToken(
    295       tokenAt(LineIndex), BreakOffsetInToken, CharsToRemove, "", "",
    296       /*InPPDirective=*/false, /*Newlines=*/0, /*Spaces=*/1);
    297 }
    298 
    299 const FormatToken &BreakableComment::tokenAt(unsigned LineIndex) const {
    300   return Tokens[LineIndex] ? *Tokens[LineIndex] : Tok;
    301 }
    302 
    303 static bool mayReflowContent(StringRef Content) {
    304   Content = Content.trim(Blanks);
    305   // Lines starting with '@' commonly have special meaning.
    306   // Lines starting with '-', '-#', '+' or '*' are bulleted/numbered lists.
    307   bool hasSpecialMeaningPrefix = false;
    308   for (StringRef Prefix :
    309        {"@", "TODO", "FIXME", "XXX", "-# ", "- ", "+ ", "* "}) {
    310     if (Content.startswith(Prefix)) {
    311       hasSpecialMeaningPrefix = true;
    312       break;
    313     }
    314   }
    315 
    316   // Numbered lists may also start with a number followed by '.'
    317   // To avoid issues if a line starts with a number which is actually the end
    318   // of a previous line, we only consider numbers with up to 2 digits.
    319   static auto *const kNumberedListRegexp = new llvm::Regex("^[1-9][0-9]?\\. ");
    320   hasSpecialMeaningPrefix =
    321       hasSpecialMeaningPrefix || kNumberedListRegexp->match(Content);
    322 
    323   // Simple heuristic for what to reflow: content should contain at least two
    324   // characters and either the first or second character must be
    325   // non-punctuation.
    326   return Content.size() >= 2 && !hasSpecialMeaningPrefix &&
    327          !Content.endswith("\\") &&
    328          // Note that this is UTF-8 safe, since if isPunctuation(Content[0]) is
    329          // true, then the first code point must be 1 byte long.
    330          (!isPunctuation(Content[0]) || !isPunctuation(Content[1]));
    331 }
    332 
    333 BreakableBlockComment::BreakableBlockComment(
    334     const FormatToken &Token, unsigned StartColumn,
    335     unsigned OriginalStartColumn, bool FirstInLine, bool InPPDirective,
    336     encoding::Encoding Encoding, const FormatStyle &Style, bool UseCRLF)
    337     : BreakableComment(Token, StartColumn, InPPDirective, Encoding, Style),
    338       DelimitersOnNewline(false),
    339       UnbreakableTailLength(Token.UnbreakableTailLength) {
    340   assert(Tok.is(TT_BlockComment) &&
    341          "block comment section must start with a block comment");
    342 
    343   StringRef TokenText(Tok.TokenText);
    344   assert(TokenText.startswith("/*") && TokenText.endswith("*/"));
    345   TokenText.substr(2, TokenText.size() - 4)
    346       .split(Lines, UseCRLF ? "\r\n" : "\n");
    347 
    348   int IndentDelta = StartColumn - OriginalStartColumn;
    349   Content.resize(Lines.size());
    350   Content[0] = Lines[0];
    351   ContentColumn.resize(Lines.size());
    352   // Account for the initial '/*'.
    353   ContentColumn[0] = StartColumn + 2;
    354   Tokens.resize(Lines.size());
    355   for (size_t i = 1; i < Lines.size(); ++i)
    356     adjustWhitespace(i, IndentDelta);
    357 
    358   // Align decorations with the column of the star on the first line,
    359   // that is one column after the start "/*".
    360   DecorationColumn = StartColumn + 1;
    361 
    362   // Account for comment decoration patterns like this:
    363   //
    364   // /*
    365   // ** blah blah blah
    366   // */
    367   if (Lines.size() >= 2 && Content[1].startswith("**") &&
    368       static_cast<unsigned>(ContentColumn[1]) == StartColumn) {
    369     DecorationColumn = StartColumn;
    370   }
    371 
    372   Decoration = "* ";
    373   if (Lines.size() == 1 && !FirstInLine) {
    374     // Comments for which FirstInLine is false can start on arbitrary column,
    375     // and available horizontal space can be too small to align consecutive
    376     // lines with the first one.
    377     // FIXME: We could, probably, align them to current indentation level, but
    378     // now we just wrap them without stars.
    379     Decoration = "";
    380   }
    381   for (size_t i = 1, e = Lines.size(); i < e && !Decoration.empty(); ++i) {
    382     // If the last line is empty, the closing "*/" will have a star.
    383     if (i + 1 == e && Content[i].empty())
    384       break;
    385     if (!Content[i].empty() && i + 1 != e && Decoration.startswith(Content[i]))
    386       continue;
    387     while (!Content[i].startswith(Decoration))
    388       Decoration = Decoration.substr(0, Decoration.size() - 1);
    389   }
    390 
    391   LastLineNeedsDecoration = true;
    392   IndentAtLineBreak = ContentColumn[0] + 1;
    393   for (size_t i = 1, e = Lines.size(); i < e; ++i) {
    394     if (Content[i].empty()) {
    395       if (i + 1 == e) {
    396         // Empty last line means that we already have a star as a part of the
    397         // trailing */. We also need to preserve whitespace, so that */ is
    398         // correctly indented.
    399         LastLineNeedsDecoration = false;
    400         // Align the star in the last '*/' with the stars on the previous lines.
    401         if (e >= 2 && !Decoration.empty()) {
    402           ContentColumn[i] = DecorationColumn;
    403         }
    404       } else if (Decoration.empty()) {
    405         // For all other lines, set the start column to 0 if they're empty, so
    406         // we do not insert trailing whitespace anywhere.
    407         ContentColumn[i] = 0;
    408       }
    409       continue;
    410     }
    411 
    412     // The first line already excludes the star.
    413     // The last line excludes the star if LastLineNeedsDecoration is false.
    414     // For all other lines, adjust the line to exclude the star and
    415     // (optionally) the first whitespace.
    416     unsigned DecorationSize = Decoration.startswith(Content[i])
    417                                   ? Content[i].size()
    418                                   : Decoration.size();
    419     if (DecorationSize) {
    420       ContentColumn[i] = DecorationColumn + DecorationSize;
    421     }
    422     Content[i] = Content[i].substr(DecorationSize);
    423     if (!Decoration.startswith(Content[i]))
    424       IndentAtLineBreak =
    425           std::min<int>(IndentAtLineBreak, std::max(0, ContentColumn[i]));
    426   }
    427   IndentAtLineBreak = std::max<unsigned>(IndentAtLineBreak, Decoration.size());
    428 
    429   // Detect a multiline jsdoc comment and set DelimitersOnNewline in that case.
    430   if (Style.Language == FormatStyle::LK_JavaScript ||
    431       Style.Language == FormatStyle::LK_Java) {
    432     if ((Lines[0] == "*" || Lines[0].startswith("* ")) && Lines.size() > 1) {
    433       // This is a multiline jsdoc comment.
    434       DelimitersOnNewline = true;
    435     } else if (Lines[0].startswith("* ") && Lines.size() == 1) {
    436       // Detect a long single-line comment, like:
    437       // /** long long long */
    438       // Below, '2' is the width of '*/'.
    439       unsigned EndColumn =
    440           ContentColumn[0] +
    441           encoding::columnWidthWithTabs(Lines[0], ContentColumn[0],
    442                                         Style.TabWidth, Encoding) +
    443           2;
    444       DelimitersOnNewline = EndColumn > Style.ColumnLimit;
    445     }
    446   }
    447 
    448   LLVM_DEBUG({
    449     llvm::dbgs() << "IndentAtLineBreak " << IndentAtLineBreak << "\n";
    450     llvm::dbgs() << "DelimitersOnNewline " << DelimitersOnNewline << "\n";
    451     for (size_t i = 0; i < Lines.size(); ++i) {
    452       llvm::dbgs() << i << " |" << Content[i] << "| "
    453                    << "CC=" << ContentColumn[i] << "| "
    454                    << "IN=" << (Content[i].data() - Lines[i].data()) << "\n";
    455     }
    456   });
    457 }
    458 
    459 BreakableToken::Split BreakableBlockComment::getSplit(
    460     unsigned LineIndex, unsigned TailOffset, unsigned ColumnLimit,
    461     unsigned ContentStartColumn, llvm::Regex &CommentPragmasRegex) const {
    462   // Don't break lines matching the comment pragmas regex.
    463   if (CommentPragmasRegex.match(Content[LineIndex]))
    464     return Split(StringRef::npos, 0);
    465   return getCommentSplit(Content[LineIndex].substr(TailOffset),
    466                          ContentStartColumn, ColumnLimit, Style.TabWidth,
    467                          Encoding, Style, Decoration.endswith("*"));
    468 }
    469 
    470 void BreakableBlockComment::adjustWhitespace(unsigned LineIndex,
    471                                              int IndentDelta) {
    472   // When in a preprocessor directive, the trailing backslash in a block comment
    473   // is not needed, but can serve a purpose of uniformity with necessary escaped
    474   // newlines outside the comment. In this case we remove it here before
    475   // trimming the trailing whitespace. The backslash will be re-added later when
    476   // inserting a line break.
    477   size_t EndOfPreviousLine = Lines[LineIndex - 1].size();
    478   if (InPPDirective && Lines[LineIndex - 1].endswith("\\"))
    479     --EndOfPreviousLine;
    480 
    481   // Calculate the end of the non-whitespace text in the previous line.
    482   EndOfPreviousLine =
    483       Lines[LineIndex - 1].find_last_not_of(Blanks, EndOfPreviousLine);
    484   if (EndOfPreviousLine == StringRef::npos)
    485     EndOfPreviousLine = 0;
    486   else
    487     ++EndOfPreviousLine;
    488   // Calculate the start of the non-whitespace text in the current line.
    489   size_t StartOfLine = Lines[LineIndex].find_first_not_of(Blanks);
    490   if (StartOfLine == StringRef::npos)
    491     StartOfLine = Lines[LineIndex].size();
    492 
    493   StringRef Whitespace = Lines[LineIndex].substr(0, StartOfLine);
    494   // Adjust Lines to only contain relevant text.
    495   size_t PreviousContentOffset =
    496       Content[LineIndex - 1].data() - Lines[LineIndex - 1].data();
    497   Content[LineIndex - 1] = Lines[LineIndex - 1].substr(
    498       PreviousContentOffset, EndOfPreviousLine - PreviousContentOffset);
    499   Content[LineIndex] = Lines[LineIndex].substr(StartOfLine);
    500 
    501   // Adjust the start column uniformly across all lines.
    502   ContentColumn[LineIndex] =
    503       encoding::columnWidthWithTabs(Whitespace, 0, Style.TabWidth, Encoding) +
    504       IndentDelta;
    505 }
    506 
    507 unsigned BreakableBlockComment::getRangeLength(unsigned LineIndex,
    508                                                unsigned Offset,
    509                                                StringRef::size_type Length,
    510                                                unsigned StartColumn) const {
    511   unsigned LineLength =
    512       encoding::columnWidthWithTabs(Content[LineIndex].substr(Offset, Length),
    513                                     StartColumn, Style.TabWidth, Encoding);
    514   // FIXME: This should go into getRemainingLength instead, but we currently
    515   // break tests when putting it there. Investigate how to fix those tests.
    516   // The last line gets a "*/" postfix.
    517   if (LineIndex + 1 == Lines.size()) {
    518     LineLength += 2;
    519     // We never need a decoration when breaking just the trailing "*/" postfix.
    520     // Note that checking that Length == 0 is not enough, since Length could
    521     // also be StringRef::npos.
    522     if (Content[LineIndex].substr(Offset, StringRef::npos).empty()) {
    523       LineLength -= Decoration.size();
    524     }
    525   }
    526   return LineLength;
    527 }
    528 
    529 unsigned BreakableBlockComment::getRemainingLength(unsigned LineIndex,
    530                                                    unsigned Offset,
    531                                                    unsigned StartColumn) const {
    532   return UnbreakableTailLength +
    533          getRangeLength(LineIndex, Offset, StringRef::npos, StartColumn);
    534 }
    535 
    536 unsigned BreakableBlockComment::getContentStartColumn(unsigned LineIndex,
    537                                                       bool Break) const {
    538   if (Break)
    539     return IndentAtLineBreak;
    540   return std::max(0, ContentColumn[LineIndex]);
    541 }
    542 
    543 const llvm::StringSet<>
    544     BreakableBlockComment::ContentIndentingJavadocAnnotations = {
    545         "@param", "@return",     "@returns", "@throws",  "@type", "@template",
    546         "@see",   "@deprecated", "@define",  "@exports", "@mods", "@private",
    547 };
    548 
    549 unsigned BreakableBlockComment::getContentIndent(unsigned LineIndex) const {
    550   if (Style.Language != FormatStyle::LK_Java &&
    551       Style.Language != FormatStyle::LK_JavaScript)
    552     return 0;
    553   // The content at LineIndex 0 of a comment like:
    554   // /** line 0 */
    555   // is "* line 0", so we need to skip over the decoration in that case.
    556   StringRef ContentWithNoDecoration = Content[LineIndex];
    557   if (LineIndex == 0 && ContentWithNoDecoration.startswith("*")) {
    558     ContentWithNoDecoration = ContentWithNoDecoration.substr(1).ltrim(Blanks);
    559   }
    560   StringRef FirstWord = ContentWithNoDecoration.substr(
    561       0, ContentWithNoDecoration.find_first_of(Blanks));
    562   if (ContentIndentingJavadocAnnotations.find(FirstWord) !=
    563       ContentIndentingJavadocAnnotations.end())
    564     return Style.ContinuationIndentWidth;
    565   return 0;
    566 }
    567 
    568 void BreakableBlockComment::insertBreak(unsigned LineIndex, unsigned TailOffset,
    569                                         Split Split, unsigned ContentIndent,
    570                                         WhitespaceManager &Whitespaces) const {
    571   StringRef Text = Content[LineIndex].substr(TailOffset);
    572   StringRef Prefix = Decoration;
    573   // We need this to account for the case when we have a decoration "* " for all
    574   // the lines except for the last one, where the star in "*/" acts as a
    575   // decoration.
    576   unsigned LocalIndentAtLineBreak = IndentAtLineBreak;
    577   if (LineIndex + 1 == Lines.size() &&
    578       Text.size() == Split.first + Split.second) {
    579     // For the last line we need to break before "*/", but not to add "* ".
    580     Prefix = "";
    581     if (LocalIndentAtLineBreak >= 2)
    582       LocalIndentAtLineBreak -= 2;
    583   }
    584   // The split offset is from the beginning of the line. Convert it to an offset
    585   // from the beginning of the token text.
    586   unsigned BreakOffsetInToken =
    587       Text.data() - tokenAt(LineIndex).TokenText.data() + Split.first;
    588   unsigned CharsToRemove = Split.second;
    589   assert(LocalIndentAtLineBreak >= Prefix.size());
    590   std::string PrefixWithTrailingIndent = Prefix;
    591   for (unsigned I = 0; I < ContentIndent; ++I)
    592     PrefixWithTrailingIndent += " ";
    593   Whitespaces.replaceWhitespaceInToken(
    594       tokenAt(LineIndex), BreakOffsetInToken, CharsToRemove, "",
    595       PrefixWithTrailingIndent, InPPDirective, /*Newlines=*/1,
    596       /*Spaces=*/LocalIndentAtLineBreak + ContentIndent -
    597           PrefixWithTrailingIndent.size());
    598 }
    599 
    600 BreakableToken::Split
    601 BreakableBlockComment::getReflowSplit(unsigned LineIndex,
    602                                       llvm::Regex &CommentPragmasRegex) const {
    603   if (!mayReflow(LineIndex, CommentPragmasRegex))
    604     return Split(StringRef::npos, 0);
    605 
    606   // If we're reflowing into a line with content indent, only reflow the next
    607   // line if its starting whitespace matches the content indent.
    608   size_t Trimmed = Content[LineIndex].find_first_not_of(Blanks);
    609   if (LineIndex) {
    610     unsigned PreviousContentIndent = getContentIndent(LineIndex - 1);
    611     if (PreviousContentIndent && Trimmed != StringRef::npos &&
    612         Trimmed != PreviousContentIndent)
    613       return Split(StringRef::npos, 0);
    614   }
    615 
    616   return Split(0, Trimmed != StringRef::npos ? Trimmed : 0);
    617 }
    618 
    619 bool BreakableBlockComment::introducesBreakBeforeToken() const {
    620   // A break is introduced when we want delimiters on newline.
    621   return DelimitersOnNewline &&
    622          Lines[0].substr(1).find_first_not_of(Blanks) != StringRef::npos;
    623 }
    624 
    625 void BreakableBlockComment::reflow(unsigned LineIndex,
    626                                    WhitespaceManager &Whitespaces) const {
    627   StringRef TrimmedContent = Content[LineIndex].ltrim(Blanks);
    628   // Here we need to reflow.
    629   assert(Tokens[LineIndex - 1] == Tokens[LineIndex] &&
    630          "Reflowing whitespace within a token");
    631   // This is the offset of the end of the last line relative to the start of
    632   // the token text in the token.
    633   unsigned WhitespaceOffsetInToken = Content[LineIndex - 1].data() +
    634                                      Content[LineIndex - 1].size() -
    635                                      tokenAt(LineIndex).TokenText.data();
    636   unsigned WhitespaceLength = TrimmedContent.data() -
    637                               tokenAt(LineIndex).TokenText.data() -
    638                               WhitespaceOffsetInToken;
    639   Whitespaces.replaceWhitespaceInToken(
    640       tokenAt(LineIndex), WhitespaceOffsetInToken,
    641       /*ReplaceChars=*/WhitespaceLength, /*PreviousPostfix=*/"",
    642       /*CurrentPrefix=*/ReflowPrefix, InPPDirective, /*Newlines=*/0,
    643       /*Spaces=*/0);
    644 }
    645 
    646 void BreakableBlockComment::adaptStartOfLine(
    647     unsigned LineIndex, WhitespaceManager &Whitespaces) const {
    648   if (LineIndex == 0) {
    649     if (DelimitersOnNewline) {
    650       // Since we're breaking at index 1 below, the break position and the
    651       // break length are the same.
    652       // Note: this works because getCommentSplit is careful never to split at
    653       // the beginning of a line.
    654       size_t BreakLength = Lines[0].substr(1).find_first_not_of(Blanks);
    655       if (BreakLength != StringRef::npos)
    656         insertBreak(LineIndex, 0, Split(1, BreakLength), /*ContentIndent=*/0,
    657                     Whitespaces);
    658     }
    659     return;
    660   }
    661   // Here no reflow with the previous line will happen.
    662   // Fix the decoration of the line at LineIndex.
    663   StringRef Prefix = Decoration;
    664   if (Content[LineIndex].empty()) {
    665     if (LineIndex + 1 == Lines.size()) {
    666       if (!LastLineNeedsDecoration) {
    667         // If the last line was empty, we don't need a prefix, as the */ will
    668         // line up with the decoration (if it exists).
    669         Prefix = "";
    670       }
    671     } else if (!Decoration.empty()) {
    672       // For other empty lines, if we do have a decoration, adapt it to not
    673       // contain a trailing whitespace.
    674       Prefix = Prefix.substr(0, 1);
    675     }
    676   } else {
    677     if (ContentColumn[LineIndex] == 1) {
    678       // This line starts immediately after the decorating *.
    679       Prefix = Prefix.substr(0, 1);
    680     }
    681   }
    682   // This is the offset of the end of the last line relative to the start of the
    683   // token text in the token.
    684   unsigned WhitespaceOffsetInToken = Content[LineIndex - 1].data() +
    685                                      Content[LineIndex - 1].size() -
    686                                      tokenAt(LineIndex).TokenText.data();
    687   unsigned WhitespaceLength = Content[LineIndex].data() -
    688                               tokenAt(LineIndex).TokenText.data() -
    689                               WhitespaceOffsetInToken;
    690   Whitespaces.replaceWhitespaceInToken(
    691       tokenAt(LineIndex), WhitespaceOffsetInToken, WhitespaceLength, "", Prefix,
    692       InPPDirective, /*Newlines=*/1, ContentColumn[LineIndex] - Prefix.size());
    693 }
    694 
    695 BreakableToken::Split
    696 BreakableBlockComment::getSplitAfterLastLine(unsigned TailOffset) const {
    697   if (DelimitersOnNewline) {
    698     // Replace the trailing whitespace of the last line with a newline.
    699     // In case the last line is empty, the ending '*/' is already on its own
    700     // line.
    701     StringRef Line = Content.back().substr(TailOffset);
    702     StringRef TrimmedLine = Line.rtrim(Blanks);
    703     if (!TrimmedLine.empty())
    704       return Split(TrimmedLine.size(), Line.size() - TrimmedLine.size());
    705   }
    706   return Split(StringRef::npos, 0);
    707 }
    708 
    709 bool BreakableBlockComment::mayReflow(unsigned LineIndex,
    710                                       llvm::Regex &CommentPragmasRegex) const {
    711   // Content[LineIndex] may exclude the indent after the '*' decoration. In that
    712   // case, we compute the start of the comment pragma manually.
    713   StringRef IndentContent = Content[LineIndex];
    714   if (Lines[LineIndex].ltrim(Blanks).startswith("*")) {
    715     IndentContent = Lines[LineIndex].ltrim(Blanks).substr(1);
    716   }
    717   return LineIndex > 0 && !CommentPragmasRegex.match(IndentContent) &&
    718          mayReflowContent(Content[LineIndex]) && !Tok.Finalized &&
    719          !switchesFormatting(tokenAt(LineIndex));
    720 }
    721 
    722 BreakableLineCommentSection::BreakableLineCommentSection(
    723     const FormatToken &Token, unsigned StartColumn,
    724     unsigned OriginalStartColumn, bool FirstInLine, bool InPPDirective,
    725     encoding::Encoding Encoding, const FormatStyle &Style)
    726     : BreakableComment(Token, StartColumn, InPPDirective, Encoding, Style) {
    727   assert(Tok.is(TT_LineComment) &&
    728          "line comment section must start with a line comment");
    729   FormatToken *LineTok = nullptr;
    730   for (const FormatToken *CurrentTok = &Tok;
    731        CurrentTok && CurrentTok->is(TT_LineComment);
    732        CurrentTok = CurrentTok->Next) {
    733     LastLineTok = LineTok;
    734     StringRef TokenText(CurrentTok->TokenText);
    735     assert((TokenText.startswith("//") || TokenText.startswith("#")) &&
    736            "unsupported line comment prefix, '//' and '#' are supported");
    737     size_t FirstLineIndex = Lines.size();
    738     TokenText.split(Lines, "\n");
    739     Content.resize(Lines.size());
    740     ContentColumn.resize(Lines.size());
    741     OriginalContentColumn.resize(Lines.size());
    742     Tokens.resize(Lines.size());
    743     Prefix.resize(Lines.size());
    744     OriginalPrefix.resize(Lines.size());
    745     for (size_t i = FirstLineIndex, e = Lines.size(); i < e; ++i) {
    746       Lines[i] = Lines[i].ltrim(Blanks);
    747       // We need to trim the blanks in case this is not the first line in a
    748       // multiline comment. Then the indent is included in Lines[i].
    749       StringRef IndentPrefix =
    750           getLineCommentIndentPrefix(Lines[i].ltrim(Blanks), Style);
    751       assert((TokenText.startswith("//") || TokenText.startswith("#")) &&
    752              "unsupported line comment prefix, '//' and '#' are supported");
    753       OriginalPrefix[i] = Prefix[i] = IndentPrefix;
    754       if (Lines[i].size() > Prefix[i].size() &&
    755           isAlphanumeric(Lines[i][Prefix[i].size()])) {
    756         if (Prefix[i] == "//")
    757           Prefix[i] = "// ";
    758         else if (Prefix[i] == "///")
    759           Prefix[i] = "/// ";
    760         else if (Prefix[i] == "//!")
    761           Prefix[i] = "//! ";
    762         else if (Prefix[i] == "///<")
    763           Prefix[i] = "///< ";
    764         else if (Prefix[i] == "//!<")
    765           Prefix[i] = "//!< ";
    766         else if (Prefix[i] == "#" &&
    767                  Style.Language == FormatStyle::LK_TextProto)
    768           Prefix[i] = "# ";
    769       }
    770 
    771       Tokens[i] = LineTok;
    772       Content[i] = Lines[i].substr(IndentPrefix.size());
    773       OriginalContentColumn[i] =
    774           StartColumn + encoding::columnWidthWithTabs(OriginalPrefix[i],
    775                                                       StartColumn,
    776                                                       Style.TabWidth, Encoding);
    777       ContentColumn[i] =
    778           StartColumn + encoding::columnWidthWithTabs(Prefix[i], StartColumn,
    779                                                       Style.TabWidth, Encoding);
    780 
    781       // Calculate the end of the non-whitespace text in this line.
    782       size_t EndOfLine = Content[i].find_last_not_of(Blanks);
    783       if (EndOfLine == StringRef::npos)
    784         EndOfLine = Content[i].size();
    785       else
    786         ++EndOfLine;
    787       Content[i] = Content[i].substr(0, EndOfLine);
    788     }
    789     LineTok = CurrentTok->Next;
    790     if (CurrentTok->Next && !CurrentTok->Next->ContinuesLineCommentSection) {
    791       // A line comment section needs to broken by a line comment that is
    792       // preceded by at least two newlines. Note that we put this break here
    793       // instead of breaking at a previous stage during parsing, since that
    794       // would split the contents of the enum into two unwrapped lines in this
    795       // example, which is undesirable:
    796       // enum A {
    797       //   a, // comment about a
    798       //
    799       //   // comment about b
    800       //   b
    801       // };
    802       //
    803       // FIXME: Consider putting separate line comment sections as children to
    804       // the unwrapped line instead.
    805       break;
    806     }
    807   }
    808 }
    809 
    810 unsigned
    811 BreakableLineCommentSection::getRangeLength(unsigned LineIndex, unsigned Offset,
    812                                             StringRef::size_type Length,
    813                                             unsigned StartColumn) const {
    814   return encoding::columnWidthWithTabs(
    815       Content[LineIndex].substr(Offset, Length), StartColumn, Style.TabWidth,
    816       Encoding);
    817 }
    818 
    819 unsigned BreakableLineCommentSection::getContentStartColumn(unsigned LineIndex,
    820                                                             bool Break) const {
    821   if (Break)
    822     return OriginalContentColumn[LineIndex];
    823   return ContentColumn[LineIndex];
    824 }
    825 
    826 void BreakableLineCommentSection::insertBreak(
    827     unsigned LineIndex, unsigned TailOffset, Split Split,
    828     unsigned ContentIndent, WhitespaceManager &Whitespaces) const {
    829   StringRef Text = Content[LineIndex].substr(TailOffset);
    830   // Compute the offset of the split relative to the beginning of the token
    831   // text.
    832   unsigned BreakOffsetInToken =
    833       Text.data() - tokenAt(LineIndex).TokenText.data() + Split.first;
    834   unsigned CharsToRemove = Split.second;
    835   // Compute the size of the new indent, including the size of the new prefix of
    836   // the newly broken line.
    837   unsigned IndentAtLineBreak = OriginalContentColumn[LineIndex] +
    838                                Prefix[LineIndex].size() -
    839                                OriginalPrefix[LineIndex].size();
    840   assert(IndentAtLineBreak >= Prefix[LineIndex].size());
    841   Whitespaces.replaceWhitespaceInToken(
    842       tokenAt(LineIndex), BreakOffsetInToken, CharsToRemove, "",
    843       Prefix[LineIndex], InPPDirective, /*Newlines=*/1,
    844       /*Spaces=*/IndentAtLineBreak - Prefix[LineIndex].size());
    845 }
    846 
    847 BreakableComment::Split BreakableLineCommentSection::getReflowSplit(
    848     unsigned LineIndex, llvm::Regex &CommentPragmasRegex) const {
    849   if (!mayReflow(LineIndex, CommentPragmasRegex))
    850     return Split(StringRef::npos, 0);
    851 
    852   size_t Trimmed = Content[LineIndex].find_first_not_of(Blanks);
    853 
    854   // In a line comment section each line is a separate token; thus, after a
    855   // split we replace all whitespace before the current line comment token
    856   // (which does not need to be included in the split), plus the start of the
    857   // line up to where the content starts.
    858   return Split(0, Trimmed != StringRef::npos ? Trimmed : 0);
    859 }
    860 
    861 void BreakableLineCommentSection::reflow(unsigned LineIndex,
    862                                          WhitespaceManager &Whitespaces) const {
    863   if (LineIndex > 0 && Tokens[LineIndex] != Tokens[LineIndex - 1]) {
    864     // Reflow happens between tokens. Replace the whitespace between the
    865     // tokens by the empty string.
    866     Whitespaces.replaceWhitespace(
    867         *Tokens[LineIndex], /*Newlines=*/0, /*Spaces=*/0,
    868         /*StartOfTokenColumn=*/StartColumn, /*InPPDirective=*/false);
    869   } else if (LineIndex > 0) {
    870     // In case we're reflowing after the '\' in:
    871     //
    872     //   // line comment \
    873     //   // line 2
    874     //
    875     // the reflow happens inside the single comment token (it is a single line
    876     // comment with an unescaped newline).
    877     // Replace the whitespace between the '\' and '//' with the empty string.
    878     //
    879     // Offset points to after the '\' relative to start of the token.
    880     unsigned Offset = Lines[LineIndex - 1].data() +
    881                       Lines[LineIndex - 1].size() -
    882                       tokenAt(LineIndex - 1).TokenText.data();
    883     // WhitespaceLength is the number of chars between the '\' and the '//' on
    884     // the next line.
    885     unsigned WhitespaceLength =
    886         Lines[LineIndex].data() - tokenAt(LineIndex).TokenText.data() - Offset;
    887     Whitespaces.replaceWhitespaceInToken(*Tokens[LineIndex], Offset,
    888                                          /*ReplaceChars=*/WhitespaceLength,
    889                                          /*PreviousPostfix=*/"",
    890                                          /*CurrentPrefix=*/"",
    891                                          /*InPPDirective=*/false,
    892                                          /*Newlines=*/0,
    893                                          /*Spaces=*/0);
    894   }
    895   // Replace the indent and prefix of the token with the reflow prefix.
    896   unsigned Offset =
    897       Lines[LineIndex].data() - tokenAt(LineIndex).TokenText.data();
    898   unsigned WhitespaceLength =
    899       Content[LineIndex].data() - Lines[LineIndex].data();
    900   Whitespaces.replaceWhitespaceInToken(*Tokens[LineIndex], Offset,
    901                                        /*ReplaceChars=*/WhitespaceLength,
    902                                        /*PreviousPostfix=*/"",
    903                                        /*CurrentPrefix=*/ReflowPrefix,
    904                                        /*InPPDirective=*/false,
    905                                        /*Newlines=*/0,
    906                                        /*Spaces=*/0);
    907 }
    908 
    909 void BreakableLineCommentSection::adaptStartOfLine(
    910     unsigned LineIndex, WhitespaceManager &Whitespaces) const {
    911   // If this is the first line of a token, we need to inform Whitespace Manager
    912   // about it: either adapt the whitespace range preceding it, or mark it as an
    913   // untouchable token.
    914   // This happens for instance here:
    915   // // line 1 \
    916   // // line 2
    917   if (LineIndex > 0 && Tokens[LineIndex] != Tokens[LineIndex - 1]) {
    918     // This is the first line for the current token, but no reflow with the
    919     // previous token is necessary. However, we still may need to adjust the
    920     // start column. Note that ContentColumn[LineIndex] is the expected
    921     // content column after a possible update to the prefix, hence the prefix
    922     // length change is included.
    923     unsigned LineColumn =
    924         ContentColumn[LineIndex] -
    925         (Content[LineIndex].data() - Lines[LineIndex].data()) +
    926         (OriginalPrefix[LineIndex].size() - Prefix[LineIndex].size());
    927 
    928     // We always want to create a replacement instead of adding an untouchable
    929     // token, even if LineColumn is the same as the original column of the
    930     // token. This is because WhitespaceManager doesn't align trailing
    931     // comments if they are untouchable.
    932     Whitespaces.replaceWhitespace(*Tokens[LineIndex],
    933                                   /*Newlines=*/1,
    934                                   /*Spaces=*/LineColumn,
    935                                   /*StartOfTokenColumn=*/LineColumn,
    936                                   /*InPPDirective=*/false);
    937   }
    938   if (OriginalPrefix[LineIndex] != Prefix[LineIndex]) {
    939     // Adjust the prefix if necessary.
    940 
    941     // Take care of the space possibly introduced after a decoration.
    942     assert(Prefix[LineIndex] == (OriginalPrefix[LineIndex] + " ").str() &&
    943            "Expecting a line comment prefix to differ from original by at most "
    944            "a space");
    945     Whitespaces.replaceWhitespaceInToken(
    946         tokenAt(LineIndex), OriginalPrefix[LineIndex].size(), 0, "", "",
    947         /*InPPDirective=*/false, /*Newlines=*/0, /*Spaces=*/1);
    948   }
    949 }
    950 
    951 void BreakableLineCommentSection::updateNextToken(LineState &State) const {
    952   if (LastLineTok) {
    953     State.NextToken = LastLineTok->Next;
    954   }
    955 }
    956 
    957 bool BreakableLineCommentSection::mayReflow(
    958     unsigned LineIndex, llvm::Regex &CommentPragmasRegex) const {
    959   // Line comments have the indent as part of the prefix, so we need to
    960   // recompute the start of the line.
    961   StringRef IndentContent = Content[LineIndex];
    962   if (Lines[LineIndex].startswith("//")) {
    963     IndentContent = Lines[LineIndex].substr(2);
    964   }
    965   // FIXME: Decide whether we want to reflow non-regular indents:
    966   // Currently, we only reflow when the OriginalPrefix[LineIndex] matches the
    967   // OriginalPrefix[LineIndex-1]. That means we don't reflow
    968   // // text that protrudes
    969   // //    into text with different indent
    970   // We do reflow in that case in block comments.
    971   return LineIndex > 0 && !CommentPragmasRegex.match(IndentContent) &&
    972          mayReflowContent(Content[LineIndex]) && !Tok.Finalized &&
    973          !switchesFormatting(tokenAt(LineIndex)) &&
    974          OriginalPrefix[LineIndex] == OriginalPrefix[LineIndex - 1];
    975 }
    976 
    977 } // namespace format
    978 } // namespace clang
    979