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   // Some spaces are unacceptable to break on, rewind past them.
105   while (SpaceOffset != StringRef::npos) {
106     // If a line-comment ends with `\`, the next line continues the comment,
107     // whether or not it starts with `//`. This is confusing and triggers
108     // -Wcomment.
109     // Avoid introducing multiline comments by not allowing a break right
110     // after '\'.
111     if (Style.isCpp()) {
112       StringRef::size_type LastNonBlank =
113           Text.find_last_not_of(Blanks, SpaceOffset);
114       if (LastNonBlank != StringRef::npos && Text[LastNonBlank] == '\\') {
115         SpaceOffset = Text.find_last_of(Blanks, LastNonBlank);
116         continue;
117       }
118     }
119 
120     // Do not split before a number followed by a dot: this would be interpreted
121     // as a numbered list, which would prevent re-flowing in subsequent passes.
122     if (kNumberedListRegexp.match(Text.substr(SpaceOffset).ltrim(Blanks))) {
123       SpaceOffset = Text.find_last_of(Blanks, SpaceOffset);
124       continue;
125     }
126 
127     // Avoid ever breaking before a @tag or a { in JavaScript.
128     if (Style.Language == FormatStyle::LK_JavaScript &&
129         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, StringRef::npos),
257                                        StartColumn, 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 
403   Decoration = "* ";
404   if (Lines.size() == 1 && !FirstInLine) {
405     // Comments for which FirstInLine is false can start on arbitrary column,
406     // and available horizontal space can be too small to align consecutive
407     // lines with the first one.
408     // FIXME: We could, probably, align them to current indentation level, but
409     // now we just wrap them without stars.
410     Decoration = "";
411   }
412   for (size_t i = 1, e = Lines.size(); i < e && !Decoration.empty(); ++i) {
413     // If the last line is empty, the closing "*/" will have a star.
414     if (i + 1 == e && Content[i].empty())
415       break;
416     if (!Content[i].empty() && i + 1 != e && Decoration.startswith(Content[i]))
417       continue;
418     while (!Content[i].startswith(Decoration))
419       Decoration = Decoration.substr(0, Decoration.size() - 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         }
435       } else if (Decoration.empty()) {
436         // For all other lines, set the start column to 0 if they're empty, so
437         // we do not insert trailing whitespace anywhere.
438         ContentColumn[i] = 0;
439       }
440       continue;
441     }
442 
443     // The first line already excludes the star.
444     // The last line excludes the star if LastLineNeedsDecoration is false.
445     // For all other lines, adjust the line to exclude the star and
446     // (optionally) the first whitespace.
447     unsigned DecorationSize = Decoration.startswith(Content[i])
448                                   ? Content[i].size()
449                                   : Decoration.size();
450     if (DecorationSize) {
451       ContentColumn[i] = DecorationColumn + DecorationSize;
452     }
453     Content[i] = Content[i].substr(DecorationSize);
454     if (!Decoration.startswith(Content[i]))
455       IndentAtLineBreak =
456           std::min<int>(IndentAtLineBreak, std::max(0, ContentColumn[i]));
457   }
458   IndentAtLineBreak = std::max<unsigned>(IndentAtLineBreak, Decoration.size());
459 
460   // Detect a multiline jsdoc comment and set DelimitersOnNewline in that case.
461   if (Style.Language == FormatStyle::LK_JavaScript ||
462       Style.Language == FormatStyle::LK_Java) {
463     if ((Lines[0] == "*" || Lines[0].startswith("* ")) && Lines.size() > 1) {
464       // This is a multiline jsdoc comment.
465       DelimitersOnNewline = true;
466     } else if (Lines[0].startswith("* ") && Lines.size() == 1) {
467       // Detect a long single-line comment, like:
468       // /** long long long */
469       // Below, '2' is the width of '*/'.
470       unsigned EndColumn =
471           ContentColumn[0] +
472           encoding::columnWidthWithTabs(Lines[0], ContentColumn[0],
473                                         Style.TabWidth, Encoding) +
474           2;
475       DelimitersOnNewline = EndColumn > Style.ColumnLimit;
476     }
477   }
478 
479   LLVM_DEBUG({
480     llvm::dbgs() << "IndentAtLineBreak " << IndentAtLineBreak << "\n";
481     llvm::dbgs() << "DelimitersOnNewline " << DelimitersOnNewline << "\n";
482     for (size_t i = 0; i < Lines.size(); ++i) {
483       llvm::dbgs() << i << " |" << Content[i] << "| "
484                    << "CC=" << ContentColumn[i] << "| "
485                    << "IN=" << (Content[i].data() - Lines[i].data()) << "\n";
486     }
487   });
488 }
489 
490 BreakableToken::Split BreakableBlockComment::getSplit(
491     unsigned LineIndex, unsigned TailOffset, unsigned ColumnLimit,
492     unsigned ContentStartColumn, const llvm::Regex &CommentPragmasRegex) const {
493   // Don't break lines matching the comment pragmas regex.
494   if (CommentPragmasRegex.match(Content[LineIndex]))
495     return Split(StringRef::npos, 0);
496   return getCommentSplit(Content[LineIndex].substr(TailOffset),
497                          ContentStartColumn, ColumnLimit, Style.TabWidth,
498                          Encoding, Style, Decoration.endswith("*"));
499 }
500 
501 void BreakableBlockComment::adjustWhitespace(unsigned LineIndex,
502                                              int IndentDelta) {
503   // When in a preprocessor directive, the trailing backslash in a block comment
504   // is not needed, but can serve a purpose of uniformity with necessary escaped
505   // newlines outside the comment. In this case we remove it here before
506   // trimming the trailing whitespace. The backslash will be re-added later when
507   // inserting a line break.
508   size_t EndOfPreviousLine = Lines[LineIndex - 1].size();
509   if (InPPDirective && Lines[LineIndex - 1].endswith("\\"))
510     --EndOfPreviousLine;
511 
512   // Calculate the end of the non-whitespace text in the previous line.
513   EndOfPreviousLine =
514       Lines[LineIndex - 1].find_last_not_of(Blanks, EndOfPreviousLine);
515   if (EndOfPreviousLine == StringRef::npos)
516     EndOfPreviousLine = 0;
517   else
518     ++EndOfPreviousLine;
519   // Calculate the start of the non-whitespace text in the current line.
520   size_t StartOfLine = Lines[LineIndex].find_first_not_of(Blanks);
521   if (StartOfLine == StringRef::npos)
522     StartOfLine = Lines[LineIndex].size();
523 
524   StringRef Whitespace = Lines[LineIndex].substr(0, StartOfLine);
525   // Adjust Lines to only contain relevant text.
526   size_t PreviousContentOffset =
527       Content[LineIndex - 1].data() - Lines[LineIndex - 1].data();
528   Content[LineIndex - 1] = Lines[LineIndex - 1].substr(
529       PreviousContentOffset, EndOfPreviousLine - PreviousContentOffset);
530   Content[LineIndex] = Lines[LineIndex].substr(StartOfLine);
531 
532   // Adjust the start column uniformly across all lines.
533   ContentColumn[LineIndex] =
534       encoding::columnWidthWithTabs(Whitespace, 0, Style.TabWidth, Encoding) +
535       IndentDelta;
536 }
537 
538 unsigned BreakableBlockComment::getRangeLength(unsigned LineIndex,
539                                                unsigned Offset,
540                                                StringRef::size_type Length,
541                                                unsigned StartColumn) const {
542   unsigned LineLength =
543       encoding::columnWidthWithTabs(Content[LineIndex].substr(Offset, Length),
544                                     StartColumn, Style.TabWidth, Encoding);
545   // FIXME: This should go into getRemainingLength instead, but we currently
546   // break tests when putting it there. Investigate how to fix those tests.
547   // The last line gets a "*/" postfix.
548   if (LineIndex + 1 == Lines.size()) {
549     LineLength += 2;
550     // We never need a decoration when breaking just the trailing "*/" postfix.
551     // Note that checking that Length == 0 is not enough, since Length could
552     // also be StringRef::npos.
553     if (Content[LineIndex].substr(Offset, StringRef::npos).empty()) {
554       LineLength -= Decoration.size();
555     }
556   }
557   return LineLength;
558 }
559 
560 unsigned BreakableBlockComment::getRemainingLength(unsigned LineIndex,
561                                                    unsigned Offset,
562                                                    unsigned StartColumn) const {
563   return UnbreakableTailLength +
564          getRangeLength(LineIndex, Offset, StringRef::npos, StartColumn);
565 }
566 
567 unsigned BreakableBlockComment::getContentStartColumn(unsigned LineIndex,
568                                                       bool Break) const {
569   if (Break)
570     return IndentAtLineBreak;
571   return std::max(0, ContentColumn[LineIndex]);
572 }
573 
574 const llvm::StringSet<>
575     BreakableBlockComment::ContentIndentingJavadocAnnotations = {
576         "@param", "@return",     "@returns", "@throws",  "@type", "@template",
577         "@see",   "@deprecated", "@define",  "@exports", "@mods", "@private",
578 };
579 
580 unsigned BreakableBlockComment::getContentIndent(unsigned LineIndex) const {
581   if (Style.Language != FormatStyle::LK_Java &&
582       Style.Language != FormatStyle::LK_JavaScript)
583     return 0;
584   // The content at LineIndex 0 of a comment like:
585   // /** line 0 */
586   // is "* line 0", so we need to skip over the decoration in that case.
587   StringRef ContentWithNoDecoration = Content[LineIndex];
588   if (LineIndex == 0 && ContentWithNoDecoration.startswith("*")) {
589     ContentWithNoDecoration = ContentWithNoDecoration.substr(1).ltrim(Blanks);
590   }
591   StringRef FirstWord = ContentWithNoDecoration.substr(
592       0, ContentWithNoDecoration.find_first_of(Blanks));
593   if (ContentIndentingJavadocAnnotations.find(FirstWord) !=
594       ContentIndentingJavadocAnnotations.end())
595     return Style.ContinuationIndentWidth;
596   return 0;
597 }
598 
599 void BreakableBlockComment::insertBreak(unsigned LineIndex, unsigned TailOffset,
600                                         Split Split, unsigned ContentIndent,
601                                         WhitespaceManager &Whitespaces) const {
602   StringRef Text = Content[LineIndex].substr(TailOffset);
603   StringRef Prefix = Decoration;
604   // We need this to account for the case when we have a decoration "* " for all
605   // the lines except for the last one, where the star in "*/" acts as a
606   // decoration.
607   unsigned LocalIndentAtLineBreak = IndentAtLineBreak;
608   if (LineIndex + 1 == Lines.size() &&
609       Text.size() == Split.first + Split.second) {
610     // For the last line we need to break before "*/", but not to add "* ".
611     Prefix = "";
612     if (LocalIndentAtLineBreak >= 2)
613       LocalIndentAtLineBreak -= 2;
614   }
615   // The split offset is from the beginning of the line. Convert it to an offset
616   // from the beginning of the token text.
617   unsigned BreakOffsetInToken =
618       Text.data() - tokenAt(LineIndex).TokenText.data() + Split.first;
619   unsigned CharsToRemove = Split.second;
620   assert(LocalIndentAtLineBreak >= Prefix.size());
621   std::string PrefixWithTrailingIndent = std::string(Prefix);
622   PrefixWithTrailingIndent.append(ContentIndent, ' ');
623   Whitespaces.replaceWhitespaceInToken(
624       tokenAt(LineIndex), BreakOffsetInToken, CharsToRemove, "",
625       PrefixWithTrailingIndent, InPPDirective, /*Newlines=*/1,
626       /*Spaces=*/LocalIndentAtLineBreak + ContentIndent -
627           PrefixWithTrailingIndent.size());
628 }
629 
630 BreakableToken::Split BreakableBlockComment::getReflowSplit(
631     unsigned LineIndex, const llvm::Regex &CommentPragmasRegex) const {
632   if (!mayReflow(LineIndex, CommentPragmasRegex))
633     return Split(StringRef::npos, 0);
634 
635   // If we're reflowing into a line with content indent, only reflow the next
636   // line if its starting whitespace matches the content indent.
637   size_t Trimmed = Content[LineIndex].find_first_not_of(Blanks);
638   if (LineIndex) {
639     unsigned PreviousContentIndent = getContentIndent(LineIndex - 1);
640     if (PreviousContentIndent && Trimmed != StringRef::npos &&
641         Trimmed != PreviousContentIndent)
642       return Split(StringRef::npos, 0);
643   }
644 
645   return Split(0, Trimmed != StringRef::npos ? Trimmed : 0);
646 }
647 
648 bool BreakableBlockComment::introducesBreakBeforeToken() const {
649   // A break is introduced when we want delimiters on newline.
650   return DelimitersOnNewline &&
651          Lines[0].substr(1).find_first_not_of(Blanks) != StringRef::npos;
652 }
653 
654 void BreakableBlockComment::reflow(unsigned LineIndex,
655                                    WhitespaceManager &Whitespaces) const {
656   StringRef TrimmedContent = Content[LineIndex].ltrim(Blanks);
657   // Here we need to reflow.
658   assert(Tokens[LineIndex - 1] == Tokens[LineIndex] &&
659          "Reflowing whitespace within a token");
660   // This is the offset of the end of the last line relative to the start of
661   // the token text in the token.
662   unsigned WhitespaceOffsetInToken = Content[LineIndex - 1].data() +
663                                      Content[LineIndex - 1].size() -
664                                      tokenAt(LineIndex).TokenText.data();
665   unsigned WhitespaceLength = TrimmedContent.data() -
666                               tokenAt(LineIndex).TokenText.data() -
667                               WhitespaceOffsetInToken;
668   Whitespaces.replaceWhitespaceInToken(
669       tokenAt(LineIndex), WhitespaceOffsetInToken,
670       /*ReplaceChars=*/WhitespaceLength, /*PreviousPostfix=*/"",
671       /*CurrentPrefix=*/ReflowPrefix, InPPDirective, /*Newlines=*/0,
672       /*Spaces=*/0);
673 }
674 
675 void BreakableBlockComment::adaptStartOfLine(
676     unsigned LineIndex, WhitespaceManager &Whitespaces) const {
677   if (LineIndex == 0) {
678     if (DelimitersOnNewline) {
679       // Since we're breaking at index 1 below, the break position and the
680       // break length are the same.
681       // Note: this works because getCommentSplit is careful never to split at
682       // the beginning of a line.
683       size_t BreakLength = Lines[0].substr(1).find_first_not_of(Blanks);
684       if (BreakLength != StringRef::npos)
685         insertBreak(LineIndex, 0, Split(1, BreakLength), /*ContentIndent=*/0,
686                     Whitespaces);
687     }
688     return;
689   }
690   // Here no reflow with the previous line will happen.
691   // Fix the decoration of the line at LineIndex.
692   StringRef Prefix = Decoration;
693   if (Content[LineIndex].empty()) {
694     if (LineIndex + 1 == Lines.size()) {
695       if (!LastLineNeedsDecoration) {
696         // If the last line was empty, we don't need a prefix, as the */ will
697         // line up with the decoration (if it exists).
698         Prefix = "";
699       }
700     } else if (!Decoration.empty()) {
701       // For other empty lines, if we do have a decoration, adapt it to not
702       // contain a trailing whitespace.
703       Prefix = Prefix.substr(0, 1);
704     }
705   } else {
706     if (ContentColumn[LineIndex] == 1) {
707       // This line starts immediately after the decorating *.
708       Prefix = Prefix.substr(0, 1);
709     }
710   }
711   // This is the offset of the end of the last line relative to the start of the
712   // token text in the token.
713   unsigned WhitespaceOffsetInToken = Content[LineIndex - 1].data() +
714                                      Content[LineIndex - 1].size() -
715                                      tokenAt(LineIndex).TokenText.data();
716   unsigned WhitespaceLength = Content[LineIndex].data() -
717                               tokenAt(LineIndex).TokenText.data() -
718                               WhitespaceOffsetInToken;
719   Whitespaces.replaceWhitespaceInToken(
720       tokenAt(LineIndex), WhitespaceOffsetInToken, WhitespaceLength, "", Prefix,
721       InPPDirective, /*Newlines=*/1, ContentColumn[LineIndex] - Prefix.size());
722 }
723 
724 BreakableToken::Split
725 BreakableBlockComment::getSplitAfterLastLine(unsigned TailOffset) const {
726   if (DelimitersOnNewline) {
727     // Replace the trailing whitespace of the last line with a newline.
728     // In case the last line is empty, the ending '*/' is already on its own
729     // line.
730     StringRef Line = Content.back().substr(TailOffset);
731     StringRef TrimmedLine = Line.rtrim(Blanks);
732     if (!TrimmedLine.empty())
733       return Split(TrimmedLine.size(), Line.size() - TrimmedLine.size());
734   }
735   return Split(StringRef::npos, 0);
736 }
737 
738 bool BreakableBlockComment::mayReflow(
739     unsigned LineIndex, const llvm::Regex &CommentPragmasRegex) const {
740   // Content[LineIndex] may exclude the indent after the '*' decoration. In that
741   // case, we compute the start of the comment pragma manually.
742   StringRef IndentContent = Content[LineIndex];
743   if (Lines[LineIndex].ltrim(Blanks).startswith("*")) {
744     IndentContent = Lines[LineIndex].ltrim(Blanks).substr(1);
745   }
746   return LineIndex > 0 && !CommentPragmasRegex.match(IndentContent) &&
747          mayReflowContent(Content[LineIndex]) && !Tok.Finalized &&
748          !switchesFormatting(tokenAt(LineIndex));
749 }
750 
751 BreakableLineCommentSection::BreakableLineCommentSection(
752     const FormatToken &Token, unsigned StartColumn,
753     unsigned OriginalStartColumn, bool FirstInLine, bool InPPDirective,
754     encoding::Encoding Encoding, const FormatStyle &Style)
755     : BreakableComment(Token, StartColumn, InPPDirective, Encoding, Style) {
756   assert(Tok.is(TT_LineComment) &&
757          "line comment section must start with a line comment");
758   FormatToken *LineTok = nullptr;
759   for (const FormatToken *CurrentTok = &Tok;
760        CurrentTok && CurrentTok->is(TT_LineComment);
761        CurrentTok = CurrentTok->Next) {
762     LastLineTok = LineTok;
763     StringRef TokenText(CurrentTok->TokenText);
764     assert((TokenText.startswith("//") || TokenText.startswith("#")) &&
765            "unsupported line comment prefix, '//' and '#' are supported");
766     size_t FirstLineIndex = Lines.size();
767     TokenText.split(Lines, "\n");
768     Content.resize(Lines.size());
769     ContentColumn.resize(Lines.size());
770     OriginalContentColumn.resize(Lines.size());
771     Tokens.resize(Lines.size());
772     Prefix.resize(Lines.size());
773     OriginalPrefix.resize(Lines.size());
774     for (size_t i = FirstLineIndex, e = Lines.size(); i < e; ++i) {
775       Lines[i] = Lines[i].ltrim(Blanks);
776       StringRef IndentPrefix = getLineCommentIndentPrefix(Lines[i], Style);
777       assert((TokenText.startswith("//") || TokenText.startswith("#")) &&
778              "unsupported line comment prefix, '//' and '#' are supported");
779       OriginalPrefix[i] = Prefix[i] = IndentPrefix;
780       if (Lines[i].size() > Prefix[i].size() &&
781           isAlphanumeric(Lines[i][Prefix[i].size()])) {
782         if (Prefix[i] == "//")
783           Prefix[i] = "// ";
784         else if (Prefix[i] == "///")
785           Prefix[i] = "/// ";
786         else if (Prefix[i] == "//!")
787           Prefix[i] = "//! ";
788         else if (Prefix[i] == "///<")
789           Prefix[i] = "///< ";
790         else if (Prefix[i] == "//!<")
791           Prefix[i] = "//!< ";
792         else if (Prefix[i] == "#")
793           Prefix[i] = "# ";
794         else if (Prefix[i] == "##")
795           Prefix[i] = "## ";
796         else if (Prefix[i] == "###")
797           Prefix[i] = "### ";
798         else if (Prefix[i] == "####")
799           Prefix[i] = "#### ";
800       }
801 
802       Tokens[i] = LineTok;
803       Content[i] = Lines[i].substr(IndentPrefix.size());
804       OriginalContentColumn[i] =
805           StartColumn + encoding::columnWidthWithTabs(OriginalPrefix[i],
806                                                       StartColumn,
807                                                       Style.TabWidth, Encoding);
808       ContentColumn[i] =
809           StartColumn + encoding::columnWidthWithTabs(Prefix[i], StartColumn,
810                                                       Style.TabWidth, Encoding);
811 
812       // Calculate the end of the non-whitespace text in this line.
813       size_t EndOfLine = Content[i].find_last_not_of(Blanks);
814       if (EndOfLine == StringRef::npos)
815         EndOfLine = Content[i].size();
816       else
817         ++EndOfLine;
818       Content[i] = Content[i].substr(0, EndOfLine);
819     }
820     LineTok = CurrentTok->Next;
821     if (CurrentTok->Next && !CurrentTok->Next->ContinuesLineCommentSection) {
822       // A line comment section needs to broken by a line comment that is
823       // preceded by at least two newlines. Note that we put this break here
824       // instead of breaking at a previous stage during parsing, since that
825       // would split the contents of the enum into two unwrapped lines in this
826       // example, which is undesirable:
827       // enum A {
828       //   a, // comment about a
829       //
830       //   // comment about b
831       //   b
832       // };
833       //
834       // FIXME: Consider putting separate line comment sections as children to
835       // the unwrapped line instead.
836       break;
837     }
838   }
839 }
840 
841 unsigned
842 BreakableLineCommentSection::getRangeLength(unsigned LineIndex, unsigned Offset,
843                                             StringRef::size_type Length,
844                                             unsigned StartColumn) const {
845   return encoding::columnWidthWithTabs(
846       Content[LineIndex].substr(Offset, Length), StartColumn, Style.TabWidth,
847       Encoding);
848 }
849 
850 unsigned BreakableLineCommentSection::getContentStartColumn(unsigned LineIndex,
851                                                             bool Break) const {
852   if (Break)
853     return OriginalContentColumn[LineIndex];
854   return ContentColumn[LineIndex];
855 }
856 
857 void BreakableLineCommentSection::insertBreak(
858     unsigned LineIndex, unsigned TailOffset, Split Split,
859     unsigned ContentIndent, WhitespaceManager &Whitespaces) const {
860   StringRef Text = Content[LineIndex].substr(TailOffset);
861   // Compute the offset of the split relative to the beginning of the token
862   // text.
863   unsigned BreakOffsetInToken =
864       Text.data() - tokenAt(LineIndex).TokenText.data() + Split.first;
865   unsigned CharsToRemove = Split.second;
866   // Compute the size of the new indent, including the size of the new prefix of
867   // the newly broken line.
868   unsigned IndentAtLineBreak = OriginalContentColumn[LineIndex] +
869                                Prefix[LineIndex].size() -
870                                OriginalPrefix[LineIndex].size();
871   assert(IndentAtLineBreak >= Prefix[LineIndex].size());
872   Whitespaces.replaceWhitespaceInToken(
873       tokenAt(LineIndex), BreakOffsetInToken, CharsToRemove, "",
874       Prefix[LineIndex], InPPDirective, /*Newlines=*/1,
875       /*Spaces=*/IndentAtLineBreak - Prefix[LineIndex].size());
876 }
877 
878 BreakableComment::Split BreakableLineCommentSection::getReflowSplit(
879     unsigned LineIndex, const llvm::Regex &CommentPragmasRegex) const {
880   if (!mayReflow(LineIndex, CommentPragmasRegex))
881     return Split(StringRef::npos, 0);
882 
883   size_t Trimmed = Content[LineIndex].find_first_not_of(Blanks);
884 
885   // In a line comment section each line is a separate token; thus, after a
886   // split we replace all whitespace before the current line comment token
887   // (which does not need to be included in the split), plus the start of the
888   // line up to where the content starts.
889   return Split(0, Trimmed != StringRef::npos ? Trimmed : 0);
890 }
891 
892 void BreakableLineCommentSection::reflow(unsigned LineIndex,
893                                          WhitespaceManager &Whitespaces) const {
894   if (LineIndex > 0 && Tokens[LineIndex] != Tokens[LineIndex - 1]) {
895     // Reflow happens between tokens. Replace the whitespace between the
896     // tokens by the empty string.
897     Whitespaces.replaceWhitespace(
898         *Tokens[LineIndex], /*Newlines=*/0, /*Spaces=*/0,
899         /*StartOfTokenColumn=*/StartColumn, /*IsAligned=*/true,
900         /*InPPDirective=*/false);
901   } else if (LineIndex > 0) {
902     // In case we're reflowing after the '\' in:
903     //
904     //   // line comment \
905     //   // line 2
906     //
907     // the reflow happens inside the single comment token (it is a single line
908     // comment with an unescaped newline).
909     // Replace the whitespace between the '\' and '//' with the empty string.
910     //
911     // Offset points to after the '\' relative to start of the token.
912     unsigned Offset = Lines[LineIndex - 1].data() +
913                       Lines[LineIndex - 1].size() -
914                       tokenAt(LineIndex - 1).TokenText.data();
915     // WhitespaceLength is the number of chars between the '\' and the '//' on
916     // the next line.
917     unsigned WhitespaceLength =
918         Lines[LineIndex].data() - tokenAt(LineIndex).TokenText.data() - Offset;
919     Whitespaces.replaceWhitespaceInToken(*Tokens[LineIndex], Offset,
920                                          /*ReplaceChars=*/WhitespaceLength,
921                                          /*PreviousPostfix=*/"",
922                                          /*CurrentPrefix=*/"",
923                                          /*InPPDirective=*/false,
924                                          /*Newlines=*/0,
925                                          /*Spaces=*/0);
926   }
927   // Replace the indent and prefix of the token with the reflow prefix.
928   unsigned Offset =
929       Lines[LineIndex].data() - tokenAt(LineIndex).TokenText.data();
930   unsigned WhitespaceLength =
931       Content[LineIndex].data() - Lines[LineIndex].data();
932   Whitespaces.replaceWhitespaceInToken(*Tokens[LineIndex], Offset,
933                                        /*ReplaceChars=*/WhitespaceLength,
934                                        /*PreviousPostfix=*/"",
935                                        /*CurrentPrefix=*/ReflowPrefix,
936                                        /*InPPDirective=*/false,
937                                        /*Newlines=*/0,
938                                        /*Spaces=*/0);
939 }
940 
941 void BreakableLineCommentSection::adaptStartOfLine(
942     unsigned LineIndex, WhitespaceManager &Whitespaces) const {
943   // If this is the first line of a token, we need to inform Whitespace Manager
944   // about it: either adapt the whitespace range preceding it, or mark it as an
945   // untouchable token.
946   // This happens for instance here:
947   // // line 1 \
948   // // line 2
949   if (LineIndex > 0 && Tokens[LineIndex] != Tokens[LineIndex - 1]) {
950     // This is the first line for the current token, but no reflow with the
951     // previous token is necessary. However, we still may need to adjust the
952     // start column. Note that ContentColumn[LineIndex] is the expected
953     // content column after a possible update to the prefix, hence the prefix
954     // length change is included.
955     unsigned LineColumn =
956         ContentColumn[LineIndex] -
957         (Content[LineIndex].data() - Lines[LineIndex].data()) +
958         (OriginalPrefix[LineIndex].size() - Prefix[LineIndex].size());
959 
960     // We always want to create a replacement instead of adding an untouchable
961     // token, even if LineColumn is the same as the original column of the
962     // token. This is because WhitespaceManager doesn't align trailing
963     // comments if they are untouchable.
964     Whitespaces.replaceWhitespace(*Tokens[LineIndex],
965                                   /*Newlines=*/1,
966                                   /*Spaces=*/LineColumn,
967                                   /*StartOfTokenColumn=*/LineColumn,
968                                   /*IsAligned=*/true,
969                                   /*InPPDirective=*/false);
970   }
971   if (OriginalPrefix[LineIndex] != Prefix[LineIndex]) {
972     // Adjust the prefix if necessary.
973 
974     // Take care of the space possibly introduced after a decoration.
975     assert(Prefix[LineIndex] == (OriginalPrefix[LineIndex] + " ").str() &&
976            "Expecting a line comment prefix to differ from original by at most "
977            "a space");
978     Whitespaces.replaceWhitespaceInToken(
979         tokenAt(LineIndex), OriginalPrefix[LineIndex].size(), 0, "", "",
980         /*InPPDirective=*/false, /*Newlines=*/0, /*Spaces=*/1);
981   }
982 }
983 
984 void BreakableLineCommentSection::updateNextToken(LineState &State) const {
985   if (LastLineTok) {
986     State.NextToken = LastLineTok->Next;
987   }
988 }
989 
990 bool BreakableLineCommentSection::mayReflow(
991     unsigned LineIndex, const llvm::Regex &CommentPragmasRegex) const {
992   // Line comments have the indent as part of the prefix, so we need to
993   // recompute the start of the line.
994   StringRef IndentContent = Content[LineIndex];
995   if (Lines[LineIndex].startswith("//")) {
996     IndentContent = Lines[LineIndex].substr(2);
997   }
998   // FIXME: Decide whether we want to reflow non-regular indents:
999   // Currently, we only reflow when the OriginalPrefix[LineIndex] matches the
1000   // OriginalPrefix[LineIndex-1]. That means we don't reflow
1001   // // text that protrudes
1002   // //    into text with different indent
1003   // We do reflow in that case in block comments.
1004   return LineIndex > 0 && !CommentPragmasRegex.match(IndentContent) &&
1005          mayReflowContent(Content[LineIndex]) && !Tok.Finalized &&
1006          !switchesFormatting(tokenAt(LineIndex)) &&
1007          OriginalPrefix[LineIndex] == OriginalPrefix[LineIndex - 1];
1008 }
1009 
1010 } // namespace format
1011 } // namespace clang
1012