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                                             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 llvm::Regex kNumberedListRegexp = 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, bool InPPDirective, encoding::Encoding Encoding,
218     const FormatStyle &Style)
219     : BreakableToken(Tok, InPPDirective, Encoding, Style),
220       StartColumn(StartColumn), Prefix(Prefix), Postfix(Postfix),
221       UnbreakableTailLength(Tok.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   static const SmallVector<StringRef, 8> kSpecialMeaningPrefixes = {
288       "@", "TODO", "FIXME", "XXX", "-# ", "- ", "+ ", "* "};
289   bool hasSpecialMeaningPrefix = false;
290   for (StringRef Prefix : kSpecialMeaningPrefixes) {
291     if (Content.startswith(Prefix)) {
292       hasSpecialMeaningPrefix = true;
293       break;
294     }
295   }
296 
297   // Numbered lists may also start with a number followed by '.'
298   // To avoid issues if a line starts with a number which is actually the end
299   // of a previous line, we only consider numbers with up to 2 digits.
300   static llvm::Regex kNumberedListRegexp = llvm::Regex("^[1-9][0-9]?\\. ");
301   hasSpecialMeaningPrefix =
302       hasSpecialMeaningPrefix || kNumberedListRegexp.match(Content);
303 
304   // Simple heuristic for what to reflow: content should contain at least two
305   // characters and either the first or second character must be
306   // non-punctuation.
307   return Content.size() >= 2 && !hasSpecialMeaningPrefix &&
308          !Content.endswith("\\") &&
309          // Note that this is UTF-8 safe, since if isPunctuation(Content[0]) is
310          // true, then the first code point must be 1 byte long.
311          (!isPunctuation(Content[0]) || !isPunctuation(Content[1]));
312 }
313 
314 BreakableBlockComment::BreakableBlockComment(
315     const FormatToken &Token, unsigned StartColumn,
316     unsigned OriginalStartColumn, bool FirstInLine, bool InPPDirective,
317     encoding::Encoding Encoding, const FormatStyle &Style)
318     : BreakableComment(Token, StartColumn, InPPDirective, Encoding, Style),
319       DelimitersOnNewline(false) {
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 getRangeLength(LineIndex, Offset, StringRef::npos, StartColumn);
501 }
502 
503 unsigned BreakableBlockComment::getContentStartColumn(unsigned LineIndex,
504                                                       bool Break) const {
505   if (Break)
506     return IndentAtLineBreak;
507   return std::max(0, ContentColumn[LineIndex]);
508 }
509 
510 void BreakableBlockComment::insertBreak(unsigned LineIndex, unsigned TailOffset,
511                                         Split Split,
512                                         WhitespaceManager &Whitespaces) const {
513   StringRef Text = Content[LineIndex].substr(TailOffset);
514   StringRef Prefix = Decoration;
515   // We need this to account for the case when we have a decoration "* " for all
516   // the lines except for the last one, where the star in "*/" acts as a
517   // decoration.
518   unsigned LocalIndentAtLineBreak = IndentAtLineBreak;
519   if (LineIndex + 1 == Lines.size() &&
520       Text.size() == Split.first + Split.second) {
521     // For the last line we need to break before "*/", but not to add "* ".
522     Prefix = "";
523     if (LocalIndentAtLineBreak >= 2)
524       LocalIndentAtLineBreak -= 2;
525   }
526   // The split offset is from the beginning of the line. Convert it to an offset
527   // from the beginning of the token text.
528   unsigned BreakOffsetInToken =
529       Text.data() - tokenAt(LineIndex).TokenText.data() + Split.first;
530   unsigned CharsToRemove = Split.second;
531   assert(LocalIndentAtLineBreak >= Prefix.size());
532   Whitespaces.replaceWhitespaceInToken(
533       tokenAt(LineIndex), BreakOffsetInToken, CharsToRemove, "", Prefix,
534       InPPDirective, /*Newlines=*/1,
535       /*Spaces=*/LocalIndentAtLineBreak - Prefix.size());
536 }
537 
538 BreakableToken::Split
539 BreakableBlockComment::getReflowSplit(unsigned LineIndex,
540                                       llvm::Regex &CommentPragmasRegex) const {
541   if (!mayReflow(LineIndex, CommentPragmasRegex))
542     return Split(StringRef::npos, 0);
543 
544   size_t Trimmed = Content[LineIndex].find_first_not_of(Blanks);
545   return Split(0, Trimmed != StringRef::npos ? Trimmed : 0);
546 }
547 
548 bool BreakableBlockComment::introducesBreakBeforeToken() const {
549   // A break is introduced when we want delimiters on newline.
550   return DelimitersOnNewline &&
551          Lines[0].substr(1).find_first_not_of(Blanks) != StringRef::npos;
552 }
553 
554 void BreakableBlockComment::reflow(unsigned LineIndex,
555                                    WhitespaceManager &Whitespaces) const {
556   StringRef TrimmedContent = Content[LineIndex].ltrim(Blanks);
557   // Here we need to reflow.
558   assert(Tokens[LineIndex - 1] == Tokens[LineIndex] &&
559          "Reflowing whitespace within a token");
560   // This is the offset of the end of the last line relative to the start of
561   // the token text in the token.
562   unsigned WhitespaceOffsetInToken = Content[LineIndex - 1].data() +
563                                      Content[LineIndex - 1].size() -
564                                      tokenAt(LineIndex).TokenText.data();
565   unsigned WhitespaceLength = TrimmedContent.data() -
566                               tokenAt(LineIndex).TokenText.data() -
567                               WhitespaceOffsetInToken;
568   Whitespaces.replaceWhitespaceInToken(
569       tokenAt(LineIndex), WhitespaceOffsetInToken,
570       /*ReplaceChars=*/WhitespaceLength, /*PreviousPostfix=*/"",
571       /*CurrentPrefix=*/ReflowPrefix, InPPDirective, /*Newlines=*/0,
572       /*Spaces=*/0);
573 }
574 
575 void BreakableBlockComment::adaptStartOfLine(
576     unsigned LineIndex, WhitespaceManager &Whitespaces) const {
577   if (LineIndex == 0) {
578     if (DelimitersOnNewline) {
579       // Since we're breaking at index 1 below, the break position and the
580       // break length are the same.
581       size_t BreakLength = Lines[0].substr(1).find_first_not_of(Blanks);
582       if (BreakLength != StringRef::npos)
583         insertBreak(LineIndex, 0, Split(1, BreakLength), Whitespaces);
584     }
585     return;
586   }
587   // Here no reflow with the previous line will happen.
588   // Fix the decoration of the line at LineIndex.
589   StringRef Prefix = Decoration;
590   if (Content[LineIndex].empty()) {
591     if (LineIndex + 1 == Lines.size()) {
592       if (!LastLineNeedsDecoration) {
593         // If the last line was empty, we don't need a prefix, as the */ will
594         // line up with the decoration (if it exists).
595         Prefix = "";
596       }
597     } else if (!Decoration.empty()) {
598       // For other empty lines, if we do have a decoration, adapt it to not
599       // contain a trailing whitespace.
600       Prefix = Prefix.substr(0, 1);
601     }
602   } else {
603     if (ContentColumn[LineIndex] == 1) {
604       // This line starts immediately after the decorating *.
605       Prefix = Prefix.substr(0, 1);
606     }
607   }
608   // This is the offset of the end of the last line relative to the start of the
609   // token text in the token.
610   unsigned WhitespaceOffsetInToken = Content[LineIndex - 1].data() +
611                                      Content[LineIndex - 1].size() -
612                                      tokenAt(LineIndex).TokenText.data();
613   unsigned WhitespaceLength = Content[LineIndex].data() -
614                               tokenAt(LineIndex).TokenText.data() -
615                               WhitespaceOffsetInToken;
616   Whitespaces.replaceWhitespaceInToken(
617       tokenAt(LineIndex), WhitespaceOffsetInToken, WhitespaceLength, "", Prefix,
618       InPPDirective, /*Newlines=*/1, ContentColumn[LineIndex] - Prefix.size());
619 }
620 
621 BreakableToken::Split
622 BreakableBlockComment::getSplitAfterLastLine(unsigned TailOffset) const {
623   if (DelimitersOnNewline) {
624     // Replace the trailing whitespace of the last line with a newline.
625     // In case the last line is empty, the ending '*/' is already on its own
626     // line.
627     StringRef Line = Content.back().substr(TailOffset);
628     StringRef TrimmedLine = Line.rtrim(Blanks);
629     if (!TrimmedLine.empty())
630       return Split(TrimmedLine.size(), Line.size() - TrimmedLine.size());
631   }
632   return Split(StringRef::npos, 0);
633 }
634 
635 bool BreakableBlockComment::mayReflow(unsigned LineIndex,
636                                       llvm::Regex &CommentPragmasRegex) const {
637   // Content[LineIndex] may exclude the indent after the '*' decoration. In that
638   // case, we compute the start of the comment pragma manually.
639   StringRef IndentContent = Content[LineIndex];
640   if (Lines[LineIndex].ltrim(Blanks).startswith("*")) {
641     IndentContent = Lines[LineIndex].ltrim(Blanks).substr(1);
642   }
643   return LineIndex > 0 && !CommentPragmasRegex.match(IndentContent) &&
644          mayReflowContent(Content[LineIndex]) && !Tok.Finalized &&
645          !switchesFormatting(tokenAt(LineIndex));
646 }
647 
648 BreakableLineCommentSection::BreakableLineCommentSection(
649     const FormatToken &Token, unsigned StartColumn,
650     unsigned OriginalStartColumn, bool FirstInLine, bool InPPDirective,
651     encoding::Encoding Encoding, const FormatStyle &Style)
652     : BreakableComment(Token, StartColumn, InPPDirective, Encoding, Style) {
653   assert(Tok.is(TT_LineComment) &&
654          "line comment section must start with a line comment");
655   FormatToken *LineTok = nullptr;
656   for (const FormatToken *CurrentTok = &Tok;
657        CurrentTok && CurrentTok->is(TT_LineComment);
658        CurrentTok = CurrentTok->Next) {
659     LastLineTok = LineTok;
660     StringRef TokenText(CurrentTok->TokenText);
661     assert((TokenText.startswith("//") || TokenText.startswith("#")) &&
662            "unsupported line comment prefix, '//' and '#' are supported");
663     size_t FirstLineIndex = Lines.size();
664     TokenText.split(Lines, "\n");
665     Content.resize(Lines.size());
666     ContentColumn.resize(Lines.size());
667     OriginalContentColumn.resize(Lines.size());
668     Tokens.resize(Lines.size());
669     Prefix.resize(Lines.size());
670     OriginalPrefix.resize(Lines.size());
671     for (size_t i = FirstLineIndex, e = Lines.size(); i < e; ++i) {
672       Lines[i] = Lines[i].ltrim(Blanks);
673       // We need to trim the blanks in case this is not the first line in a
674       // multiline comment. Then the indent is included in Lines[i].
675       StringRef IndentPrefix =
676           getLineCommentIndentPrefix(Lines[i].ltrim(Blanks), Style);
677       assert((TokenText.startswith("//") || TokenText.startswith("#")) &&
678              "unsupported line comment prefix, '//' and '#' are supported");
679       OriginalPrefix[i] = Prefix[i] = IndentPrefix;
680       if (Lines[i].size() > Prefix[i].size() &&
681           isAlphanumeric(Lines[i][Prefix[i].size()])) {
682         if (Prefix[i] == "//")
683           Prefix[i] = "// ";
684         else if (Prefix[i] == "///")
685           Prefix[i] = "/// ";
686         else if (Prefix[i] == "//!")
687           Prefix[i] = "//! ";
688         else if (Prefix[i] == "///<")
689           Prefix[i] = "///< ";
690         else if (Prefix[i] == "//!<")
691           Prefix[i] = "//!< ";
692         else if (Prefix[i] == "#" &&
693                  Style.Language == FormatStyle::LK_TextProto)
694           Prefix[i] = "# ";
695       }
696 
697       Tokens[i] = LineTok;
698       Content[i] = Lines[i].substr(IndentPrefix.size());
699       OriginalContentColumn[i] =
700           StartColumn + encoding::columnWidthWithTabs(OriginalPrefix[i],
701                                                       StartColumn,
702                                                       Style.TabWidth, Encoding);
703       ContentColumn[i] =
704           StartColumn + encoding::columnWidthWithTabs(Prefix[i], StartColumn,
705                                                       Style.TabWidth, Encoding);
706 
707       // Calculate the end of the non-whitespace text in this line.
708       size_t EndOfLine = Content[i].find_last_not_of(Blanks);
709       if (EndOfLine == StringRef::npos)
710         EndOfLine = Content[i].size();
711       else
712         ++EndOfLine;
713       Content[i] = Content[i].substr(0, EndOfLine);
714     }
715     LineTok = CurrentTok->Next;
716     if (CurrentTok->Next && !CurrentTok->Next->ContinuesLineCommentSection) {
717       // A line comment section needs to broken by a line comment that is
718       // preceded by at least two newlines. Note that we put this break here
719       // instead of breaking at a previous stage during parsing, since that
720       // would split the contents of the enum into two unwrapped lines in this
721       // example, which is undesirable:
722       // enum A {
723       //   a, // comment about a
724       //
725       //   // comment about b
726       //   b
727       // };
728       //
729       // FIXME: Consider putting separate line comment sections as children to
730       // the unwrapped line instead.
731       break;
732     }
733   }
734 }
735 
736 unsigned
737 BreakableLineCommentSection::getRangeLength(unsigned LineIndex, unsigned Offset,
738                                             StringRef::size_type Length,
739                                             unsigned StartColumn) const {
740   return encoding::columnWidthWithTabs(
741       Content[LineIndex].substr(Offset, Length), StartColumn, Style.TabWidth,
742       Encoding);
743 }
744 
745 unsigned BreakableLineCommentSection::getContentStartColumn(unsigned LineIndex,
746                                                             bool Break) const {
747   if (Break)
748     return OriginalContentColumn[LineIndex];
749   return ContentColumn[LineIndex];
750 }
751 
752 void BreakableLineCommentSection::insertBreak(
753     unsigned LineIndex, unsigned TailOffset, Split Split,
754     WhitespaceManager &Whitespaces) const {
755   StringRef Text = Content[LineIndex].substr(TailOffset);
756   // Compute the offset of the split relative to the beginning of the token
757   // text.
758   unsigned BreakOffsetInToken =
759       Text.data() - tokenAt(LineIndex).TokenText.data() + Split.first;
760   unsigned CharsToRemove = Split.second;
761   // Compute the size of the new indent, including the size of the new prefix of
762   // the newly broken line.
763   unsigned IndentAtLineBreak = OriginalContentColumn[LineIndex] +
764                                Prefix[LineIndex].size() -
765                                OriginalPrefix[LineIndex].size();
766   assert(IndentAtLineBreak >= Prefix[LineIndex].size());
767   Whitespaces.replaceWhitespaceInToken(
768       tokenAt(LineIndex), BreakOffsetInToken, CharsToRemove, "",
769       Prefix[LineIndex], InPPDirective, /*Newlines=*/1,
770       /*Spaces=*/IndentAtLineBreak - Prefix[LineIndex].size());
771 }
772 
773 BreakableComment::Split BreakableLineCommentSection::getReflowSplit(
774     unsigned LineIndex, llvm::Regex &CommentPragmasRegex) const {
775   if (!mayReflow(LineIndex, CommentPragmasRegex))
776     return Split(StringRef::npos, 0);
777 
778   size_t Trimmed = Content[LineIndex].find_first_not_of(Blanks);
779 
780   // In a line comment section each line is a separate token; thus, after a
781   // split we replace all whitespace before the current line comment token
782   // (which does not need to be included in the split), plus the start of the
783   // line up to where the content starts.
784   return Split(0, Trimmed != StringRef::npos ? Trimmed : 0);
785 }
786 
787 void BreakableLineCommentSection::reflow(unsigned LineIndex,
788                                          WhitespaceManager &Whitespaces) const {
789   // Reflow happens between tokens. Replace the whitespace between the
790   // tokens by the empty string.
791   Whitespaces.replaceWhitespace(
792       *Tokens[LineIndex], /*Newlines=*/0, /*Spaces=*/0,
793       /*StartOfTokenColumn=*/StartColumn, /*InPPDirective=*/false);
794   // Replace the indent and prefix of the token with the reflow prefix.
795   unsigned WhitespaceLength =
796       Content[LineIndex].data() - tokenAt(LineIndex).TokenText.data();
797   Whitespaces.replaceWhitespaceInToken(*Tokens[LineIndex],
798                                        /*Offset=*/0,
799                                        /*ReplaceChars=*/WhitespaceLength,
800                                        /*PreviousPostfix=*/"",
801                                        /*CurrentPrefix=*/ReflowPrefix,
802                                        /*InPPDirective=*/false,
803                                        /*Newlines=*/0,
804                                        /*Spaces=*/0);
805 }
806 
807 void BreakableLineCommentSection::adaptStartOfLine(
808     unsigned LineIndex, WhitespaceManager &Whitespaces) const {
809   // If this is the first line of a token, we need to inform Whitespace Manager
810   // about it: either adapt the whitespace range preceding it, or mark it as an
811   // untouchable token.
812   // This happens for instance here:
813   // // line 1 \
814   // // line 2
815   if (LineIndex > 0 && Tokens[LineIndex] != Tokens[LineIndex - 1]) {
816     // This is the first line for the current token, but no reflow with the
817     // previous token is necessary. However, we still may need to adjust the
818     // start column. Note that ContentColumn[LineIndex] is the expected
819     // content column after a possible update to the prefix, hence the prefix
820     // length change is included.
821     unsigned LineColumn =
822         ContentColumn[LineIndex] -
823         (Content[LineIndex].data() - Lines[LineIndex].data()) +
824         (OriginalPrefix[LineIndex].size() - Prefix[LineIndex].size());
825 
826     // We always want to create a replacement instead of adding an untouchable
827     // token, even if LineColumn is the same as the original column of the
828     // token. This is because WhitespaceManager doesn't align trailing
829     // comments if they are untouchable.
830     Whitespaces.replaceWhitespace(*Tokens[LineIndex],
831                                   /*Newlines=*/1,
832                                   /*Spaces=*/LineColumn,
833                                   /*StartOfTokenColumn=*/LineColumn,
834                                   /*InPPDirective=*/false);
835   }
836   if (OriginalPrefix[LineIndex] != Prefix[LineIndex]) {
837     // Adjust the prefix if necessary.
838 
839     // Take care of the space possibly introduced after a decoration.
840     assert(Prefix[LineIndex] == (OriginalPrefix[LineIndex] + " ").str() &&
841            "Expecting a line comment prefix to differ from original by at most "
842            "a space");
843     Whitespaces.replaceWhitespaceInToken(
844         tokenAt(LineIndex), OriginalPrefix[LineIndex].size(), 0, "", "",
845         /*InPPDirective=*/false, /*Newlines=*/0, /*Spaces=*/1);
846   }
847 }
848 
849 void BreakableLineCommentSection::updateNextToken(LineState &State) const {
850   if (LastLineTok) {
851     State.NextToken = LastLineTok->Next;
852   }
853 }
854 
855 bool BreakableLineCommentSection::mayReflow(
856     unsigned LineIndex, llvm::Regex &CommentPragmasRegex) const {
857   // Line comments have the indent as part of the prefix, so we need to
858   // recompute the start of the line.
859   StringRef IndentContent = Content[LineIndex];
860   if (Lines[LineIndex].startswith("//")) {
861     IndentContent = Lines[LineIndex].substr(2);
862   }
863   // FIXME: Decide whether we want to reflow non-regular indents:
864   // Currently, we only reflow when the OriginalPrefix[LineIndex] matches the
865   // OriginalPrefix[LineIndex-1]. That means we don't reflow
866   // // text that protrudes
867   // //    into text with different indent
868   // We do reflow in that case in block comments.
869   return LineIndex > 0 && !CommentPragmasRegex.match(IndentContent) &&
870          mayReflowContent(Content[LineIndex]) && !Tok.Finalized &&
871          !switchesFormatting(tokenAt(LineIndex)) &&
872          OriginalPrefix[LineIndex] == OriginalPrefix[LineIndex - 1];
873 }
874 
875 } // namespace format
876 } // namespace clang
877