Coverage Report

Created: 2021-09-21 08:58

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