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