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 the last line is empty, the closing "*/" will have a star. 414 if (i + 1 == e && Text.empty()) 415 break; 416 if (!Text.empty() && i + 1 != e && Decoration.startswith(Text)) 417 continue; 418 while (!Text.startswith(Decoration)) 419 Decoration = Decoration.drop_back(1); 420 } 421 422 LastLineNeedsDecoration = true; 423 IndentAtLineBreak = ContentColumn[0] + 1; 424 for (size_t i = 1, e = Lines.size(); i < e; ++i) { 425 if (Content[i].empty()) { 426 if (i + 1 == e) { 427 // Empty last line means that we already have a star as a part of the 428 // trailing */. We also need to preserve whitespace, so that */ is 429 // correctly indented. 430 LastLineNeedsDecoration = false; 431 // Align the star in the last '*/' with the stars on the previous lines. 432 if (e >= 2 && !Decoration.empty()) 433 ContentColumn[i] = DecorationColumn; 434 } else if (Decoration.empty()) { 435 // For all other lines, set the start column to 0 if they're empty, so 436 // we do not insert trailing whitespace anywhere. 437 ContentColumn[i] = 0; 438 } 439 continue; 440 } 441 442 // The first line already excludes the star. 443 // The last line excludes the star if LastLineNeedsDecoration is false. 444 // For all other lines, adjust the line to exclude the star and 445 // (optionally) the first whitespace. 446 unsigned DecorationSize = Decoration.startswith(Content[i]) 447 ? Content[i].size() 448 : Decoration.size(); 449 if (DecorationSize) 450 ContentColumn[i] = DecorationColumn + DecorationSize; 451 Content[i] = Content[i].substr(DecorationSize); 452 if (!Decoration.startswith(Content[i])) 453 IndentAtLineBreak = 454 std::min<int>(IndentAtLineBreak, std::max(0, ContentColumn[i])); 455 } 456 IndentAtLineBreak = std::max<unsigned>(IndentAtLineBreak, Decoration.size()); 457 458 // Detect a multiline jsdoc comment and set DelimitersOnNewline in that case. 459 if (Style.isJavaScript() || Style.Language == FormatStyle::LK_Java) { 460 if ((Lines[0] == "*" || Lines[0].startswith("* ")) && Lines.size() > 1) { 461 // This is a multiline jsdoc comment. 462 DelimitersOnNewline = true; 463 } else if (Lines[0].startswith("* ") && Lines.size() == 1) { 464 // Detect a long single-line comment, like: 465 // /** long long long */ 466 // Below, '2' is the width of '*/'. 467 unsigned EndColumn = 468 ContentColumn[0] + 469 encoding::columnWidthWithTabs(Lines[0], ContentColumn[0], 470 Style.TabWidth, Encoding) + 471 2; 472 DelimitersOnNewline = EndColumn > Style.ColumnLimit; 473 } 474 } 475 476 LLVM_DEBUG({ 477 llvm::dbgs() << "IndentAtLineBreak " << IndentAtLineBreak << "\n"; 478 llvm::dbgs() << "DelimitersOnNewline " << DelimitersOnNewline << "\n"; 479 for (size_t i = 0; i < Lines.size(); ++i) 480 llvm::dbgs() << i << " |" << Content[i] << "| " 481 << "CC=" << ContentColumn[i] << "| " 482 << "IN=" << (Content[i].data() - Lines[i].data()) << "\n"; 483 }); 484 } 485 486 BreakableToken::Split BreakableBlockComment::getSplit( 487 unsigned LineIndex, unsigned TailOffset, unsigned ColumnLimit, 488 unsigned ContentStartColumn, const llvm::Regex &CommentPragmasRegex) const { 489 // Don't break lines matching the comment pragmas regex. 490 if (CommentPragmasRegex.match(Content[LineIndex])) 491 return Split(StringRef::npos, 0); 492 return getCommentSplit(Content[LineIndex].substr(TailOffset), 493 ContentStartColumn, ColumnLimit, Style.TabWidth, 494 Encoding, Style, Decoration.endswith("*")); 495 } 496 497 void BreakableBlockComment::adjustWhitespace(unsigned LineIndex, 498 int IndentDelta) { 499 // When in a preprocessor directive, the trailing backslash in a block comment 500 // is not needed, but can serve a purpose of uniformity with necessary escaped 501 // newlines outside the comment. In this case we remove it here before 502 // trimming the trailing whitespace. The backslash will be re-added later when 503 // inserting a line break. 504 size_t EndOfPreviousLine = Lines[LineIndex - 1].size(); 505 if (InPPDirective && Lines[LineIndex - 1].endswith("\\")) 506 --EndOfPreviousLine; 507 508 // Calculate the end of the non-whitespace text in the previous line. 509 EndOfPreviousLine = 510 Lines[LineIndex - 1].find_last_not_of(Blanks, EndOfPreviousLine); 511 if (EndOfPreviousLine == StringRef::npos) 512 EndOfPreviousLine = 0; 513 else 514 ++EndOfPreviousLine; 515 // Calculate the start of the non-whitespace text in the current line. 516 size_t StartOfLine = Lines[LineIndex].find_first_not_of(Blanks); 517 if (StartOfLine == StringRef::npos) 518 StartOfLine = Lines[LineIndex].size(); 519 520 StringRef Whitespace = Lines[LineIndex].substr(0, StartOfLine); 521 // Adjust Lines to only contain relevant text. 522 size_t PreviousContentOffset = 523 Content[LineIndex - 1].data() - Lines[LineIndex - 1].data(); 524 Content[LineIndex - 1] = Lines[LineIndex - 1].substr( 525 PreviousContentOffset, EndOfPreviousLine - PreviousContentOffset); 526 Content[LineIndex] = Lines[LineIndex].substr(StartOfLine); 527 528 // Adjust the start column uniformly across all lines. 529 ContentColumn[LineIndex] = 530 encoding::columnWidthWithTabs(Whitespace, 0, Style.TabWidth, Encoding) + 531 IndentDelta; 532 } 533 534 unsigned BreakableBlockComment::getRangeLength(unsigned LineIndex, 535 unsigned Offset, 536 StringRef::size_type Length, 537 unsigned StartColumn) const { 538 return encoding::columnWidthWithTabs( 539 Content[LineIndex].substr(Offset, Length), StartColumn, Style.TabWidth, 540 Encoding); 541 } 542 543 unsigned BreakableBlockComment::getRemainingLength(unsigned LineIndex, 544 unsigned Offset, 545 unsigned StartColumn) const { 546 unsigned LineLength = 547 UnbreakableTailLength + 548 getRangeLength(LineIndex, Offset, StringRef::npos, StartColumn); 549 if (LineIndex + 1 == Lines.size()) { 550 LineLength += 2; 551 // We never need a decoration when breaking just the trailing "*/" postfix. 552 bool HasRemainingText = Offset < Content[LineIndex].size(); 553 if (!HasRemainingText) { 554 bool HasDecoration = Lines[LineIndex].ltrim().startswith(Decoration); 555 if (HasDecoration) 556 LineLength -= Decoration.size(); 557 } 558 } 559 return LineLength; 560 } 561 562 unsigned BreakableBlockComment::getContentStartColumn(unsigned LineIndex, 563 bool Break) const { 564 if (Break) 565 return IndentAtLineBreak; 566 return std::max(0, ContentColumn[LineIndex]); 567 } 568 569 const llvm::StringSet<> 570 BreakableBlockComment::ContentIndentingJavadocAnnotations = { 571 "@param", "@return", "@returns", "@throws", "@type", "@template", 572 "@see", "@deprecated", "@define", "@exports", "@mods", "@private", 573 }; 574 575 unsigned BreakableBlockComment::getContentIndent(unsigned LineIndex) const { 576 if (Style.Language != FormatStyle::LK_Java && !Style.isJavaScript()) 577 return 0; 578 // The content at LineIndex 0 of a comment like: 579 // /** line 0 */ 580 // is "* line 0", so we need to skip over the decoration in that case. 581 StringRef ContentWithNoDecoration = Content[LineIndex]; 582 if (LineIndex == 0 && ContentWithNoDecoration.startswith("*")) 583 ContentWithNoDecoration = ContentWithNoDecoration.substr(1).ltrim(Blanks); 584 StringRef FirstWord = ContentWithNoDecoration.substr( 585 0, ContentWithNoDecoration.find_first_of(Blanks)); 586 if (ContentIndentingJavadocAnnotations.find(FirstWord) != 587 ContentIndentingJavadocAnnotations.end()) 588 return Style.ContinuationIndentWidth; 589 return 0; 590 } 591 592 void BreakableBlockComment::insertBreak(unsigned LineIndex, unsigned TailOffset, 593 Split Split, unsigned ContentIndent, 594 WhitespaceManager &Whitespaces) const { 595 StringRef Text = Content[LineIndex].substr(TailOffset); 596 StringRef Prefix = Decoration; 597 // We need this to account for the case when we have a decoration "* " for all 598 // the lines except for the last one, where the star in "*/" acts as a 599 // decoration. 600 unsigned LocalIndentAtLineBreak = IndentAtLineBreak; 601 if (LineIndex + 1 == Lines.size() && 602 Text.size() == Split.first + Split.second) { 603 // For the last line we need to break before "*/", but not to add "* ". 604 Prefix = ""; 605 if (LocalIndentAtLineBreak >= 2) 606 LocalIndentAtLineBreak -= 2; 607 } 608 // The split offset is from the beginning of the line. Convert it to an offset 609 // from the beginning of the token text. 610 unsigned BreakOffsetInToken = 611 Text.data() - tokenAt(LineIndex).TokenText.data() + Split.first; 612 unsigned CharsToRemove = Split.second; 613 assert(LocalIndentAtLineBreak >= Prefix.size()); 614 std::string PrefixWithTrailingIndent = std::string(Prefix); 615 PrefixWithTrailingIndent.append(ContentIndent, ' '); 616 Whitespaces.replaceWhitespaceInToken( 617 tokenAt(LineIndex), BreakOffsetInToken, CharsToRemove, "", 618 PrefixWithTrailingIndent, InPPDirective, /*Newlines=*/1, 619 /*Spaces=*/LocalIndentAtLineBreak + ContentIndent - 620 PrefixWithTrailingIndent.size()); 621 } 622 623 BreakableToken::Split BreakableBlockComment::getReflowSplit( 624 unsigned LineIndex, const llvm::Regex &CommentPragmasRegex) const { 625 if (!mayReflow(LineIndex, CommentPragmasRegex)) 626 return Split(StringRef::npos, 0); 627 628 // If we're reflowing into a line with content indent, only reflow the next 629 // line if its starting whitespace matches the content indent. 630 size_t Trimmed = Content[LineIndex].find_first_not_of(Blanks); 631 if (LineIndex) { 632 unsigned PreviousContentIndent = getContentIndent(LineIndex - 1); 633 if (PreviousContentIndent && Trimmed != StringRef::npos && 634 Trimmed != PreviousContentIndent) 635 return Split(StringRef::npos, 0); 636 } 637 638 return Split(0, Trimmed != StringRef::npos ? Trimmed : 0); 639 } 640 641 bool BreakableBlockComment::introducesBreakBeforeToken() const { 642 // A break is introduced when we want delimiters on newline. 643 return DelimitersOnNewline && 644 Lines[0].substr(1).find_first_not_of(Blanks) != StringRef::npos; 645 } 646 647 void BreakableBlockComment::reflow(unsigned LineIndex, 648 WhitespaceManager &Whitespaces) const { 649 StringRef TrimmedContent = Content[LineIndex].ltrim(Blanks); 650 // Here we need to reflow. 651 assert(Tokens[LineIndex - 1] == Tokens[LineIndex] && 652 "Reflowing whitespace within a token"); 653 // This is the offset of the end of the last line relative to the start of 654 // the token text in the token. 655 unsigned WhitespaceOffsetInToken = Content[LineIndex - 1].data() + 656 Content[LineIndex - 1].size() - 657 tokenAt(LineIndex).TokenText.data(); 658 unsigned WhitespaceLength = TrimmedContent.data() - 659 tokenAt(LineIndex).TokenText.data() - 660 WhitespaceOffsetInToken; 661 Whitespaces.replaceWhitespaceInToken( 662 tokenAt(LineIndex), WhitespaceOffsetInToken, 663 /*ReplaceChars=*/WhitespaceLength, /*PreviousPostfix=*/"", 664 /*CurrentPrefix=*/ReflowPrefix, InPPDirective, /*Newlines=*/0, 665 /*Spaces=*/0); 666 } 667 668 void BreakableBlockComment::adaptStartOfLine( 669 unsigned LineIndex, WhitespaceManager &Whitespaces) const { 670 if (LineIndex == 0) { 671 if (DelimitersOnNewline) { 672 // Since we're breaking at index 1 below, the break position and the 673 // break length are the same. 674 // Note: this works because getCommentSplit is careful never to split at 675 // the beginning of a line. 676 size_t BreakLength = Lines[0].substr(1).find_first_not_of(Blanks); 677 if (BreakLength != StringRef::npos) 678 insertBreak(LineIndex, 0, Split(1, BreakLength), /*ContentIndent=*/0, 679 Whitespaces); 680 } 681 return; 682 } 683 // Here no reflow with the previous line will happen. 684 // Fix the decoration of the line at LineIndex. 685 StringRef Prefix = Decoration; 686 if (Content[LineIndex].empty()) { 687 if (LineIndex + 1 == Lines.size()) { 688 if (!LastLineNeedsDecoration) { 689 // If the last line was empty, we don't need a prefix, as the */ will 690 // line up with the decoration (if it exists). 691 Prefix = ""; 692 } 693 } else if (!Decoration.empty()) { 694 // For other empty lines, if we do have a decoration, adapt it to not 695 // contain a trailing whitespace. 696 Prefix = Prefix.substr(0, 1); 697 } 698 } else { 699 if (ContentColumn[LineIndex] == 1) { 700 // This line starts immediately after the decorating *. 701 Prefix = Prefix.substr(0, 1); 702 } 703 } 704 // This is the offset of the end of the last line relative to the start of the 705 // token text in the token. 706 unsigned WhitespaceOffsetInToken = Content[LineIndex - 1].data() + 707 Content[LineIndex - 1].size() - 708 tokenAt(LineIndex).TokenText.data(); 709 unsigned WhitespaceLength = Content[LineIndex].data() - 710 tokenAt(LineIndex).TokenText.data() - 711 WhitespaceOffsetInToken; 712 Whitespaces.replaceWhitespaceInToken( 713 tokenAt(LineIndex), WhitespaceOffsetInToken, WhitespaceLength, "", Prefix, 714 InPPDirective, /*Newlines=*/1, ContentColumn[LineIndex] - Prefix.size()); 715 } 716 717 BreakableToken::Split 718 BreakableBlockComment::getSplitAfterLastLine(unsigned TailOffset) const { 719 if (DelimitersOnNewline) { 720 // Replace the trailing whitespace of the last line with a newline. 721 // In case the last line is empty, the ending '*/' is already on its own 722 // line. 723 StringRef Line = Content.back().substr(TailOffset); 724 StringRef TrimmedLine = Line.rtrim(Blanks); 725 if (!TrimmedLine.empty()) 726 return Split(TrimmedLine.size(), Line.size() - TrimmedLine.size()); 727 } 728 return Split(StringRef::npos, 0); 729 } 730 731 bool BreakableBlockComment::mayReflow( 732 unsigned LineIndex, const llvm::Regex &CommentPragmasRegex) const { 733 // Content[LineIndex] may exclude the indent after the '*' decoration. In that 734 // case, we compute the start of the comment pragma manually. 735 StringRef IndentContent = Content[LineIndex]; 736 if (Lines[LineIndex].ltrim(Blanks).startswith("*")) 737 IndentContent = Lines[LineIndex].ltrim(Blanks).substr(1); 738 return LineIndex > 0 && !CommentPragmasRegex.match(IndentContent) && 739 mayReflowContent(Content[LineIndex]) && !Tok.Finalized && 740 !switchesFormatting(tokenAt(LineIndex)); 741 } 742 743 BreakableLineCommentSection::BreakableLineCommentSection( 744 const FormatToken &Token, unsigned StartColumn, bool InPPDirective, 745 encoding::Encoding Encoding, const FormatStyle &Style) 746 : BreakableComment(Token, StartColumn, InPPDirective, Encoding, Style) { 747 assert(Tok.is(TT_LineComment) && 748 "line comment section must start with a line comment"); 749 FormatToken *LineTok = nullptr; 750 // How many spaces we changed in the first line of the section, this will be 751 // applied in all following lines 752 int FirstLineSpaceChange = 0; 753 for (const FormatToken *CurrentTok = &Tok; 754 CurrentTok && CurrentTok->is(TT_LineComment); 755 CurrentTok = CurrentTok->Next) { 756 LastLineTok = LineTok; 757 StringRef TokenText(CurrentTok->TokenText); 758 assert((TokenText.startswith("//") || TokenText.startswith("#")) && 759 "unsupported line comment prefix, '//' and '#' are supported"); 760 size_t FirstLineIndex = Lines.size(); 761 TokenText.split(Lines, "\n"); 762 Content.resize(Lines.size()); 763 ContentColumn.resize(Lines.size()); 764 PrefixSpaceChange.resize(Lines.size()); 765 Tokens.resize(Lines.size()); 766 Prefix.resize(Lines.size()); 767 OriginalPrefix.resize(Lines.size()); 768 for (size_t i = FirstLineIndex, e = Lines.size(); i < e; ++i) { 769 Lines[i] = Lines[i].ltrim(Blanks); 770 StringRef IndentPrefix = getLineCommentIndentPrefix(Lines[i], Style); 771 OriginalPrefix[i] = IndentPrefix; 772 const unsigned SpacesInPrefix = llvm::count(IndentPrefix, ' '); 773 774 // This lambda also considers multibyte character that is not handled in 775 // functions like isPunctuation provided by CharInfo. 776 const auto NoSpaceBeforeFirstCommentChar = [&]() { 777 assert(Lines[i].size() > IndentPrefix.size()); 778 const char FirstCommentChar = Lines[i][IndentPrefix.size()]; 779 const unsigned FirstCharByteSize = 780 encoding::getCodePointNumBytes(FirstCommentChar, Encoding); 781 return encoding::columnWidth( 782 Lines[i].substr(IndentPrefix.size(), FirstCharByteSize), 783 Encoding) == 1 && 784 (FirstCommentChar == '\\' || isPunctuation(FirstCommentChar) || 785 isHorizontalWhitespace(FirstCommentChar)); 786 }; 787 788 // On the first line of the comment section we calculate how many spaces 789 // are to be added or removed, all lines after that just get only the 790 // change and we will not look at the maximum anymore. Additionally to the 791 // actual first line, we calculate that when the non space Prefix changes, 792 // e.g. from "///" to "//". 793 if (i == 0 || OriginalPrefix[i].rtrim(Blanks) != 794 OriginalPrefix[i - 1].rtrim(Blanks)) { 795 if (SpacesInPrefix < Style.SpacesInLineCommentPrefix.Minimum && 796 Lines[i].size() > IndentPrefix.size() && 797 !NoSpaceBeforeFirstCommentChar()) { 798 FirstLineSpaceChange = 799 Style.SpacesInLineCommentPrefix.Minimum - SpacesInPrefix; 800 } else if (SpacesInPrefix > Style.SpacesInLineCommentPrefix.Maximum) { 801 FirstLineSpaceChange = 802 Style.SpacesInLineCommentPrefix.Maximum - SpacesInPrefix; 803 } else { 804 FirstLineSpaceChange = 0; 805 } 806 } 807 808 if (Lines[i].size() != IndentPrefix.size()) { 809 PrefixSpaceChange[i] = FirstLineSpaceChange; 810 811 if (SpacesInPrefix + PrefixSpaceChange[i] < 812 Style.SpacesInLineCommentPrefix.Minimum) { 813 PrefixSpaceChange[i] += Style.SpacesInLineCommentPrefix.Minimum - 814 (SpacesInPrefix + PrefixSpaceChange[i]); 815 } 816 817 assert(Lines[i].size() > IndentPrefix.size()); 818 const auto FirstNonSpace = Lines[i][IndentPrefix.size()]; 819 const auto AllowsSpaceChange = 820 SpacesInPrefix != 0 || 821 (!NoSpaceBeforeFirstCommentChar() || 822 (FirstNonSpace == '}' && FirstLineSpaceChange != 0)); 823 824 if (PrefixSpaceChange[i] > 0 && AllowsSpaceChange) { 825 Prefix[i] = IndentPrefix.str(); 826 Prefix[i].append(PrefixSpaceChange[i], ' '); 827 } else if (PrefixSpaceChange[i] < 0 && AllowsSpaceChange) { 828 Prefix[i] = IndentPrefix 829 .drop_back(std::min<std::size_t>( 830 -PrefixSpaceChange[i], SpacesInPrefix)) 831 .str(); 832 } else { 833 Prefix[i] = IndentPrefix.str(); 834 } 835 } else { 836 // If the IndentPrefix is the whole line, there is no content and we 837 // drop just all space 838 Prefix[i] = IndentPrefix.drop_back(SpacesInPrefix).str(); 839 } 840 841 Tokens[i] = LineTok; 842 Content[i] = Lines[i].substr(IndentPrefix.size()); 843 ContentColumn[i] = 844 StartColumn + encoding::columnWidthWithTabs(Prefix[i], StartColumn, 845 Style.TabWidth, Encoding); 846 847 // Calculate the end of the non-whitespace text in this line. 848 size_t EndOfLine = Content[i].find_last_not_of(Blanks); 849 if (EndOfLine == StringRef::npos) 850 EndOfLine = Content[i].size(); 851 else 852 ++EndOfLine; 853 Content[i] = Content[i].substr(0, EndOfLine); 854 } 855 LineTok = CurrentTok->Next; 856 if (CurrentTok->Next && !CurrentTok->Next->ContinuesLineCommentSection) { 857 // A line comment section needs to broken by a line comment that is 858 // preceded by at least two newlines. Note that we put this break here 859 // instead of breaking at a previous stage during parsing, since that 860 // would split the contents of the enum into two unwrapped lines in this 861 // example, which is undesirable: 862 // enum A { 863 // a, // comment about a 864 // 865 // // comment about b 866 // b 867 // }; 868 // 869 // FIXME: Consider putting separate line comment sections as children to 870 // the unwrapped line instead. 871 break; 872 } 873 } 874 } 875 876 unsigned 877 BreakableLineCommentSection::getRangeLength(unsigned LineIndex, unsigned Offset, 878 StringRef::size_type Length, 879 unsigned StartColumn) const { 880 return encoding::columnWidthWithTabs( 881 Content[LineIndex].substr(Offset, Length), StartColumn, Style.TabWidth, 882 Encoding); 883 } 884 885 unsigned 886 BreakableLineCommentSection::getContentStartColumn(unsigned LineIndex, 887 bool /*Break*/) const { 888 return ContentColumn[LineIndex]; 889 } 890 891 void BreakableLineCommentSection::insertBreak( 892 unsigned LineIndex, unsigned TailOffset, Split Split, 893 unsigned ContentIndent, WhitespaceManager &Whitespaces) const { 894 StringRef Text = Content[LineIndex].substr(TailOffset); 895 // Compute the offset of the split relative to the beginning of the token 896 // text. 897 unsigned BreakOffsetInToken = 898 Text.data() - tokenAt(LineIndex).TokenText.data() + Split.first; 899 unsigned CharsToRemove = Split.second; 900 Whitespaces.replaceWhitespaceInToken( 901 tokenAt(LineIndex), BreakOffsetInToken, CharsToRemove, "", 902 Prefix[LineIndex], InPPDirective, /*Newlines=*/1, 903 /*Spaces=*/ContentColumn[LineIndex] - Prefix[LineIndex].size()); 904 } 905 906 BreakableComment::Split BreakableLineCommentSection::getReflowSplit( 907 unsigned LineIndex, const llvm::Regex &CommentPragmasRegex) const { 908 if (!mayReflow(LineIndex, CommentPragmasRegex)) 909 return Split(StringRef::npos, 0); 910 911 size_t Trimmed = Content[LineIndex].find_first_not_of(Blanks); 912 913 // In a line comment section each line is a separate token; thus, after a 914 // split we replace all whitespace before the current line comment token 915 // (which does not need to be included in the split), plus the start of the 916 // line up to where the content starts. 917 return Split(0, Trimmed != StringRef::npos ? Trimmed : 0); 918 } 919 920 void BreakableLineCommentSection::reflow(unsigned LineIndex, 921 WhitespaceManager &Whitespaces) const { 922 if (LineIndex > 0 && Tokens[LineIndex] != Tokens[LineIndex - 1]) { 923 // Reflow happens between tokens. Replace the whitespace between the 924 // tokens by the empty string. 925 Whitespaces.replaceWhitespace( 926 *Tokens[LineIndex], /*Newlines=*/0, /*Spaces=*/0, 927 /*StartOfTokenColumn=*/StartColumn, /*IsAligned=*/true, 928 /*InPPDirective=*/false); 929 } else if (LineIndex > 0) { 930 // In case we're reflowing after the '\' in: 931 // 932 // // line comment \ 933 // // line 2 934 // 935 // the reflow happens inside the single comment token (it is a single line 936 // comment with an unescaped newline). 937 // Replace the whitespace between the '\' and '//' with the empty string. 938 // 939 // Offset points to after the '\' relative to start of the token. 940 unsigned Offset = Lines[LineIndex - 1].data() + 941 Lines[LineIndex - 1].size() - 942 tokenAt(LineIndex - 1).TokenText.data(); 943 // WhitespaceLength is the number of chars between the '\' and the '//' on 944 // the next line. 945 unsigned WhitespaceLength = 946 Lines[LineIndex].data() - tokenAt(LineIndex).TokenText.data() - Offset; 947 Whitespaces.replaceWhitespaceInToken(*Tokens[LineIndex], Offset, 948 /*ReplaceChars=*/WhitespaceLength, 949 /*PreviousPostfix=*/"", 950 /*CurrentPrefix=*/"", 951 /*InPPDirective=*/false, 952 /*Newlines=*/0, 953 /*Spaces=*/0); 954 } 955 // Replace the indent and prefix of the token with the reflow prefix. 956 unsigned Offset = 957 Lines[LineIndex].data() - tokenAt(LineIndex).TokenText.data(); 958 unsigned WhitespaceLength = 959 Content[LineIndex].data() - Lines[LineIndex].data(); 960 Whitespaces.replaceWhitespaceInToken(*Tokens[LineIndex], Offset, 961 /*ReplaceChars=*/WhitespaceLength, 962 /*PreviousPostfix=*/"", 963 /*CurrentPrefix=*/ReflowPrefix, 964 /*InPPDirective=*/false, 965 /*Newlines=*/0, 966 /*Spaces=*/0); 967 } 968 969 void BreakableLineCommentSection::adaptStartOfLine( 970 unsigned LineIndex, WhitespaceManager &Whitespaces) const { 971 // If this is the first line of a token, we need to inform Whitespace Manager 972 // about it: either adapt the whitespace range preceding it, or mark it as an 973 // untouchable token. 974 // This happens for instance here: 975 // // line 1 \ 976 // // line 2 977 if (LineIndex > 0 && Tokens[LineIndex] != Tokens[LineIndex - 1]) { 978 // This is the first line for the current token, but no reflow with the 979 // previous token is necessary. However, we still may need to adjust the 980 // start column. Note that ContentColumn[LineIndex] is the expected 981 // content column after a possible update to the prefix, hence the prefix 982 // length change is included. 983 unsigned LineColumn = 984 ContentColumn[LineIndex] - 985 (Content[LineIndex].data() - Lines[LineIndex].data()) + 986 (OriginalPrefix[LineIndex].size() - Prefix[LineIndex].size()); 987 988 // We always want to create a replacement instead of adding an untouchable 989 // token, even if LineColumn is the same as the original column of the 990 // token. This is because WhitespaceManager doesn't align trailing 991 // comments if they are untouchable. 992 Whitespaces.replaceWhitespace(*Tokens[LineIndex], 993 /*Newlines=*/1, 994 /*Spaces=*/LineColumn, 995 /*StartOfTokenColumn=*/LineColumn, 996 /*IsAligned=*/true, 997 /*InPPDirective=*/false); 998 } 999 if (OriginalPrefix[LineIndex] != Prefix[LineIndex]) { 1000 // Adjust the prefix if necessary. 1001 const auto SpacesToRemove = -std::min(PrefixSpaceChange[LineIndex], 0); 1002 const auto SpacesToAdd = std::max(PrefixSpaceChange[LineIndex], 0); 1003 Whitespaces.replaceWhitespaceInToken( 1004 tokenAt(LineIndex), OriginalPrefix[LineIndex].size() - SpacesToRemove, 1005 /*ReplaceChars=*/SpacesToRemove, "", "", /*InPPDirective=*/false, 1006 /*Newlines=*/0, /*Spaces=*/SpacesToAdd); 1007 } 1008 } 1009 1010 void BreakableLineCommentSection::updateNextToken(LineState &State) const { 1011 if (LastLineTok) 1012 State.NextToken = LastLineTok->Next; 1013 } 1014 1015 bool BreakableLineCommentSection::mayReflow( 1016 unsigned LineIndex, const llvm::Regex &CommentPragmasRegex) const { 1017 // Line comments have the indent as part of the prefix, so we need to 1018 // recompute the start of the line. 1019 StringRef IndentContent = Content[LineIndex]; 1020 if (Lines[LineIndex].startswith("//")) 1021 IndentContent = Lines[LineIndex].substr(2); 1022 // FIXME: Decide whether we want to reflow non-regular indents: 1023 // Currently, we only reflow when the OriginalPrefix[LineIndex] matches the 1024 // OriginalPrefix[LineIndex-1]. That means we don't reflow 1025 // // text that protrudes 1026 // // into text with different indent 1027 // We do reflow in that case in block comments. 1028 return LineIndex > 0 && !CommentPragmasRegex.match(IndentContent) && 1029 mayReflowContent(Content[LineIndex]) && !Tok.Finalized && 1030 !switchesFormatting(tokenAt(LineIndex)) && 1031 OriginalPrefix[LineIndex] == OriginalPrefix[LineIndex - 1]; 1032 } 1033 1034 } // namespace format 1035 } // namespace clang 1036