clang  16.0.0git
BreakableToken.cpp
Go to the documentation of this file.
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 static bool IsBlank(char C) {
30  switch (C) {
31  case ' ':
32  case '\t':
33  case '\v':
34  case '\f':
35  case '\r':
36  return true;
37  default:
38  return false;
39  }
40 }
41 
42 static StringRef getLineCommentIndentPrefix(StringRef Comment,
43  const FormatStyle &Style) {
44  static constexpr StringRef KnownCStylePrefixes[] = {"///<", "//!<", "///",
45  "//!", "//:", "//"};
46  static constexpr StringRef KnownTextProtoPrefixes[] = {"####", "###", "##",
47  "//", "#"};
48  ArrayRef<StringRef> KnownPrefixes(KnownCStylePrefixes);
50  KnownPrefixes = KnownTextProtoPrefixes;
51 
52  assert(
53  llvm::is_sorted(KnownPrefixes, [](StringRef Lhs, StringRef Rhs) noexcept {
54  return Lhs.size() > Rhs.size();
55  }));
56 
57  for (StringRef KnownPrefix : KnownPrefixes) {
58  if (Comment.startswith(KnownPrefix)) {
59  const auto PrefixLength =
60  Comment.find_first_not_of(' ', KnownPrefix.size());
61  return Comment.substr(0, PrefixLength);
62  }
63  }
64  return {};
65 }
66 
68 getCommentSplit(StringRef Text, unsigned ContentStartColumn,
69  unsigned ColumnLimit, unsigned TabWidth,
71  bool DecorationEndsWithStar = false) {
72  LLVM_DEBUG(llvm::dbgs() << "Comment split: \"" << Text
73  << "\", Column limit: " << ColumnLimit
74  << ", Content start: " << ContentStartColumn << "\n");
75  if (ColumnLimit <= ContentStartColumn + 1)
76  return BreakableToken::Split(StringRef::npos, 0);
77 
78  unsigned MaxSplit = ColumnLimit - ContentStartColumn + 1;
79  unsigned MaxSplitBytes = 0;
80 
81  for (unsigned NumChars = 0;
82  NumChars < MaxSplit && MaxSplitBytes < Text.size();) {
83  unsigned BytesInChar =
85  NumChars +=
86  encoding::columnWidthWithTabs(Text.substr(MaxSplitBytes, BytesInChar),
87  ContentStartColumn, TabWidth, Encoding);
88  MaxSplitBytes += BytesInChar;
89  }
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  if (Style.isJavaScript()) {
95  StringRef::size_type SpaceOffset =
96  Text.find_first_of(Blanks, MaxSplitBytes);
97  if (SpaceOffset != StringRef::npos && SpaceOffset + 1 < Text.size() &&
98  Text[SpaceOffset + 1] == '{') {
99  MaxSplitBytes = SpaceOffset + 1;
100  }
101  }
102 
103  StringRef::size_type SpaceOffset = Text.find_last_of(Blanks, MaxSplitBytes);
104 
105  static const auto kNumberedListRegexp = llvm::Regex("^[1-9][0-9]?\\.");
106  // Some spaces are unacceptable to break on, rewind past them.
107  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  if (Style.isCpp()) {
114  StringRef::size_type LastNonBlank =
115  Text.find_last_not_of(Blanks, SpaceOffset);
116  if (LastNonBlank != StringRef::npos && Text[LastNonBlank] == '\\') {
117  SpaceOffset = Text.find_last_of(Blanks, LastNonBlank);
118  continue;
119  }
120  }
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  if (kNumberedListRegexp.match(Text.substr(SpaceOffset).ltrim(Blanks))) {
125  SpaceOffset = Text.find_last_of(Blanks, SpaceOffset);
126  continue;
127  }
128 
129  // Avoid ever breaking before a @tag or a { in JavaScript.
130  if (Style.isJavaScript() && SpaceOffset + 1 < Text.size() &&
131  (Text[SpaceOffset + 1] == '{' || Text[SpaceOffset + 1] == '@')) {
132  SpaceOffset = Text.find_last_of(Blanks, SpaceOffset);
133  continue;
134  }
135 
136  break;
137  }
138 
139  if (SpaceOffset == StringRef::npos ||
140  // Don't break at leading whitespace.
141  Text.find_last_not_of(Blanks, SpaceOffset) == StringRef::npos) {
142  // Make sure that we don't break at leading whitespace that
143  // reaches past MaxSplit.
144  StringRef::size_type FirstNonWhitespace = Text.find_first_not_of(Blanks);
145  if (FirstNonWhitespace == StringRef::npos) {
146  // If the comment is only whitespace, we cannot split.
147  return BreakableToken::Split(StringRef::npos, 0);
148  }
149  SpaceOffset = Text.find_first_of(
150  Blanks, std::max<unsigned>(MaxSplitBytes, FirstNonWhitespace));
151  }
152  if (SpaceOffset != StringRef::npos && SpaceOffset != 0) {
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  if (SpaceOffset == 1 && Text[SpaceOffset - 1] == '*')
158  return BreakableToken::Split(StringRef::npos, 0);
159  StringRef BeforeCut = Text.substr(0, SpaceOffset).rtrim(Blanks);
160  StringRef AfterCut = Text.substr(SpaceOffset);
161  // Don't trim the leading blanks if it would create a */ after the break.
162  if (!DecorationEndsWithStar || AfterCut.size() <= 1 || AfterCut[1] != '/')
163  AfterCut = AfterCut.ltrim(Blanks);
164  return BreakableToken::Split(BeforeCut.size(),
165  AfterCut.begin() - BeforeCut.end());
166  }
167  return BreakableToken::Split(StringRef::npos, 0);
168 }
169 
171 getStringSplit(StringRef Text, unsigned UsedColumns, unsigned ColumnLimit,
172  unsigned TabWidth, encoding::Encoding Encoding) {
173  // FIXME: Reduce unit test case.
174  if (Text.empty())
175  return BreakableToken::Split(StringRef::npos, 0);
176  if (ColumnLimit <= UsedColumns)
177  return BreakableToken::Split(StringRef::npos, 0);
178  unsigned MaxSplit = ColumnLimit - UsedColumns;
179  StringRef::size_type SpaceOffset = 0;
180  StringRef::size_type SlashOffset = 0;
181  StringRef::size_type WordStartOffset = 0;
182  StringRef::size_type SplitPoint = 0;
183  for (unsigned Chars = 0;;) {
184  unsigned Advance;
185  if (Text[0] == '\\') {
187  Chars += Advance;
188  } else {
191  Text.substr(0, Advance), UsedColumns + Chars, TabWidth, Encoding);
192  }
193 
194  if (Chars > MaxSplit || Text.size() <= Advance)
195  break;
196 
197  if (IsBlank(Text[0]))
198  SpaceOffset = SplitPoint;
199  if (Text[0] == '/')
200  SlashOffset = SplitPoint;
201  if (Advance == 1 && !isAlphanumeric(Text[0]))
202  WordStartOffset = SplitPoint;
203 
204  SplitPoint += Advance;
205  Text = Text.substr(Advance);
206  }
207 
208  if (SpaceOffset != 0)
209  return BreakableToken::Split(SpaceOffset + 1, 0);
210  if (SlashOffset != 0)
211  return BreakableToken::Split(SlashOffset + 1, 0);
212  if (WordStartOffset != 0)
213  return BreakableToken::Split(WordStartOffset + 1, 0);
214  if (SplitPoint != 0)
215  return BreakableToken::Split(SplitPoint, 0);
216  return BreakableToken::Split(StringRef::npos, 0);
217 }
218 
220  assert((Token.is(TT_BlockComment) || Token.is(TT_LineComment)) &&
221  "formatting regions are switched by comment tokens");
222  StringRef Content = Token.TokenText.substr(2).ltrim();
223  return Content.startswith("clang-format on") ||
224  Content.startswith("clang-format off");
225 }
226 
227 unsigned
228 BreakableToken::getLengthAfterCompression(unsigned RemainingTokenColumns,
229  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  return RemainingTokenColumns + 1 - Split.second;
242 }
243 
244 unsigned BreakableStringLiteral::getLineCount() const { return 1; }
245 
246 unsigned BreakableStringLiteral::getRangeLength(unsigned LineIndex,
247  unsigned Offset,
248  StringRef::size_type Length,
249  unsigned StartColumn) const {
250  llvm_unreachable("Getting the length of a part of the string literal "
251  "indicates that the code tries to reflow it.");
252 }
253 
254 unsigned
256  unsigned StartColumn) const {
257  return UnbreakableTailLength + Postfix.size() +
260 }
261 
263  bool Break) const {
264  return StartColumn + Prefix.size();
265 }
266 
268  const FormatToken &Tok, unsigned StartColumn, StringRef Prefix,
269  StringRef Postfix, unsigned UnbreakableTailLength, bool InPPDirective,
271  : BreakableToken(Tok, InPPDirective, Encoding, Style),
272  StartColumn(StartColumn), Prefix(Prefix), Postfix(Postfix),
273  UnbreakableTailLength(UnbreakableTailLength) {
274  assert(Tok.TokenText.startswith(Prefix) && Tok.TokenText.endswith(Postfix));
275  Line = Tok.TokenText.substr(
276  Prefix.size(), Tok.TokenText.size() - Prefix.size() - Postfix.size());
277 }
278 
280  unsigned LineIndex, unsigned TailOffset, unsigned ColumnLimit,
281  unsigned ContentStartColumn, const llvm::Regex &CommentPragmasRegex) const {
282  return getStringSplit(Line.substr(TailOffset), ContentStartColumn,
283  ColumnLimit - Postfix.size(), Style.TabWidth, Encoding);
284 }
285 
286 void BreakableStringLiteral::insertBreak(unsigned LineIndex,
287  unsigned TailOffset, Split Split,
288  unsigned ContentIndent,
289  WhitespaceManager &Whitespaces) const {
290  Whitespaces.replaceWhitespaceInToken(
291  Tok, Prefix.size() + TailOffset + Split.first, Split.second, Postfix,
293 }
294 
296  unsigned StartColumn, bool InPPDirective,
298  const FormatStyle &Style)
299  : BreakableToken(Token, InPPDirective, Encoding, Style),
300  StartColumn(StartColumn) {}
301 
302 unsigned BreakableComment::getLineCount() const { return Lines.size(); }
303 
305 BreakableComment::getSplit(unsigned LineIndex, unsigned TailOffset,
306  unsigned ColumnLimit, unsigned ContentStartColumn,
307  const llvm::Regex &CommentPragmasRegex) const {
308  // Don't break lines matching the comment pragmas regex.
309  if (CommentPragmasRegex.match(Content[LineIndex]))
310  return Split(StringRef::npos, 0);
311  return getCommentSplit(Content[LineIndex].substr(TailOffset),
312  ContentStartColumn, ColumnLimit, Style.TabWidth,
313  Encoding, Style);
314 }
315 
317  unsigned LineIndex, unsigned TailOffset, Split Split,
318  WhitespaceManager &Whitespaces) const {
319  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  unsigned BreakOffsetInToken =
325  Text.data() - tokenAt(LineIndex).TokenText.data() + Split.first;
326  unsigned CharsToRemove = Split.second;
327  Whitespaces.replaceWhitespaceInToken(
328  tokenAt(LineIndex), BreakOffsetInToken, CharsToRemove, "", "",
329  /*InPPDirective=*/false, /*Newlines=*/0, /*Spaces=*/1);
330 }
331 
332 const FormatToken &BreakableComment::tokenAt(unsigned LineIndex) const {
333  return Tokens[LineIndex] ? *Tokens[LineIndex] : Tok;
334 }
335 
336 static bool mayReflowContent(StringRef Content) {
337  Content = Content.trim(Blanks);
338  // Lines starting with '@' commonly have special meaning.
339  // Lines starting with '-', '-#', '+' or '*' are bulleted/numbered lists.
340  bool hasSpecialMeaningPrefix = false;
341  for (StringRef Prefix :
342  {"@", "TODO", "FIXME", "XXX", "-# ", "- ", "+ ", "* "}) {
343  if (Content.startswith(Prefix)) {
344  hasSpecialMeaningPrefix = true;
345  break;
346  }
347  }
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  static const auto kNumberedListRegexp = llvm::Regex("^[1-9][0-9]?\\. ");
353  hasSpecialMeaningPrefix =
354  hasSpecialMeaningPrefix || kNumberedListRegexp.match(Content);
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  return Content.size() >= 2 && !hasSpecialMeaningPrefix &&
360  !Content.endswith("\\") &&
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  (!isPunctuation(Content[0]) || !isPunctuation(Content[1]));
364 }
365 
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  UnbreakableTailLength(Token.UnbreakableTailLength) {
373  assert(Tok.is(TT_BlockComment) &&
374  "block comment section must start with a block comment");
375 
376  StringRef TokenText(Tok.TokenText);
377  assert(TokenText.startswith("/*") && TokenText.endswith("*/"));
378  TokenText.substr(2, TokenText.size() - 4)
379  .split(Lines, UseCRLF ? "\r\n" : "\n");
380 
381  int IndentDelta = StartColumn - OriginalStartColumn;
382  Content.resize(Lines.size());
383  Content[0] = Lines[0];
384  ContentColumn.resize(Lines.size());
385  // Account for the initial '/*'.
386  ContentColumn[0] = StartColumn + 2;
387  Tokens.resize(Lines.size());
388  for (size_t i = 1; i < Lines.size(); ++i)
389  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  DecorationColumn = StartColumn + 1;
394 
395  // Account for comment decoration patterns like this:
396  //
397  // /*
398  // ** blah blah blah
399  // */
400  if (Lines.size() >= 2 && Content[1].startswith("**") &&
401  static_cast<unsigned>(ContentColumn[1]) == StartColumn) {
402  DecorationColumn = StartColumn;
403  }
404 
405  Decoration = "* ";
406  if (Lines.size() == 1 && !FirstInLine) {
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  Decoration = "";
413  }
414  for (size_t i = 1, e = Content.size(); i < e && !Decoration.empty(); ++i) {
415  const StringRef &Text = Content[i];
416  if (i + 1 == e) {
417  // If the last line is empty, the closing "*/" will have a star.
418  if (Text.empty())
419  break;
420  } else if (!Text.empty() && Decoration.startswith(Text)) {
421  continue;
422  }
423  while (!Text.startswith(Decoration))
424  Decoration = Decoration.drop_back(1);
425  }
426 
427  LastLineNeedsDecoration = true;
428  IndentAtLineBreak = ContentColumn[0] + 1;
429  for (size_t i = 1, e = Lines.size(); i < e; ++i) {
430  if (Content[i].empty()) {
431  if (i + 1 == e) {
432  // Empty last line means that we already have a star as a part of the
433  // trailing */. We also need to preserve whitespace, so that */ is
434  // correctly indented.
435  LastLineNeedsDecoration = false;
436  // Align the star in the last '*/' with the stars on the previous lines.
437  if (e >= 2 && !Decoration.empty())
438  ContentColumn[i] = DecorationColumn;
439  } else if (Decoration.empty()) {
440  // For all other lines, set the start column to 0 if they're empty, so
441  // we do not insert trailing whitespace anywhere.
442  ContentColumn[i] = 0;
443  }
444  continue;
445  }
446 
447  // The first line already excludes the star.
448  // The last line excludes the star if LastLineNeedsDecoration is false.
449  // For all other lines, adjust the line to exclude the star and
450  // (optionally) the first whitespace.
451  unsigned DecorationSize = Decoration.startswith(Content[i])
452  ? Content[i].size()
453  : Decoration.size();
454  if (DecorationSize)
455  ContentColumn[i] = DecorationColumn + DecorationSize;
456  Content[i] = Content[i].substr(DecorationSize);
457  if (!Decoration.startswith(Content[i])) {
458  IndentAtLineBreak =
459  std::min<int>(IndentAtLineBreak, std::max(0, ContentColumn[i]));
460  }
461  }
462  IndentAtLineBreak = std::max<unsigned>(IndentAtLineBreak, Decoration.size());
463 
464  // Detect a multiline jsdoc comment and set DelimitersOnNewline in that case.
466  if ((Lines[0] == "*" || Lines[0].startswith("* ")) && Lines.size() > 1) {
467  // This is a multiline jsdoc comment.
468  DelimitersOnNewline = true;
469  } else if (Lines[0].startswith("* ") && Lines.size() == 1) {
470  // Detect a long single-line comment, like:
471  // /** long long long */
472  // Below, '2' is the width of '*/'.
473  unsigned EndColumn =
474  ContentColumn[0] +
477  2;
478  DelimitersOnNewline = EndColumn > Style.ColumnLimit;
479  }
480  }
481 
482  LLVM_DEBUG({
483  llvm::dbgs() << "IndentAtLineBreak " << IndentAtLineBreak << "\n";
484  llvm::dbgs() << "DelimitersOnNewline " << DelimitersOnNewline << "\n";
485  for (size_t i = 0; i < Lines.size(); ++i) {
486  llvm::dbgs() << i << " |" << Content[i] << "| "
487  << "CC=" << ContentColumn[i] << "| "
488  << "IN=" << (Content[i].data() - Lines[i].data()) << "\n";
489  }
490  });
491 }
492 
494  unsigned LineIndex, unsigned TailOffset, unsigned ColumnLimit,
495  unsigned ContentStartColumn, const llvm::Regex &CommentPragmasRegex) const {
496  // Don't break lines matching the comment pragmas regex.
497  if (CommentPragmasRegex.match(Content[LineIndex]))
498  return Split(StringRef::npos, 0);
499  return getCommentSplit(Content[LineIndex].substr(TailOffset),
500  ContentStartColumn, ColumnLimit, Style.TabWidth,
501  Encoding, Style, Decoration.endswith("*"));
502 }
503 
504 void BreakableBlockComment::adjustWhitespace(unsigned LineIndex,
505  int IndentDelta) {
506  // When in a preprocessor directive, the trailing backslash in a block comment
507  // is not needed, but can serve a purpose of uniformity with necessary escaped
508  // newlines outside the comment. In this case we remove it here before
509  // trimming the trailing whitespace. The backslash will be re-added later when
510  // inserting a line break.
511  size_t EndOfPreviousLine = Lines[LineIndex - 1].size();
512  if (InPPDirective && Lines[LineIndex - 1].endswith("\\"))
513  --EndOfPreviousLine;
514 
515  // Calculate the end of the non-whitespace text in the previous line.
516  EndOfPreviousLine =
517  Lines[LineIndex - 1].find_last_not_of(Blanks, EndOfPreviousLine);
518  if (EndOfPreviousLine == StringRef::npos)
519  EndOfPreviousLine = 0;
520  else
521  ++EndOfPreviousLine;
522  // Calculate the start of the non-whitespace text in the current line.
523  size_t StartOfLine = Lines[LineIndex].find_first_not_of(Blanks);
524  if (StartOfLine == StringRef::npos)
525  StartOfLine = Lines[LineIndex].size();
526 
527  StringRef Whitespace = Lines[LineIndex].substr(0, StartOfLine);
528  // Adjust Lines to only contain relevant text.
529  size_t PreviousContentOffset =
530  Content[LineIndex - 1].data() - Lines[LineIndex - 1].data();
531  Content[LineIndex - 1] = Lines[LineIndex - 1].substr(
532  PreviousContentOffset, EndOfPreviousLine - PreviousContentOffset);
533  Content[LineIndex] = Lines[LineIndex].substr(StartOfLine);
534 
535  // Adjust the start column uniformly across all lines.
536  ContentColumn[LineIndex] =
538  IndentDelta;
539 }
540 
541 unsigned BreakableBlockComment::getRangeLength(unsigned LineIndex,
542  unsigned Offset,
543  StringRef::size_type Length,
544  unsigned StartColumn) const {
546  Content[LineIndex].substr(Offset, Length), StartColumn, Style.TabWidth,
547  Encoding);
548 }
549 
550 unsigned BreakableBlockComment::getRemainingLength(unsigned LineIndex,
551  unsigned Offset,
552  unsigned StartColumn) const {
553  unsigned LineLength =
554  UnbreakableTailLength +
555  getRangeLength(LineIndex, Offset, StringRef::npos, StartColumn);
556  if (LineIndex + 1 == Lines.size()) {
557  LineLength += 2;
558  // We never need a decoration when breaking just the trailing "*/" postfix.
559  bool HasRemainingText = Offset < Content[LineIndex].size();
560  if (!HasRemainingText) {
561  bool HasDecoration = Lines[LineIndex].ltrim().startswith(Decoration);
562  if (HasDecoration)
563  LineLength -= Decoration.size();
564  }
565  }
566  return LineLength;
567 }
568 
570  bool Break) const {
571  if (Break)
572  return IndentAtLineBreak;
573  return std::max(0, ContentColumn[LineIndex]);
574 }
575 
576 const llvm::StringSet<>
578  "@param", "@return", "@returns", "@throws", "@type", "@template",
579  "@see", "@deprecated", "@define", "@exports", "@mods", "@private",
580 };
581 
582 unsigned BreakableBlockComment::getContentIndent(unsigned LineIndex) const {
584  return 0;
585  // The content at LineIndex 0 of a comment like:
586  // /** line 0 */
587  // is "* line 0", so we need to skip over the decoration in that case.
588  StringRef ContentWithNoDecoration = Content[LineIndex];
589  if (LineIndex == 0 && ContentWithNoDecoration.startswith("*"))
590  ContentWithNoDecoration = ContentWithNoDecoration.substr(1).ltrim(Blanks);
591  StringRef FirstWord = ContentWithNoDecoration.substr(
592  0, ContentWithNoDecoration.find_first_of(Blanks));
593  if (ContentIndentingJavadocAnnotations.find(FirstWord) !=
596  }
597  return 0;
598 }
599 
600 void BreakableBlockComment::insertBreak(unsigned LineIndex, unsigned TailOffset,
601  Split Split, unsigned ContentIndent,
602  WhitespaceManager &Whitespaces) const {
603  StringRef Text = Content[LineIndex].substr(TailOffset);
604  StringRef Prefix = Decoration;
605  // We need this to account for the case when we have a decoration "* " for all
606  // the lines except for the last one, where the star in "*/" acts as a
607  // decoration.
608  unsigned LocalIndentAtLineBreak = IndentAtLineBreak;
609  if (LineIndex + 1 == Lines.size() &&
610  Text.size() == Split.first + Split.second) {
611  // For the last line we need to break before "*/", but not to add "* ".
612  Prefix = "";
613  if (LocalIndentAtLineBreak >= 2)
614  LocalIndentAtLineBreak -= 2;
615  }
616  // The split offset is from the beginning of the line. Convert it to an offset
617  // from the beginning of the token text.
618  unsigned BreakOffsetInToken =
619  Text.data() - tokenAt(LineIndex).TokenText.data() + Split.first;
620  unsigned CharsToRemove = Split.second;
621  assert(LocalIndentAtLineBreak >= Prefix.size());
622  std::string PrefixWithTrailingIndent = std::string(Prefix);
623  PrefixWithTrailingIndent.append(ContentIndent, ' ');
624  Whitespaces.replaceWhitespaceInToken(
625  tokenAt(LineIndex), BreakOffsetInToken, CharsToRemove, "",
626  PrefixWithTrailingIndent, InPPDirective, /*Newlines=*/1,
627  /*Spaces=*/LocalIndentAtLineBreak + ContentIndent -
628  PrefixWithTrailingIndent.size());
629 }
630 
632  unsigned LineIndex, const llvm::Regex &CommentPragmasRegex) const {
633  if (!mayReflow(LineIndex, CommentPragmasRegex))
634  return Split(StringRef::npos, 0);
635 
636  // If we're reflowing into a line with content indent, only reflow the next
637  // line if its starting whitespace matches the content indent.
638  size_t Trimmed = Content[LineIndex].find_first_not_of(Blanks);
639  if (LineIndex) {
640  unsigned PreviousContentIndent = getContentIndent(LineIndex - 1);
641  if (PreviousContentIndent && Trimmed != StringRef::npos &&
642  Trimmed != PreviousContentIndent) {
643  return Split(StringRef::npos, 0);
644  }
645  }
646 
647  return Split(0, Trimmed != StringRef::npos ? Trimmed : 0);
648 }
649 
651  // A break is introduced when we want delimiters on newline.
652  return DelimitersOnNewline &&
653  Lines[0].substr(1).find_first_not_of(Blanks) != StringRef::npos;
654 }
655 
656 void BreakableBlockComment::reflow(unsigned LineIndex,
657  WhitespaceManager &Whitespaces) const {
658  StringRef TrimmedContent = Content[LineIndex].ltrim(Blanks);
659  // Here we need to reflow.
660  assert(Tokens[LineIndex - 1] == Tokens[LineIndex] &&
661  "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  unsigned WhitespaceOffsetInToken = Content[LineIndex - 1].data() +
665  Content[LineIndex - 1].size() -
666  tokenAt(LineIndex).TokenText.data();
667  unsigned WhitespaceLength = TrimmedContent.data() -
668  tokenAt(LineIndex).TokenText.data() -
669  WhitespaceOffsetInToken;
670  Whitespaces.replaceWhitespaceInToken(
671  tokenAt(LineIndex), WhitespaceOffsetInToken,
672  /*ReplaceChars=*/WhitespaceLength, /*PreviousPostfix=*/"",
673  /*CurrentPrefix=*/ReflowPrefix, InPPDirective, /*Newlines=*/0,
674  /*Spaces=*/0);
675 }
676 
678  unsigned LineIndex, WhitespaceManager &Whitespaces) const {
679  if (LineIndex == 0) {
680  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  size_t BreakLength = Lines[0].substr(1).find_first_not_of(Blanks);
686  if (BreakLength != StringRef::npos) {
687  insertBreak(LineIndex, 0, Split(1, BreakLength), /*ContentIndent=*/0,
688  Whitespaces);
689  }
690  }
691  return;
692  }
693  // Here no reflow with the previous line will happen.
694  // Fix the decoration of the line at LineIndex.
695  StringRef Prefix = Decoration;
696  if (Content[LineIndex].empty()) {
697  if (LineIndex + 1 == Lines.size()) {
698  if (!LastLineNeedsDecoration) {
699  // If the last line was empty, we don't need a prefix, as the */ will
700  // line up with the decoration (if it exists).
701  Prefix = "";
702  }
703  } else if (!Decoration.empty()) {
704  // For other empty lines, if we do have a decoration, adapt it to not
705  // contain a trailing whitespace.
706  Prefix = Prefix.substr(0, 1);
707  }
708  } else if (ContentColumn[LineIndex] == 1) {
709  // This line starts immediately after the decorating *.
710  Prefix = Prefix.substr(0, 1);
711  }
712  // This is the offset of the end of the last line relative to the start of the
713  // token text in the token.
714  unsigned WhitespaceOffsetInToken = Content[LineIndex - 1].data() +
715  Content[LineIndex - 1].size() -
716  tokenAt(LineIndex).TokenText.data();
717  unsigned WhitespaceLength = Content[LineIndex].data() -
718  tokenAt(LineIndex).TokenText.data() -
719  WhitespaceOffsetInToken;
720  Whitespaces.replaceWhitespaceInToken(
721  tokenAt(LineIndex), WhitespaceOffsetInToken, WhitespaceLength, "", Prefix,
722  InPPDirective, /*Newlines=*/1, ContentColumn[LineIndex] - Prefix.size());
723 }
724 
727  if (DelimitersOnNewline) {
728  // Replace the trailing whitespace of the last line with a newline.
729  // In case the last line is empty, the ending '*/' is already on its own
730  // line.
731  StringRef Line = Content.back().substr(TailOffset);
732  StringRef TrimmedLine = Line.rtrim(Blanks);
733  if (!TrimmedLine.empty())
734  return Split(TrimmedLine.size(), Line.size() - TrimmedLine.size());
735  }
736  return Split(StringRef::npos, 0);
737 }
738 
740  unsigned LineIndex, const llvm::Regex &CommentPragmasRegex) const {
741  // Content[LineIndex] may exclude the indent after the '*' decoration. In that
742  // case, we compute the start of the comment pragma manually.
743  StringRef IndentContent = Content[LineIndex];
744  if (Lines[LineIndex].ltrim(Blanks).startswith("*"))
745  IndentContent = Lines[LineIndex].ltrim(Blanks).substr(1);
746  return LineIndex > 0 && !CommentPragmasRegex.match(IndentContent) &&
747  mayReflowContent(Content[LineIndex]) && !Tok.Finalized &&
748  !switchesFormatting(tokenAt(LineIndex));
749 }
750 
752  const FormatToken &Token, unsigned StartColumn, bool InPPDirective,
754  : BreakableComment(Token, StartColumn, InPPDirective, Encoding, Style) {
755  assert(Tok.is(TT_LineComment) &&
756  "line comment section must start with a line comment");
757  FormatToken *LineTok = nullptr;
758  const int Minimum = Style.SpacesInLineCommentPrefix.Minimum;
759  // How many spaces we changed in the first line of the section, this will be
760  // applied in all following lines
761  int FirstLineSpaceChange = 0;
762  for (const FormatToken *CurrentTok = &Tok;
763  CurrentTok && CurrentTok->is(TT_LineComment);
764  CurrentTok = CurrentTok->Next) {
765  LastLineTok = LineTok;
766  StringRef TokenText(CurrentTok->TokenText);
767  assert((TokenText.startswith("//") || TokenText.startswith("#")) &&
768  "unsupported line comment prefix, '//' and '#' are supported");
769  size_t FirstLineIndex = Lines.size();
770  TokenText.split(Lines, "\n");
771  Content.resize(Lines.size());
772  ContentColumn.resize(Lines.size());
773  PrefixSpaceChange.resize(Lines.size());
774  Tokens.resize(Lines.size());
775  Prefix.resize(Lines.size());
776  OriginalPrefix.resize(Lines.size());
777  for (size_t i = FirstLineIndex, e = Lines.size(); i < e; ++i) {
778  Lines[i] = Lines[i].ltrim(Blanks);
779  StringRef IndentPrefix = getLineCommentIndentPrefix(Lines[i], Style);
780  OriginalPrefix[i] = IndentPrefix;
781  const int SpacesInPrefix = llvm::count(IndentPrefix, ' ');
782 
783  // This lambda also considers multibyte character that is not handled in
784  // functions like isPunctuation provided by CharInfo.
785  const auto NoSpaceBeforeFirstCommentChar = [&]() {
786  assert(Lines[i].size() > IndentPrefix.size());
787  const char FirstCommentChar = Lines[i][IndentPrefix.size()];
788  const unsigned FirstCharByteSize =
789  encoding::getCodePointNumBytes(FirstCommentChar, Encoding);
791  Lines[i].substr(IndentPrefix.size(), FirstCharByteSize),
792  Encoding) != 1) {
793  return false;
794  }
795  // In C-like comments, add a space before #. For example this is useful
796  // to preserve the relative indentation when commenting out code with
797  // #includes.
798  //
799  // In languages using # as the comment leader such as proto, don't
800  // add a space to support patterns like:
801  // #########
802  // # section
803  // #########
804  if (FirstCommentChar == '#' && !TokenText.startswith("#"))
805  return false;
806  return FirstCommentChar == '\\' || isPunctuation(FirstCommentChar) ||
807  isHorizontalWhitespace(FirstCommentChar);
808  };
809 
810  // On the first line of the comment section we calculate how many spaces
811  // are to be added or removed, all lines after that just get only the
812  // change and we will not look at the maximum anymore. Additionally to the
813  // actual first line, we calculate that when the non space Prefix changes,
814  // e.g. from "///" to "//".
815  if (i == 0 || OriginalPrefix[i].rtrim(Blanks) !=
816  OriginalPrefix[i - 1].rtrim(Blanks)) {
817  if (SpacesInPrefix < Minimum && Lines[i].size() > IndentPrefix.size() &&
818  !NoSpaceBeforeFirstCommentChar()) {
819  FirstLineSpaceChange = Minimum - SpacesInPrefix;
820  } else if (static_cast<unsigned>(SpacesInPrefix) >
822  FirstLineSpaceChange =
823  Style.SpacesInLineCommentPrefix.Maximum - SpacesInPrefix;
824  } else {
825  FirstLineSpaceChange = 0;
826  }
827  }
828 
829  if (Lines[i].size() != IndentPrefix.size()) {
830  PrefixSpaceChange[i] = FirstLineSpaceChange;
831 
832  if (SpacesInPrefix + PrefixSpaceChange[i] < Minimum) {
833  PrefixSpaceChange[i] +=
834  Minimum - (SpacesInPrefix + PrefixSpaceChange[i]);
835  }
836 
837  assert(Lines[i].size() > IndentPrefix.size());
838  const auto FirstNonSpace = Lines[i][IndentPrefix.size()];
839  const bool IsFormatComment = LineTok && switchesFormatting(*LineTok);
840  const bool LineRequiresLeadingSpace =
841  !NoSpaceBeforeFirstCommentChar() ||
842  (FirstNonSpace == '}' && FirstLineSpaceChange != 0);
843  const bool AllowsSpaceChange =
844  !IsFormatComment &&
845  (SpacesInPrefix != 0 || LineRequiresLeadingSpace);
846 
847  if (PrefixSpaceChange[i] > 0 && AllowsSpaceChange) {
848  Prefix[i] = IndentPrefix.str();
849  Prefix[i].append(PrefixSpaceChange[i], ' ');
850  } else if (PrefixSpaceChange[i] < 0 && AllowsSpaceChange) {
851  Prefix[i] = IndentPrefix
852  .drop_back(std::min<std::size_t>(
853  -PrefixSpaceChange[i], SpacesInPrefix))
854  .str();
855  } else {
856  Prefix[i] = IndentPrefix.str();
857  }
858  } else {
859  // If the IndentPrefix is the whole line, there is no content and we
860  // drop just all space
861  Prefix[i] = IndentPrefix.drop_back(SpacesInPrefix).str();
862  }
863 
864  Tokens[i] = LineTok;
865  Content[i] = Lines[i].substr(IndentPrefix.size());
866  ContentColumn[i] =
869 
870  // Calculate the end of the non-whitespace text in this line.
871  size_t EndOfLine = Content[i].find_last_not_of(Blanks);
872  if (EndOfLine == StringRef::npos)
873  EndOfLine = Content[i].size();
874  else
875  ++EndOfLine;
876  Content[i] = Content[i].substr(0, EndOfLine);
877  }
878  LineTok = CurrentTok->Next;
879  if (CurrentTok->Next && !CurrentTok->Next->ContinuesLineCommentSection) {
880  // A line comment section needs to broken by a line comment that is
881  // preceded by at least two newlines. Note that we put this break here
882  // instead of breaking at a previous stage during parsing, since that
883  // would split the contents of the enum into two unwrapped lines in this
884  // example, which is undesirable:
885  // enum A {
886  // a, // comment about a
887  //
888  // // comment about b
889  // b
890  // };
891  //
892  // FIXME: Consider putting separate line comment sections as children to
893  // the unwrapped line instead.
894  break;
895  }
896  }
897 }
898 
899 unsigned
901  StringRef::size_type Length,
902  unsigned StartColumn) const {
904  Content[LineIndex].substr(Offset, Length), StartColumn, Style.TabWidth,
905  Encoding);
906 }
907 
908 unsigned
910  bool /*Break*/) const {
911  return ContentColumn[LineIndex];
912 }
913 
915  unsigned LineIndex, unsigned TailOffset, Split Split,
916  unsigned ContentIndent, WhitespaceManager &Whitespaces) const {
917  StringRef Text = Content[LineIndex].substr(TailOffset);
918  // Compute the offset of the split relative to the beginning of the token
919  // text.
920  unsigned BreakOffsetInToken =
921  Text.data() - tokenAt(LineIndex).TokenText.data() + Split.first;
922  unsigned CharsToRemove = Split.second;
923  Whitespaces.replaceWhitespaceInToken(
924  tokenAt(LineIndex), BreakOffsetInToken, CharsToRemove, "",
925  Prefix[LineIndex], InPPDirective, /*Newlines=*/1,
926  /*Spaces=*/ContentColumn[LineIndex] - Prefix[LineIndex].size());
927 }
928 
930  unsigned LineIndex, const llvm::Regex &CommentPragmasRegex) const {
931  if (!mayReflow(LineIndex, CommentPragmasRegex))
932  return Split(StringRef::npos, 0);
933 
934  size_t Trimmed = Content[LineIndex].find_first_not_of(Blanks);
935 
936  // In a line comment section each line is a separate token; thus, after a
937  // split we replace all whitespace before the current line comment token
938  // (which does not need to be included in the split), plus the start of the
939  // line up to where the content starts.
940  return Split(0, Trimmed != StringRef::npos ? Trimmed : 0);
941 }
942 
943 void BreakableLineCommentSection::reflow(unsigned LineIndex,
944  WhitespaceManager &Whitespaces) const {
945  if (LineIndex > 0 && Tokens[LineIndex] != Tokens[LineIndex - 1]) {
946  // Reflow happens between tokens. Replace the whitespace between the
947  // tokens by the empty string.
948  Whitespaces.replaceWhitespace(
949  *Tokens[LineIndex], /*Newlines=*/0, /*Spaces=*/0,
950  /*StartOfTokenColumn=*/StartColumn, /*IsAligned=*/true,
951  /*InPPDirective=*/false);
952  } else if (LineIndex > 0) {
953  // In case we're reflowing after the '\' in:
954  //
955  // // line comment \
956  // // line 2
957  //
958  // the reflow happens inside the single comment token (it is a single line
959  // comment with an unescaped newline).
960  // Replace the whitespace between the '\' and '//' with the empty string.
961  //
962  // Offset points to after the '\' relative to start of the token.
963  unsigned Offset = Lines[LineIndex - 1].data() +
964  Lines[LineIndex - 1].size() -
965  tokenAt(LineIndex - 1).TokenText.data();
966  // WhitespaceLength is the number of chars between the '\' and the '//' on
967  // the next line.
968  unsigned WhitespaceLength =
969  Lines[LineIndex].data() - tokenAt(LineIndex).TokenText.data() - Offset;
970  Whitespaces.replaceWhitespaceInToken(*Tokens[LineIndex], Offset,
971  /*ReplaceChars=*/WhitespaceLength,
972  /*PreviousPostfix=*/"",
973  /*CurrentPrefix=*/"",
974  /*InPPDirective=*/false,
975  /*Newlines=*/0,
976  /*Spaces=*/0);
977  }
978  // Replace the indent and prefix of the token with the reflow prefix.
979  unsigned Offset =
980  Lines[LineIndex].data() - tokenAt(LineIndex).TokenText.data();
981  unsigned WhitespaceLength =
982  Content[LineIndex].data() - Lines[LineIndex].data();
983  Whitespaces.replaceWhitespaceInToken(*Tokens[LineIndex], Offset,
984  /*ReplaceChars=*/WhitespaceLength,
985  /*PreviousPostfix=*/"",
986  /*CurrentPrefix=*/ReflowPrefix,
987  /*InPPDirective=*/false,
988  /*Newlines=*/0,
989  /*Spaces=*/0);
990 }
991 
993  unsigned LineIndex, WhitespaceManager &Whitespaces) const {
994  // If this is the first line of a token, we need to inform Whitespace Manager
995  // about it: either adapt the whitespace range preceding it, or mark it as an
996  // untouchable token.
997  // This happens for instance here:
998  // // line 1 \
999  // // line 2
1000  if (LineIndex > 0 && Tokens[LineIndex] != Tokens[LineIndex - 1]) {
1001  // This is the first line for the current token, but no reflow with the
1002  // previous token is necessary. However, we still may need to adjust the
1003  // start column. Note that ContentColumn[LineIndex] is the expected
1004  // content column after a possible update to the prefix, hence the prefix
1005  // length change is included.
1006  unsigned LineColumn =
1007  ContentColumn[LineIndex] -
1008  (Content[LineIndex].data() - Lines[LineIndex].data()) +
1009  (OriginalPrefix[LineIndex].size() - Prefix[LineIndex].size());
1010 
1011  // We always want to create a replacement instead of adding an untouchable
1012  // token, even if LineColumn is the same as the original column of the
1013  // token. This is because WhitespaceManager doesn't align trailing
1014  // comments if they are untouchable.
1015  Whitespaces.replaceWhitespace(*Tokens[LineIndex],
1016  /*Newlines=*/1,
1017  /*Spaces=*/LineColumn,
1018  /*StartOfTokenColumn=*/LineColumn,
1019  /*IsAligned=*/true,
1020  /*InPPDirective=*/false);
1021  }
1022  if (OriginalPrefix[LineIndex] != Prefix[LineIndex]) {
1023  // Adjust the prefix if necessary.
1024  const auto SpacesToRemove = -std::min(PrefixSpaceChange[LineIndex], 0);
1025  const auto SpacesToAdd = std::max(PrefixSpaceChange[LineIndex], 0);
1026  Whitespaces.replaceWhitespaceInToken(
1027  tokenAt(LineIndex), OriginalPrefix[LineIndex].size() - SpacesToRemove,
1028  /*ReplaceChars=*/SpacesToRemove, "", "", /*InPPDirective=*/false,
1029  /*Newlines=*/0, /*Spaces=*/SpacesToAdd);
1030  }
1031 }
1032 
1034  if (LastLineTok)
1035  State.NextToken = LastLineTok->Next;
1036 }
1037 
1039  unsigned LineIndex, const llvm::Regex &CommentPragmasRegex) const {
1040  // Line comments have the indent as part of the prefix, so we need to
1041  // recompute the start of the line.
1042  StringRef IndentContent = Content[LineIndex];
1043  if (Lines[LineIndex].startswith("//"))
1044  IndentContent = Lines[LineIndex].substr(2);
1045  // FIXME: Decide whether we want to reflow non-regular indents:
1046  // Currently, we only reflow when the OriginalPrefix[LineIndex] matches the
1047  // OriginalPrefix[LineIndex-1]. That means we don't reflow
1048  // // text that protrudes
1049  // // into text with different indent
1050  // We do reflow in that case in block comments.
1051  return LineIndex > 0 && !CommentPragmasRegex.match(IndentContent) &&
1052  mayReflowContent(Content[LineIndex]) && !Tok.Finalized &&
1053  !switchesFormatting(tokenAt(LineIndex)) &&
1054  OriginalPrefix[LineIndex] == OriginalPrefix[LineIndex - 1];
1055 }
1056 
1057 } // namespace format
1058 } // namespace clang
max
__DEVICE__ int max(int __a, int __b)
Definition: __clang_cuda_math.h:196
clang::format::BreakableToken::InPPDirective
const bool InPPDirective
Definition: BreakableToken.h:240
clang::format::BreakableToken
Base class for tokens / ranges of tokens that can allow breaking within the tokens - for example,...
Definition: BreakableToken.h:89
clang::format::BreakableBlockComment::BreakableBlockComment
BreakableBlockComment(const FormatToken &Token, unsigned StartColumn, unsigned OriginalStartColumn, bool FirstInLine, bool InPPDirective, encoding::Encoding Encoding, const FormatStyle &Style, bool UseCRLF)
Definition: BreakableToken.cpp:366
clang::format::BreakableToken::Encoding
const encoding::Encoding Encoding
Definition: BreakableToken.h:241
string
string(SUBSTRING ${CMAKE_CURRENT_BINARY_DIR} 0 ${PATH_LIB_START} PATH_HEAD) string(SUBSTRING $
Definition: CMakeLists.txt:22
clang::format::BreakableStringLiteral::getLineCount
unsigned getLineCount() const override
Returns the number of lines in this token in the original code.
Definition: BreakableToken.cpp:244
clang::format::mayReflowContent
static bool mayReflowContent(StringRef Content)
Definition: BreakableToken.cpp:336
clang::format::BreakableStringLiteral::Line
StringRef Line
Definition: BreakableToken.h:280
clang::format::encoding::columnWidth
unsigned columnWidth(StringRef Text, Encoding Encoding)
Returns the number of columns required to display the Text on a generic Unicode-capable terminal.
Definition: Encoding.h:45
clang::format::BreakableLineCommentSection::getReflowSplit
Split getReflowSplit(unsigned LineIndex, const llvm::Regex &CommentPragmasRegex) const override
Returns a whitespace range (offset, length) of the content at LineIndex such that the content of that...
Definition: BreakableToken.cpp:929
clang::format::BreakableBlockComment::reflow
void reflow(unsigned LineIndex, WhitespaceManager &Whitespaces) const override
Reflows the current line into the end of the previous one.
Definition: BreakableToken.cpp:656
clang::format::FormatStyle
The FormatStyle is used to configure the formatting to follow specific guidelines.
Definition: Format.h:54
clang::format::FormatToken::TokenText
StringRef TokenText
The raw text of the token.
Definition: FormatToken.h:258
clang::format::BreakableBlockComment::getRangeLength
unsigned getRangeLength(unsigned LineIndex, unsigned Offset, StringRef::size_type Length, unsigned StartColumn) const override
Returns the number of columns required to format the text in the byte range [Offset,...
Definition: BreakableToken.cpp:541
clang::format::BreakableToken::Tok
const FormatToken & Tok
Definition: BreakableToken.h:239
clang::format::FormatToken
A wrapper around a Token storing information about the whitespace characters preceding it.
Definition: FormatToken.h:240
clang::format::BreakableStringLiteral::getSplit
Split getSplit(unsigned LineIndex, unsigned TailOffset, unsigned ColumnLimit, unsigned ContentStartColumn, const llvm::Regex &CommentPragmasRegex) const override
Returns a range (offset, length) at which to break the line at LineIndex, if previously broken at Tai...
Definition: BreakableToken.cpp:279
clang::isPunctuation
LLVM_READONLY bool isPunctuation(unsigned char c)
Return true if this character is an ASCII punctuation character.
Definition: CharInfo.h:137
Format.h
clang::format::BreakableStringLiteral::getRemainingLength
unsigned getRemainingLength(unsigned LineIndex, unsigned Offset, unsigned StartColumn) const override
Returns the number of columns required to format the text following the byte Offset in the line LineI...
Definition: BreakableToken.cpp:255
clang::Token
Token - This structure provides full information about a lexed token.
Definition: Token.h:35
clang::format::BreakableComment::getLineCount
unsigned getLineCount() const override
Returns the number of lines in this token in the original code.
Definition: BreakableToken.cpp:302
clang::format::BreakableStringLiteral::getContentStartColumn
unsigned getContentStartColumn(unsigned LineIndex, bool Break) const override
Returns the column at which content in line LineIndex starts, assuming no reflow.
Definition: BreakableToken.cpp:262
BreakableToken.h
Offset
unsigned Offset
Definition: Format.cpp:2717
clang::format::BreakableBlockComment::getContentStartColumn
unsigned getContentStartColumn(unsigned LineIndex, bool Break) const override
Returns the column at which content in line LineIndex starts, assuming no reflow.
Definition: BreakableToken.cpp:569
clang::format::LineState
The current state when indenting a unwrapped line.
Definition: ContinuationIndenter.h:415
clang::format::encoding::getEscapeSequenceLength
unsigned getEscapeSequenceLength(StringRef Text)
Gets the length of an escape sequence inside a C++ string literal.
Definition: Encoding.h:97
min
__DEVICE__ int min(int __a, int __b)
Definition: __clang_cuda_math.h:197
clang::format::encoding::Encoding
Encoding
Definition: Encoding.h:27
clang::format::FormatStyle::LK_TextProto
@ LK_TextProto
Should be used for Protocol Buffer messages in text format (https://developers.google....
Definition: Format.h:2602
clang::format::BreakableComment::Tokens
SmallVector< FormatToken *, 16 > Tokens
Definition: BreakableToken.h:329
clang::format::BreakableComment::ContentColumn
SmallVector< int, 16 > ContentColumn
Definition: BreakableToken.h:341
clang::format::BreakableBlockComment::getRemainingLength
unsigned getRemainingLength(unsigned LineIndex, unsigned Offset, unsigned StartColumn) const override
Returns the number of columns required to format the text following the byte Offset in the line LineI...
Definition: BreakableToken.cpp:550
clang::format::BreakableBlockComment::mayReflow
bool mayReflow(unsigned LineIndex, const llvm::Regex &CommentPragmasRegex) const override
Definition: BreakableToken.cpp:739
clang::format::WhitespaceManager
Manages the whitespaces around tokens and their replacements.
Definition: WhitespaceManager.h:40
clang::format::getCommentSplit
static BreakableToken::Split getCommentSplit(StringRef Text, unsigned ContentStartColumn, unsigned ColumnLimit, unsigned TabWidth, encoding::Encoding Encoding, const FormatStyle &Style, bool DecorationEndsWithStar=false)
Definition: BreakableToken.cpp:68
clang::format::BreakableStringLiteral::insertBreak
void insertBreak(unsigned LineIndex, unsigned TailOffset, Split Split, unsigned ContentIndent, WhitespaceManager &Whitespaces) const override
Emits the previously retrieved Split via Whitespaces.
Definition: BreakableToken.cpp:286
clang::format::FormatStyle::SpacesInLineComment::Minimum
unsigned Minimum
The minimum number of spaces at the start of the comment.
Definition: Format.h:3832
clang::format::BreakableComment::BreakableComment
BreakableComment(const FormatToken &Token, unsigned StartColumn, bool InPPDirective, encoding::Encoding Encoding, const FormatStyle &Style)
Creates a breakable token for a comment.
Definition: BreakableToken.cpp:295
clang::format::BreakableComment::compressWhitespace
void compressWhitespace(unsigned LineIndex, unsigned TailOffset, Split Split, WhitespaceManager &Whitespaces) const override
Replaces the whitespace range described by Split with a single space.
Definition: BreakableToken.cpp:316
clang::format::getLineCommentIndentPrefix
static StringRef getLineCommentIndentPrefix(StringRef Comment, const FormatStyle &Style)
Definition: BreakableToken.cpp:42
clang::Token::is
bool is(tok::TokenKind K) const
is/isNot - Predicates to check if this token is a specific kind, as in "if (Tok.is(tok::l_brace)) {....
Definition: Token.h:98
clang::format::FormatStyle::ColumnLimit
unsigned ColumnLimit
The column limit.
Definition: Format.h:1859
clang::format::BreakableBlockComment::getContentIndent
unsigned getContentIndent(unsigned LineIndex) const override
Returns additional content indent required for the second line after the content at line LineIndex is...
Definition: BreakableToken.cpp:582
clang::format::BreakableToken::Style
const FormatStyle & Style
Definition: BreakableToken.h:242
clang::format::BreakableBlockComment::adaptStartOfLine
void adaptStartOfLine(unsigned LineIndex, WhitespaceManager &Whitespaces) const override
Replaces the whitespace between LineIndex-1 and LineIndex.
Definition: BreakableToken.cpp:677
Line
const AnnotatedLine * Line
Definition: UsingDeclarationsSorter.cpp:68
clang::format::BreakableLineCommentSection::updateNextToken
void updateNextToken(LineState &State) const override
Updates the next token of State to the next token after this one.
Definition: BreakableToken.cpp:1033
clang::format::Blanks
static constexpr StringRef Blanks
Definition: BreakableToken.cpp:28
clang::format::FormatStyle::TabWidth
unsigned TabWidth
The number of columns used for tab stops.
Definition: Format.h:3955
clang::format::BreakableLineCommentSection::getContentStartColumn
unsigned getContentStartColumn(unsigned LineIndex, bool Break) const override
Returns the column at which content in line LineIndex starts, assuming no reflow.
Definition: BreakableToken.cpp:909
clang::format::BreakableBlockComment::getSplitAfterLastLine
Split getSplitAfterLastLine(unsigned TailOffset) const override
Returns a whitespace range (offset, length) of the content at the last line that needs to be reformat...
Definition: BreakableToken.cpp:726
clang::format::FormatStyle::isJavaScript
bool isJavaScript() const
Definition: Format.h:2611
clang::format::BreakableBlockComment::getSplit
Split getSplit(unsigned LineIndex, unsigned TailOffset, unsigned ColumnLimit, unsigned ContentStartColumn, const llvm::Regex &CommentPragmasRegex) const override
Returns a range (offset, length) at which to break the line at LineIndex, if previously broken at Tai...
Definition: BreakableToken.cpp:493
clang::format::BreakableComment::StartColumn
unsigned StartColumn
Definition: BreakableToken.h:344
clang::format::BreakableStringLiteral::BreakableStringLiteral
BreakableStringLiteral(const FormatToken &Tok, unsigned StartColumn, StringRef Prefix, StringRef Postfix, unsigned UnbreakableTailLength, bool InPPDirective, encoding::Encoding Encoding, const FormatStyle &Style)
Creates a breakable token for a single line string literal.
Definition: BreakableToken.cpp:267
clang::format::FormatStyle::SpacesInLineComment::Maximum
unsigned Maximum
The maximum number of spaces at the start of the comment.
Definition: Format.h:3834
clang::format::FormatStyle::ContinuationIndentWidth
unsigned ContinuationIndentWidth
Indent width for line continuations.
Definition: Format.h:1954
CharInfo.h
clang::format::BreakableToken::getLengthAfterCompression
unsigned getLengthAfterCompression(unsigned RemainingTokenColumns, Split Split) const
Returns the number of columns needed to format RemainingTokenColumns, assuming that Split is within t...
Definition: BreakableToken.cpp:228
false
#define false
Definition: stdbool.h:22
clang::format::FormatToken::Finalized
unsigned Finalized
If true, this token has been fully formatted (indented and potentially re-formatted inside),...
Definition: FormatToken.h:313
clang::format::FormatStyle::Language
LanguageKind Language
Language, this format style is targeted at.
Definition: Format.h:2617
clang::format::FormatStyle::LK_Java
@ LK_Java
Should be used for Java.
Definition: Format.h:2588
clang::format::BreakableLineCommentSection::BreakableLineCommentSection
BreakableLineCommentSection(const FormatToken &Token, unsigned StartColumn, bool InPPDirective, encoding::Encoding Encoding, const FormatStyle &Style)
Definition: BreakableToken.cpp:751
llvm::ArrayRef
Definition: LLVM.h:34
clang::isAlphanumeric
LLVM_READONLY bool isAlphanumeric(unsigned char c)
Return true if this character is an ASCII letter or digit: [a-zA-Z0-9].
Definition: CharInfo.h:123
clang::format::BreakableBlockComment::ContentIndentingJavadocAnnotations
static const llvm::StringSet ContentIndentingJavadocAnnotations
Definition: BreakableToken.h:391
clang::format::getStringSplit
static BreakableToken::Split getStringSplit(StringRef Text, unsigned UsedColumns, unsigned ColumnLimit, unsigned TabWidth, encoding::Encoding Encoding)
Definition: BreakableToken.cpp:171
clang::format::FormatToken::is
bool is(tok::TokenKind Kind) const
Definition: FormatToken.h:525
clang::format::BreakableComment::Content
SmallVector< StringRef, 16 > Content
Definition: BreakableToken.h:324
clang::format::BreakableStringLiteral::Postfix
StringRef Postfix
Definition: BreakableToken.h:278
State
LineState State
Definition: UnwrappedLineFormatter.cpp:1147
clang::format::BreakableStringLiteral::getRangeLength
unsigned getRangeLength(unsigned LineIndex, unsigned Offset, StringRef::size_type Length, unsigned StartColumn) const override
Returns the number of columns required to format the text in the byte range [Offset,...
Definition: BreakableToken.cpp:246
clang::format::IsBlank
static bool IsBlank(char C)
Definition: BreakableToken.cpp:29
clang::format::BreakableStringLiteral::Prefix
StringRef Prefix
Definition: BreakableToken.h:276
clang::format::BreakableComment::Lines
SmallVector< StringRef, 16 > Lines
Definition: BreakableToken.h:319
clang::format::BreakableBlockComment::getReflowSplit
Split getReflowSplit(unsigned LineIndex, const llvm::Regex &CommentPragmasRegex) const override
Returns a whitespace range (offset, length) of the content at LineIndex such that the content of that...
Definition: BreakableToken.cpp:631
clang::format::FormatStyle::SpacesInLineCommentPrefix
SpacesInLineComment SpacesInLineCommentPrefix
How many spaces are allowed at the start of a line comment.
Definition: Format.h:3869
clang
Definition: CalledOnceCheck.h:17
Text
StringRef Text
Definition: Format.cpp:2716
clang::format::BreakableBlockComment::introducesBreakBeforeToken
bool introducesBreakBeforeToken() const override
Returns whether there will be a line break at the start of the token.
Definition: BreakableToken.cpp:650
clang::format::switchesFormatting
bool switchesFormatting(const FormatToken &Token)
Checks if Token switches formatting, like /* clang-format off *‍/.
Definition: BreakableToken.cpp:219
clang::format::BreakableLineCommentSection::insertBreak
void insertBreak(unsigned LineIndex, unsigned TailOffset, Split Split, unsigned ContentIndent, WhitespaceManager &Whitespaces) const override
Emits the previously retrieved Split via Whitespaces.
Definition: BreakableToken.cpp:914
clang::format::BreakableBlockComment::insertBreak
void insertBreak(unsigned LineIndex, unsigned TailOffset, Split Split, unsigned ContentIndent, WhitespaceManager &Whitespaces) const override
Emits the previously retrieved Split via Whitespaces.
Definition: BreakableToken.cpp:600
clang::format::FormatStyle::isCpp
bool isCpp() const
Definition: Format.h:2608
clang::format::encoding::getCodePointNumBytes
unsigned getCodePointNumBytes(char FirstChar, Encoding Encoding)
Gets the number of bytes in a sequence representing a single codepoint and starting with FirstChar in...
Definition: Encoding.h:78
clang::format::BreakableLineCommentSection::adaptStartOfLine
void adaptStartOfLine(unsigned LineIndex, WhitespaceManager &Whitespaces) const override
Replaces the whitespace between LineIndex-1 and LineIndex.
Definition: BreakableToken.cpp:992
clang::format::encoding::columnWidthWithTabs
unsigned columnWidthWithTabs(StringRef Text, unsigned StartColumn, unsigned TabWidth, Encoding Encoding)
Returns the number of columns required to display the Text, starting from the StartColumn on a termin...
Definition: Encoding.h:61
clang::isHorizontalWhitespace
LLVM_READONLY bool isHorizontalWhitespace(unsigned char c)
Returns true if this character is horizontal ASCII whitespace: ' ', '\t', '\f', '\v'.
Definition: CharInfo.h:76
clang::format::BreakableLineCommentSection::getRangeLength
unsigned getRangeLength(unsigned LineIndex, unsigned Offset, StringRef::size_type Length, unsigned StartColumn) const override
Returns the number of columns required to format the text in the byte range [Offset,...
Definition: BreakableToken.cpp:900
ContinuationIndenter.h
clang::format::BreakableLineCommentSection::reflow
void reflow(unsigned LineIndex, WhitespaceManager &Whitespaces) const override
Reflows the current line into the end of the previous one.
Definition: BreakableToken.cpp:943
clang::format::BreakableComment::getSplit
Split getSplit(unsigned LineIndex, unsigned TailOffset, unsigned ColumnLimit, unsigned ContentStartColumn, const llvm::Regex &CommentPragmasRegex) const override
Returns a range (offset, length) at which to break the line at LineIndex, if previously broken at Tai...
Definition: BreakableToken.cpp:305
clang::format::BreakableComment
Definition: BreakableToken.h:286
clang::format::BreakableStringLiteral::UnbreakableTailLength
unsigned UnbreakableTailLength
Definition: BreakableToken.h:283
clang::format::FormatToken::Next
FormatToken * Next
The next token in the unwrapped line.
Definition: FormatToken.h:488
clang::format::BreakableLineCommentSection::mayReflow
bool mayReflow(unsigned LineIndex, const llvm::Regex &CommentPragmasRegex) const override
Definition: BreakableToken.cpp:1038
clang::format::BreakableToken::Split
std::pair< StringRef::size_type, unsigned > Split
Contains starting character index and length of split.
Definition: BreakableToken.h:92
clang::format::BreakableStringLiteral::StartColumn
unsigned StartColumn
Definition: BreakableToken.h:274
clang::format::BreakableComment::ReflowPrefix
StringRef ReflowPrefix
Definition: BreakableToken.h:354
clang::format::BreakableComment::tokenAt
const FormatToken & tokenAt(unsigned LineIndex) const
Definition: BreakableToken.cpp:332