1 //===--- BreakableToken.cpp - Format C++ code -----------------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 /// 10 /// \file 11 /// \brief Contains implementation of BreakableToken class and classes derived 12 /// from it. 13 /// 14 //===----------------------------------------------------------------------===// 15 16 #define DEBUG_TYPE "format-token-breaker" 17 18 #include "BreakableToken.h" 19 #include "clang/Basic/CharInfo.h" 20 #include "clang/Format/Format.h" 21 #include "llvm/ADT/STLExtras.h" 22 #include "llvm/Support/Debug.h" 23 #include <algorithm> 24 25 namespace clang { 26 namespace format { 27 28 static const char *const 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 BreakableToken::Split getCommentSplit(StringRef Text, 43 unsigned ContentStartColumn, 44 unsigned ColumnLimit, 45 unsigned TabWidth, 46 encoding::Encoding Encoding) { 47 if (ColumnLimit <= ContentStartColumn + 1) 48 return BreakableToken::Split(StringRef::npos, 0); 49 50 unsigned MaxSplit = ColumnLimit - ContentStartColumn + 1; 51 unsigned MaxSplitBytes = 0; 52 53 for (unsigned NumChars = 0; 54 NumChars < MaxSplit && MaxSplitBytes < Text.size();) { 55 unsigned BytesInChar = 56 encoding::getCodePointNumBytes(Text[MaxSplitBytes], Encoding); 57 NumChars += 58 encoding::columnWidthWithTabs(Text.substr(MaxSplitBytes, BytesInChar), 59 ContentStartColumn, TabWidth, Encoding); 60 MaxSplitBytes += BytesInChar; 61 } 62 63 StringRef::size_type SpaceOffset = Text.find_last_of(Blanks, MaxSplitBytes); 64 if (SpaceOffset == StringRef::npos || 65 // Don't break at leading whitespace. 66 Text.find_last_not_of(Blanks, SpaceOffset) == StringRef::npos) { 67 // Make sure that we don't break at leading whitespace that 68 // reaches past MaxSplit. 69 StringRef::size_type FirstNonWhitespace = Text.find_first_not_of(Blanks); 70 if (FirstNonWhitespace == StringRef::npos) 71 // If the comment is only whitespace, we cannot split. 72 return BreakableToken::Split(StringRef::npos, 0); 73 SpaceOffset = Text.find_first_of( 74 Blanks, std::max<unsigned>(MaxSplitBytes, FirstNonWhitespace)); 75 } 76 if (SpaceOffset != StringRef::npos && SpaceOffset != 0) { 77 StringRef BeforeCut = Text.substr(0, SpaceOffset).rtrim(Blanks); 78 StringRef AfterCut = Text.substr(SpaceOffset).ltrim(Blanks); 79 return BreakableToken::Split(BeforeCut.size(), 80 AfterCut.begin() - BeforeCut.end()); 81 } 82 return BreakableToken::Split(StringRef::npos, 0); 83 } 84 85 static BreakableToken::Split getStringSplit(StringRef Text, 86 unsigned UsedColumns, 87 unsigned ColumnLimit, 88 unsigned TabWidth, 89 encoding::Encoding Encoding) { 90 // FIXME: Reduce unit test case. 91 if (Text.empty()) 92 return BreakableToken::Split(StringRef::npos, 0); 93 if (ColumnLimit <= UsedColumns) 94 return BreakableToken::Split(StringRef::npos, 0); 95 unsigned MaxSplit = ColumnLimit - UsedColumns; 96 StringRef::size_type SpaceOffset = 0; 97 StringRef::size_type SlashOffset = 0; 98 StringRef::size_type WordStartOffset = 0; 99 StringRef::size_type SplitPoint = 0; 100 for (unsigned Chars = 0;;) { 101 unsigned Advance; 102 if (Text[0] == '\\') { 103 Advance = encoding::getEscapeSequenceLength(Text); 104 Chars += Advance; 105 } else { 106 Advance = encoding::getCodePointNumBytes(Text[0], Encoding); 107 Chars += encoding::columnWidthWithTabs( 108 Text.substr(0, Advance), UsedColumns + Chars, TabWidth, Encoding); 109 } 110 111 if (Chars > MaxSplit || Text.size() == Advance) 112 break; 113 114 if (IsBlank(Text[0])) 115 SpaceOffset = SplitPoint; 116 if (Text[0] == '/') 117 SlashOffset = SplitPoint; 118 if (Advance == 1 && !isAlphanumeric(Text[0])) 119 WordStartOffset = SplitPoint; 120 121 SplitPoint += Advance; 122 Text = Text.substr(Advance); 123 } 124 125 if (SpaceOffset != 0) 126 return BreakableToken::Split(SpaceOffset + 1, 0); 127 if (SlashOffset != 0) 128 return BreakableToken::Split(SlashOffset + 1, 0); 129 if (WordStartOffset != 0) 130 return BreakableToken::Split(WordStartOffset + 1, 0); 131 if (SplitPoint != 0) 132 return BreakableToken::Split(SplitPoint, 0); 133 return BreakableToken::Split(StringRef::npos, 0); 134 } 135 136 unsigned BreakableSingleLineToken::getLineCount() const { return 1; } 137 138 unsigned BreakableSingleLineToken::getLineLengthAfterSplit( 139 unsigned LineIndex, unsigned Offset, StringRef::size_type Length) const { 140 return StartColumn + Prefix.size() + Postfix.size() + 141 encoding::columnWidthWithTabs(Line.substr(Offset, Length), 142 StartColumn + Prefix.size(), 143 Style.TabWidth, Encoding); 144 } 145 146 BreakableSingleLineToken::BreakableSingleLineToken( 147 const FormatToken &Tok, unsigned IndentLevel, unsigned StartColumn, 148 StringRef Prefix, StringRef Postfix, bool InPPDirective, 149 encoding::Encoding Encoding, const FormatStyle &Style) 150 : BreakableToken(Tok, IndentLevel, InPPDirective, Encoding, Style), 151 StartColumn(StartColumn), Prefix(Prefix), Postfix(Postfix) { 152 assert(Tok.TokenText.startswith(Prefix) && Tok.TokenText.endswith(Postfix)); 153 Line = Tok.TokenText.substr( 154 Prefix.size(), Tok.TokenText.size() - Prefix.size() - Postfix.size()); 155 } 156 157 BreakableStringLiteral::BreakableStringLiteral( 158 const FormatToken &Tok, unsigned IndentLevel, unsigned StartColumn, 159 StringRef Prefix, StringRef Postfix, bool InPPDirective, 160 encoding::Encoding Encoding, const FormatStyle &Style) 161 : BreakableSingleLineToken(Tok, IndentLevel, StartColumn, Prefix, Postfix, 162 InPPDirective, Encoding, Style) {} 163 164 BreakableToken::Split 165 BreakableStringLiteral::getSplit(unsigned LineIndex, unsigned TailOffset, 166 unsigned ColumnLimit) const { 167 return getStringSplit(Line.substr(TailOffset), 168 StartColumn + Prefix.size() + Postfix.size(), 169 ColumnLimit, Style.TabWidth, Encoding); 170 } 171 172 void BreakableStringLiteral::insertBreak(unsigned LineIndex, 173 unsigned TailOffset, Split Split, 174 WhitespaceManager &Whitespaces) { 175 Whitespaces.replaceWhitespaceInToken( 176 Tok, Prefix.size() + TailOffset + Split.first, Split.second, Postfix, 177 Prefix, InPPDirective, 1, IndentLevel, StartColumn); 178 } 179 180 static StringRef getLineCommentPrefix(StringRef Comment) { 181 static const char *const KnownPrefixes[] = { "/// ", "///", "// ", "//" }; 182 for (size_t i = 0, e = llvm::array_lengthof(KnownPrefixes); i != e; ++i) 183 if (Comment.startswith(KnownPrefixes[i])) 184 return KnownPrefixes[i]; 185 return ""; 186 } 187 188 BreakableLineComment::BreakableLineComment( 189 const FormatToken &Token, unsigned IndentLevel, unsigned StartColumn, 190 bool InPPDirective, encoding::Encoding Encoding, const FormatStyle &Style) 191 : BreakableSingleLineToken(Token, IndentLevel, StartColumn, 192 getLineCommentPrefix(Token.TokenText), "", 193 InPPDirective, Encoding, Style) { 194 OriginalPrefix = Prefix; 195 if (Token.TokenText.size() > Prefix.size() && 196 isAlphanumeric(Token.TokenText[Prefix.size()])) { 197 if (Prefix == "//") 198 Prefix = "// "; 199 else if (Prefix == "///") 200 Prefix = "/// "; 201 } 202 } 203 204 BreakableToken::Split 205 BreakableLineComment::getSplit(unsigned LineIndex, unsigned TailOffset, 206 unsigned ColumnLimit) const { 207 return getCommentSplit(Line.substr(TailOffset), StartColumn + Prefix.size(), 208 ColumnLimit, Style.TabWidth, Encoding); 209 } 210 211 void BreakableLineComment::insertBreak(unsigned LineIndex, unsigned TailOffset, 212 Split Split, 213 WhitespaceManager &Whitespaces) { 214 Whitespaces.replaceWhitespaceInToken( 215 Tok, OriginalPrefix.size() + TailOffset + Split.first, Split.second, 216 Postfix, Prefix, InPPDirective, /*Newlines=*/1, IndentLevel, StartColumn); 217 } 218 219 void BreakableLineComment::replaceWhitespace(unsigned LineIndex, 220 unsigned TailOffset, Split Split, 221 WhitespaceManager &Whitespaces) { 222 Whitespaces.replaceWhitespaceInToken( 223 Tok, OriginalPrefix.size() + TailOffset + Split.first, Split.second, "", 224 "", /*InPPDirective=*/false, /*Newlines=*/0, /*IndentLevel=*/0, 225 /*Spaces=*/1); 226 } 227 228 void 229 BreakableLineComment::replaceWhitespaceBefore(unsigned LineIndex, 230 WhitespaceManager &Whitespaces) { 231 if (OriginalPrefix != Prefix) { 232 Whitespaces.replaceWhitespaceInToken(Tok, OriginalPrefix.size(), 0, "", "", 233 /*InPPDirective=*/false, 234 /*Newlines=*/0, /*IndentLevel=*/0, 235 /*Spaces=*/1); 236 } 237 } 238 239 BreakableBlockComment::BreakableBlockComment( 240 const FormatToken &Token, unsigned IndentLevel, unsigned StartColumn, 241 unsigned OriginalStartColumn, bool FirstInLine, bool InPPDirective, 242 encoding::Encoding Encoding, const FormatStyle &Style) 243 : BreakableToken(Token, IndentLevel, InPPDirective, Encoding, Style) { 244 StringRef TokenText(Token.TokenText); 245 assert(TokenText.startswith("/*") && TokenText.endswith("*/")); 246 TokenText.substr(2, TokenText.size() - 4).split(Lines, "\n"); 247 248 int IndentDelta = StartColumn - OriginalStartColumn; 249 LeadingWhitespace.resize(Lines.size()); 250 StartOfLineColumn.resize(Lines.size()); 251 StartOfLineColumn[0] = StartColumn + 2; 252 for (size_t i = 1; i < Lines.size(); ++i) 253 adjustWhitespace(i, IndentDelta); 254 255 Decoration = "* "; 256 if (Lines.size() == 1 && !FirstInLine) { 257 // Comments for which FirstInLine is false can start on arbitrary column, 258 // and available horizontal space can be too small to align consecutive 259 // lines with the first one. 260 // FIXME: We could, probably, align them to current indentation level, but 261 // now we just wrap them without stars. 262 Decoration = ""; 263 } 264 for (size_t i = 1, e = Lines.size(); i < e && !Decoration.empty(); ++i) { 265 // If the last line is empty, the closing "*/" will have a star. 266 if (i + 1 == e && Lines[i].empty()) 267 break; 268 while (!Lines[i].startswith(Decoration)) 269 Decoration = Decoration.substr(0, Decoration.size() - 1); 270 } 271 272 LastLineNeedsDecoration = true; 273 IndentAtLineBreak = StartOfLineColumn[0] + 1; 274 for (size_t i = 1; i < Lines.size(); ++i) { 275 if (Lines[i].empty()) { 276 if (i + 1 == Lines.size()) { 277 // Empty last line means that we already have a star as a part of the 278 // trailing */. We also need to preserve whitespace, so that */ is 279 // correctly indented. 280 LastLineNeedsDecoration = false; 281 } else if (Decoration.empty()) { 282 // For all other lines, set the start column to 0 if they're empty, so 283 // we do not insert trailing whitespace anywhere. 284 StartOfLineColumn[i] = 0; 285 } 286 continue; 287 } 288 // The first line already excludes the star. 289 // For all other lines, adjust the line to exclude the star and 290 // (optionally) the first whitespace. 291 StartOfLineColumn[i] += Decoration.size(); 292 Lines[i] = Lines[i].substr(Decoration.size()); 293 LeadingWhitespace[i] += Decoration.size(); 294 IndentAtLineBreak = std::min<int>(IndentAtLineBreak, StartOfLineColumn[i]); 295 } 296 IndentAtLineBreak = std::max<unsigned>(IndentAtLineBreak, Decoration.size()); 297 DEBUG({ 298 llvm::dbgs() << "IndentAtLineBreak " << IndentAtLineBreak << "\n"; 299 for (size_t i = 0; i < Lines.size(); ++i) { 300 llvm::dbgs() << i << " |" << Lines[i] << "| " << LeadingWhitespace[i] 301 << "\n"; 302 } 303 }); 304 } 305 306 void BreakableBlockComment::adjustWhitespace(unsigned LineIndex, 307 int IndentDelta) { 308 // When in a preprocessor directive, the trailing backslash in a block comment 309 // is not needed, but can serve a purpose of uniformity with necessary escaped 310 // newlines outside the comment. In this case we remove it here before 311 // trimming the trailing whitespace. The backslash will be re-added later when 312 // inserting a line break. 313 size_t EndOfPreviousLine = Lines[LineIndex - 1].size(); 314 if (InPPDirective && Lines[LineIndex - 1].endswith("\\")) 315 --EndOfPreviousLine; 316 317 // Calculate the end of the non-whitespace text in the previous line. 318 EndOfPreviousLine = 319 Lines[LineIndex - 1].find_last_not_of(Blanks, EndOfPreviousLine); 320 if (EndOfPreviousLine == StringRef::npos) 321 EndOfPreviousLine = 0; 322 else 323 ++EndOfPreviousLine; 324 // Calculate the start of the non-whitespace text in the current line. 325 size_t StartOfLine = Lines[LineIndex].find_first_not_of(Blanks); 326 if (StartOfLine == StringRef::npos) 327 StartOfLine = Lines[LineIndex].size(); 328 329 StringRef Whitespace = Lines[LineIndex].substr(0, StartOfLine); 330 // Adjust Lines to only contain relevant text. 331 Lines[LineIndex - 1] = Lines[LineIndex - 1].substr(0, EndOfPreviousLine); 332 Lines[LineIndex] = Lines[LineIndex].substr(StartOfLine); 333 // Adjust LeadingWhitespace to account all whitespace between the lines 334 // to the current line. 335 LeadingWhitespace[LineIndex] = 336 Lines[LineIndex].begin() - Lines[LineIndex - 1].end(); 337 338 // Adjust the start column uniformly across all lines. 339 StartOfLineColumn[LineIndex] = std::max<int>( 340 0, 341 encoding::columnWidthWithTabs(Whitespace, 0, Style.TabWidth, Encoding) + 342 IndentDelta); 343 } 344 345 unsigned BreakableBlockComment::getLineCount() const { return Lines.size(); } 346 347 unsigned BreakableBlockComment::getLineLengthAfterSplit( 348 unsigned LineIndex, unsigned Offset, StringRef::size_type Length) const { 349 unsigned ContentStartColumn = getContentStartColumn(LineIndex, Offset); 350 return ContentStartColumn + 351 encoding::columnWidthWithTabs(Lines[LineIndex].substr(Offset, Length), 352 ContentStartColumn, Style.TabWidth, 353 Encoding) + 354 // The last line gets a "*/" postfix. 355 (LineIndex + 1 == Lines.size() ? 2 : 0); 356 } 357 358 BreakableToken::Split 359 BreakableBlockComment::getSplit(unsigned LineIndex, unsigned TailOffset, 360 unsigned ColumnLimit) const { 361 return getCommentSplit(Lines[LineIndex].substr(TailOffset), 362 getContentStartColumn(LineIndex, TailOffset), 363 ColumnLimit, Style.TabWidth, Encoding); 364 } 365 366 void BreakableBlockComment::insertBreak(unsigned LineIndex, unsigned TailOffset, 367 Split Split, 368 WhitespaceManager &Whitespaces) { 369 StringRef Text = Lines[LineIndex].substr(TailOffset); 370 StringRef Prefix = Decoration; 371 if (LineIndex + 1 == Lines.size() && 372 Text.size() == Split.first + Split.second) { 373 // For the last line we need to break before "*/", but not to add "* ". 374 Prefix = ""; 375 } 376 377 unsigned BreakOffsetInToken = 378 Text.data() - Tok.TokenText.data() + Split.first; 379 unsigned CharsToRemove = Split.second; 380 assert(IndentAtLineBreak >= Decoration.size()); 381 Whitespaces.replaceWhitespaceInToken( 382 Tok, BreakOffsetInToken, CharsToRemove, "", Prefix, InPPDirective, 1, 383 IndentLevel, IndentAtLineBreak - Decoration.size()); 384 } 385 386 void BreakableBlockComment::replaceWhitespace(unsigned LineIndex, 387 unsigned TailOffset, Split Split, 388 WhitespaceManager &Whitespaces) { 389 StringRef Text = Lines[LineIndex].substr(TailOffset); 390 unsigned BreakOffsetInToken = 391 Text.data() - Tok.TokenText.data() + Split.first; 392 unsigned CharsToRemove = Split.second; 393 Whitespaces.replaceWhitespaceInToken( 394 Tok, BreakOffsetInToken, CharsToRemove, "", "", /*InPPDirective=*/false, 395 /*Newlines=*/0, /*IndentLevel=*/0, /*Spaces=*/1); 396 } 397 398 void 399 BreakableBlockComment::replaceWhitespaceBefore(unsigned LineIndex, 400 WhitespaceManager &Whitespaces) { 401 if (LineIndex == 0) 402 return; 403 StringRef Prefix = Decoration; 404 if (Lines[LineIndex].empty()) { 405 if (LineIndex + 1 == Lines.size()) { 406 if (!LastLineNeedsDecoration) { 407 // If the last line was empty, we don't need a prefix, as the */ will 408 // line up with the decoration (if it exists). 409 Prefix = ""; 410 } 411 } else if (!Decoration.empty()) { 412 // For other empty lines, if we do have a decoration, adapt it to not 413 // contain a trailing whitespace. 414 Prefix = Prefix.substr(0, 1); 415 } 416 } else { 417 if (StartOfLineColumn[LineIndex] == 1) { 418 // This line starts immediately after the decorating *. 419 Prefix = Prefix.substr(0, 1); 420 } 421 } 422 423 unsigned WhitespaceOffsetInToken = Lines[LineIndex].data() - 424 Tok.TokenText.data() - 425 LeadingWhitespace[LineIndex]; 426 assert(StartOfLineColumn[LineIndex] >= Prefix.size()); 427 Whitespaces.replaceWhitespaceInToken( 428 Tok, WhitespaceOffsetInToken, LeadingWhitespace[LineIndex], "", Prefix, 429 InPPDirective, 1, IndentLevel, 430 StartOfLineColumn[LineIndex] - Prefix.size()); 431 } 432 433 unsigned 434 BreakableBlockComment::getContentStartColumn(unsigned LineIndex, 435 unsigned TailOffset) const { 436 // If we break, we always break at the predefined indent. 437 if (TailOffset != 0) 438 return IndentAtLineBreak; 439 return StartOfLineColumn[LineIndex]; 440 } 441 442 } // namespace format 443 } // namespace clang 444