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