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