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