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