Coverage Report

Created: 2022-01-18 06:27

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