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