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