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