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