Coverage Report

Created: 2020-02-15 09:57

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