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