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