1 //===--- BreakableToken.cpp - Format C++ code -----------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
11 /// \brief Contains implementation of BreakableToken class and classes derived
14 //===----------------------------------------------------------------------===//
16 #define DEBUG_TYPE "format-token-breaker"
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"
28 static const char *const Blanks = " \t\v\f\r";
29 static bool IsBlank(char C) {
42 static BreakableToken::Split getCommentSplit(StringRef Text,
43 unsigned ContentStartColumn,
46 encoding::Encoding Encoding) {
47 if (ColumnLimit <= ContentStartColumn + 1)
48 return BreakableToken::Split(StringRef::npos, 0);
50 unsigned MaxSplit = ColumnLimit - ContentStartColumn + 1;
51 unsigned MaxSplitBytes = 0;
53 for (unsigned NumChars = 0;
54 NumChars < MaxSplit && MaxSplitBytes < Text.size();) {
55 unsigned BytesInChar =
56 encoding::getCodePointNumBytes(Text[MaxSplitBytes], Encoding);
58 encoding::columnWidthWithTabs(Text.substr(MaxSplitBytes, BytesInChar),
59 ContentStartColumn, TabWidth, Encoding);
60 MaxSplitBytes += BytesInChar;
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));
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());
82 return BreakableToken::Split(StringRef::npos, 0);
85 static BreakableToken::Split getStringSplit(StringRef Text,
89 encoding::Encoding Encoding) {
90 // FIXME: Reduce unit test case.
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;;) {
102 if (Text[0] == '\\') {
103 Advance = encoding::getEscapeSequenceLength(Text);
106 Advance = encoding::getCodePointNumBytes(Text[0], Encoding);
107 Chars += encoding::columnWidthWithTabs(
108 Text.substr(0, Advance), UsedColumns + Chars, TabWidth, Encoding);
111 if (Chars > MaxSplit || Text.size() == Advance)
114 if (IsBlank(Text[0]))
115 SpaceOffset = SplitPoint;
117 SlashOffset = SplitPoint;
118 if (Advance == 1 && !isAlphanumeric(Text[0]))
119 WordStartOffset = SplitPoint;
121 SplitPoint += Advance;
122 Text = Text.substr(Advance);
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);
132 return BreakableToken::Split(SplitPoint, 0);
133 return BreakableToken::Split(StringRef::npos, 0);
136 unsigned BreakableSingleLineToken::getLineCount() const { return 1; }
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);
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.endswith(Postfix));
153 Line = Tok.TokenText.substr(
154 Prefix.size(), Tok.TokenText.size() - Prefix.size() - Postfix.size());
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) {}
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);
172 void BreakableStringLiteral::insertBreak(unsigned LineIndex,
173 unsigned TailOffset, Split Split,
174 WhitespaceManager &Whitespaces) {
175 unsigned LeadingSpaces = StartColumn;
176 // The '@' of an ObjC string literal (@"Test") does not become part of the
178 // FIXME: It might be a cleaner solution to merge the tokens as a
179 // precomputation step.
180 if (Prefix.startswith("@"))
182 Whitespaces.replaceWhitespaceInToken(
183 Tok, Prefix.size() + TailOffset + Split.first, Split.second, Postfix,
184 Prefix, InPPDirective, 1, IndentLevel, LeadingSpaces);
187 static StringRef getLineCommentIndentPrefix(StringRef Comment) {
188 static const char *const KnownPrefixes[] = { "///", "//" };
189 StringRef LongestPrefix;
190 for (StringRef KnownPrefix : KnownPrefixes) {
191 if (Comment.startswith(KnownPrefix)) {
192 size_t PrefixLength = KnownPrefix.size();
193 while (PrefixLength < Comment.size() && Comment[PrefixLength] == ' ')
195 if (PrefixLength > LongestPrefix.size())
196 LongestPrefix = Comment.substr(0, PrefixLength);
199 return LongestPrefix;
202 BreakableLineComment::BreakableLineComment(
203 const FormatToken &Token, unsigned IndentLevel, unsigned StartColumn,
204 bool InPPDirective, encoding::Encoding Encoding, const FormatStyle &Style)
205 : BreakableSingleLineToken(Token, IndentLevel, StartColumn,
206 getLineCommentIndentPrefix(Token.TokenText), "",
207 InPPDirective, Encoding, Style) {
208 OriginalPrefix = Prefix;
209 if (Token.TokenText.size() > Prefix.size() &&
210 isAlphanumeric(Token.TokenText[Prefix.size()])) {
213 else if (Prefix == "///")
218 BreakableToken::Split
219 BreakableLineComment::getSplit(unsigned LineIndex, unsigned TailOffset,
220 unsigned ColumnLimit) const {
221 return getCommentSplit(Line.substr(TailOffset), StartColumn + Prefix.size(),
222 ColumnLimit, Style.TabWidth, Encoding);
225 void BreakableLineComment::insertBreak(unsigned LineIndex, unsigned TailOffset,
227 WhitespaceManager &Whitespaces) {
228 Whitespaces.replaceWhitespaceInToken(
229 Tok, OriginalPrefix.size() + TailOffset + Split.first, Split.second,
230 Postfix, Prefix, InPPDirective, /*Newlines=*/1, IndentLevel, StartColumn);
233 void BreakableLineComment::replaceWhitespace(unsigned LineIndex,
234 unsigned TailOffset, Split Split,
235 WhitespaceManager &Whitespaces) {
236 Whitespaces.replaceWhitespaceInToken(
237 Tok, OriginalPrefix.size() + TailOffset + Split.first, Split.second, "",
238 "", /*InPPDirective=*/false, /*Newlines=*/0, /*IndentLevel=*/0,
243 BreakableLineComment::replaceWhitespaceBefore(unsigned LineIndex,
244 WhitespaceManager &Whitespaces) {
245 if (OriginalPrefix != Prefix) {
246 Whitespaces.replaceWhitespaceInToken(Tok, OriginalPrefix.size(), 0, "", "",
247 /*InPPDirective=*/false,
248 /*Newlines=*/0, /*IndentLevel=*/0,
253 BreakableBlockComment::BreakableBlockComment(
254 const FormatToken &Token, unsigned IndentLevel, unsigned StartColumn,
255 unsigned OriginalStartColumn, bool FirstInLine, bool InPPDirective,
256 encoding::Encoding Encoding, const FormatStyle &Style)
257 : BreakableToken(Token, IndentLevel, InPPDirective, Encoding, Style) {
258 StringRef TokenText(Token.TokenText);
259 assert(TokenText.startswith("/*") && TokenText.endswith("*/"));
260 TokenText.substr(2, TokenText.size() - 4).split(Lines, "\n");
262 int IndentDelta = StartColumn - OriginalStartColumn;
263 LeadingWhitespace.resize(Lines.size());
264 StartOfLineColumn.resize(Lines.size());
265 StartOfLineColumn[0] = StartColumn + 2;
266 for (size_t i = 1; i < Lines.size(); ++i)
267 adjustWhitespace(i, IndentDelta);
270 if (Lines.size() == 1 && !FirstInLine) {
271 // Comments for which FirstInLine is false can start on arbitrary column,
272 // and available horizontal space can be too small to align consecutive
273 // lines with the first one.
274 // FIXME: We could, probably, align them to current indentation level, but
275 // now we just wrap them without stars.
278 for (size_t i = 1, e = Lines.size(); i < e && !Decoration.empty(); ++i) {
279 // If the last line is empty, the closing "*/" will have a star.
280 if (i + 1 == e && Lines[i].empty())
282 while (!Lines[i].startswith(Decoration))
283 Decoration = Decoration.substr(0, Decoration.size() - 1);
286 LastLineNeedsDecoration = true;
287 IndentAtLineBreak = StartOfLineColumn[0] + 1;
288 for (size_t i = 1; i < Lines.size(); ++i) {
289 if (Lines[i].empty()) {
290 if (i + 1 == Lines.size()) {
291 // Empty last line means that we already have a star as a part of the
292 // trailing */. We also need to preserve whitespace, so that */ is
293 // correctly indented.
294 LastLineNeedsDecoration = false;
295 } else if (Decoration.empty()) {
296 // For all other lines, set the start column to 0 if they're empty, so
297 // we do not insert trailing whitespace anywhere.
298 StartOfLineColumn[i] = 0;
302 // The first line already excludes the star.
303 // For all other lines, adjust the line to exclude the star and
304 // (optionally) the first whitespace.
305 StartOfLineColumn[i] += Decoration.size();
306 Lines[i] = Lines[i].substr(Decoration.size());
307 LeadingWhitespace[i] += Decoration.size();
308 IndentAtLineBreak = std::min<int>(IndentAtLineBreak, StartOfLineColumn[i]);
310 IndentAtLineBreak = std::max<unsigned>(IndentAtLineBreak, Decoration.size());
312 llvm::dbgs() << "IndentAtLineBreak " << IndentAtLineBreak << "\n";
313 for (size_t i = 0; i < Lines.size(); ++i) {
314 llvm::dbgs() << i << " |" << Lines[i] << "| " << LeadingWhitespace[i]
320 void BreakableBlockComment::adjustWhitespace(unsigned LineIndex,
322 // When in a preprocessor directive, the trailing backslash in a block comment
323 // is not needed, but can serve a purpose of uniformity with necessary escaped
324 // newlines outside the comment. In this case we remove it here before
325 // trimming the trailing whitespace. The backslash will be re-added later when
326 // inserting a line break.
327 size_t EndOfPreviousLine = Lines[LineIndex - 1].size();
328 if (InPPDirective && Lines[LineIndex - 1].endswith("\\"))
331 // Calculate the end of the non-whitespace text in the previous line.
333 Lines[LineIndex - 1].find_last_not_of(Blanks, EndOfPreviousLine);
334 if (EndOfPreviousLine == StringRef::npos)
335 EndOfPreviousLine = 0;
338 // Calculate the start of the non-whitespace text in the current line.
339 size_t StartOfLine = Lines[LineIndex].find_first_not_of(Blanks);
340 if (StartOfLine == StringRef::npos)
341 StartOfLine = Lines[LineIndex].size();
343 StringRef Whitespace = Lines[LineIndex].substr(0, StartOfLine);
344 // Adjust Lines to only contain relevant text.
345 Lines[LineIndex - 1] = Lines[LineIndex - 1].substr(0, EndOfPreviousLine);
346 Lines[LineIndex] = Lines[LineIndex].substr(StartOfLine);
347 // Adjust LeadingWhitespace to account all whitespace between the lines
348 // to the current line.
349 LeadingWhitespace[LineIndex] =
350 Lines[LineIndex].begin() - Lines[LineIndex - 1].end();
352 // Adjust the start column uniformly across all lines.
353 StartOfLineColumn[LineIndex] = std::max<int>(
355 encoding::columnWidthWithTabs(Whitespace, 0, Style.TabWidth, Encoding) +
359 unsigned BreakableBlockComment::getLineCount() const { return Lines.size(); }
361 unsigned BreakableBlockComment::getLineLengthAfterSplit(
362 unsigned LineIndex, unsigned Offset, StringRef::size_type Length) const {
363 unsigned ContentStartColumn = getContentStartColumn(LineIndex, Offset);
364 return ContentStartColumn +
365 encoding::columnWidthWithTabs(Lines[LineIndex].substr(Offset, Length),
366 ContentStartColumn, Style.TabWidth,
368 // The last line gets a "*/" postfix.
369 (LineIndex + 1 == Lines.size() ? 2 : 0);
372 BreakableToken::Split
373 BreakableBlockComment::getSplit(unsigned LineIndex, unsigned TailOffset,
374 unsigned ColumnLimit) const {
375 return getCommentSplit(Lines[LineIndex].substr(TailOffset),
376 getContentStartColumn(LineIndex, TailOffset),
377 ColumnLimit, Style.TabWidth, Encoding);
380 void BreakableBlockComment::insertBreak(unsigned LineIndex, unsigned TailOffset,
382 WhitespaceManager &Whitespaces) {
383 StringRef Text = Lines[LineIndex].substr(TailOffset);
384 StringRef Prefix = Decoration;
385 if (LineIndex + 1 == Lines.size() &&
386 Text.size() == Split.first + Split.second) {
387 // For the last line we need to break before "*/", but not to add "* ".
391 unsigned BreakOffsetInToken =
392 Text.data() - Tok.TokenText.data() + Split.first;
393 unsigned CharsToRemove = Split.second;
394 assert(IndentAtLineBreak >= Decoration.size());
395 Whitespaces.replaceWhitespaceInToken(
396 Tok, BreakOffsetInToken, CharsToRemove, "", Prefix, InPPDirective, 1,
397 IndentLevel, IndentAtLineBreak - Decoration.size());
400 void BreakableBlockComment::replaceWhitespace(unsigned LineIndex,
401 unsigned TailOffset, Split Split,
402 WhitespaceManager &Whitespaces) {
403 StringRef Text = Lines[LineIndex].substr(TailOffset);
404 unsigned BreakOffsetInToken =
405 Text.data() - Tok.TokenText.data() + Split.first;
406 unsigned CharsToRemove = Split.second;
407 Whitespaces.replaceWhitespaceInToken(
408 Tok, BreakOffsetInToken, CharsToRemove, "", "", /*InPPDirective=*/false,
409 /*Newlines=*/0, /*IndentLevel=*/0, /*Spaces=*/1);
413 BreakableBlockComment::replaceWhitespaceBefore(unsigned LineIndex,
414 WhitespaceManager &Whitespaces) {
417 StringRef Prefix = Decoration;
418 if (Lines[LineIndex].empty()) {
419 if (LineIndex + 1 == Lines.size()) {
420 if (!LastLineNeedsDecoration) {
421 // If the last line was empty, we don't need a prefix, as the */ will
422 // line up with the decoration (if it exists).
425 } else if (!Decoration.empty()) {
426 // For other empty lines, if we do have a decoration, adapt it to not
427 // contain a trailing whitespace.
428 Prefix = Prefix.substr(0, 1);
431 if (StartOfLineColumn[LineIndex] == 1) {
432 // This line starts immediately after the decorating *.
433 Prefix = Prefix.substr(0, 1);
437 unsigned WhitespaceOffsetInToken = Lines[LineIndex].data() -
438 Tok.TokenText.data() -
439 LeadingWhitespace[LineIndex];
440 assert(StartOfLineColumn[LineIndex] >= Prefix.size());
441 Whitespaces.replaceWhitespaceInToken(
442 Tok, WhitespaceOffsetInToken, LeadingWhitespace[LineIndex], "", Prefix,
443 InPPDirective, 1, IndentLevel,
444 StartOfLineColumn[LineIndex] - Prefix.size());
448 BreakableBlockComment::getContentStartColumn(unsigned LineIndex,
449 unsigned TailOffset) const {
450 // If we break, we always break at the predefined indent.
452 return IndentAtLineBreak;
453 return StartOfLineColumn[LineIndex];
456 } // namespace format