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