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