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