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