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