blob: d915aef2f947e1a0c2d0d148e42e85b44ee53343 [file] [log] [blame]
Alexander Kornienko70ce7882013-04-15 14:28:00 +00001//===--- 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
Manuel Klimekde008c02013-05-27 15:23:34 +000016#define DEBUG_TYPE "format-token-breaker"
17
Alexander Kornienko70ce7882013-04-15 14:28:00 +000018#include "BreakableToken.h"
Alexander Kornienko2b2faa52013-06-11 16:01:49 +000019#include "clang/Basic/CharInfo.h"
Manuel Klimekde008c02013-05-27 15:23:34 +000020#include "clang/Format/Format.h"
Alexander Kornienko919398b2013-04-17 17:34:05 +000021#include "llvm/ADT/STLExtras.h"
Manuel Klimekde008c02013-05-27 15:23:34 +000022#include "llvm/Support/Debug.h"
Alexander Kornienko70ce7882013-04-15 14:28:00 +000023#include <algorithm>
24
25namespace clang {
26namespace format {
Manuel Klimekde008c02013-05-27 15:23:34 +000027namespace {
Alexander Kornienko70ce7882013-04-15 14:28:00 +000028
Manuel Klimekde008c02013-05-27 15:23:34 +000029BreakableToken::Split getCommentSplit(StringRef Text,
30 unsigned ContentStartColumn,
Alexander Kornienko00895102013-06-05 14:09:10 +000031 unsigned ColumnLimit,
32 encoding::Encoding Encoding) {
Alexander Kornienko919398b2013-04-17 17:34:05 +000033 if (ColumnLimit <= ContentStartColumn + 1)
Manuel Klimekde008c02013-05-27 15:23:34 +000034 return BreakableToken::Split(StringRef::npos, 0);
Alexander Kornienko919398b2013-04-17 17:34:05 +000035
36 unsigned MaxSplit = ColumnLimit - ContentStartColumn + 1;
Alexander Kornienko00895102013-06-05 14:09:10 +000037 unsigned MaxSplitBytes = 0;
38
39 for (unsigned NumChars = 0;
40 NumChars < MaxSplit && MaxSplitBytes < Text.size(); ++NumChars)
41 MaxSplitBytes +=
42 encoding::getCodePointNumBytes(Text[MaxSplitBytes], Encoding);
43
44 StringRef::size_type SpaceOffset = Text.rfind(' ', MaxSplitBytes);
Alexander Kornienko919398b2013-04-17 17:34:05 +000045 if (SpaceOffset == StringRef::npos ||
Manuel Klimekde008c02013-05-27 15:23:34 +000046 // Don't break at leading whitespace.
Manuel Klimekbe9ed772013-05-29 22:06:18 +000047 Text.find_last_not_of(' ', SpaceOffset) == StringRef::npos) {
48 // Make sure that we don't break at leading whitespace that
49 // reaches past MaxSplit.
50 StringRef::size_type FirstNonWhitespace = Text.find_first_not_of(" ");
51 if (FirstNonWhitespace == StringRef::npos)
52 // If the comment is only whitespace, we cannot split.
53 return BreakableToken::Split(StringRef::npos, 0);
54 SpaceOffset =
Alexander Kornienko00895102013-06-05 14:09:10 +000055 Text.find(' ', std::max<unsigned>(MaxSplitBytes, FirstNonWhitespace));
Manuel Klimekbe9ed772013-05-29 22:06:18 +000056 }
Alexander Kornienko919398b2013-04-17 17:34:05 +000057 if (SpaceOffset != StringRef::npos && SpaceOffset != 0) {
58 StringRef BeforeCut = Text.substr(0, SpaceOffset).rtrim();
59 StringRef AfterCut = Text.substr(SpaceOffset).ltrim();
60 return BreakableToken::Split(BeforeCut.size(),
61 AfterCut.begin() - BeforeCut.end());
62 }
63 return BreakableToken::Split(StringRef::npos, 0);
64}
65
Manuel Klimekde008c02013-05-27 15:23:34 +000066BreakableToken::Split getStringSplit(StringRef Text,
67 unsigned ContentStartColumn,
Alexander Kornienko00895102013-06-05 14:09:10 +000068 unsigned ColumnLimit,
69 encoding::Encoding Encoding) {
Manuel Klimekde008c02013-05-27 15:23:34 +000070 // FIXME: Reduce unit test case.
71 if (Text.empty())
72 return BreakableToken::Split(StringRef::npos, 0);
Alexander Kornienko00895102013-06-05 14:09:10 +000073 if (ColumnLimit <= ContentStartColumn)
Manuel Klimekde008c02013-05-27 15:23:34 +000074 return BreakableToken::Split(StringRef::npos, 0);
Alexander Kornienko00895102013-06-05 14:09:10 +000075 unsigned MaxSplit =
76 std::min<unsigned>(ColumnLimit - ContentStartColumn,
77 encoding::getCodePointCount(Text, Encoding) - 1);
78 StringRef::size_type SpaceOffset = 0;
79 StringRef::size_type SlashOffset = 0;
80 StringRef::size_type SplitPoint = 0;
81 for (unsigned Chars = 0;;) {
82 unsigned Advance;
83 if (Text[0] == '\\') {
84 Advance = encoding::getEscapeSequenceLength(Text);
85 Chars += Advance;
86 } else {
87 Advance = encoding::getCodePointNumBytes(Text[0], Encoding);
88 Chars += 1;
89 }
90
91 if (Chars > MaxSplit)
92 break;
93
94 if (Text[0] == ' ')
95 SpaceOffset = SplitPoint;
96 if (Text[0] == '/')
97 SlashOffset = SplitPoint;
98
99 SplitPoint += Advance;
100 Text = Text.substr(Advance);
101 }
102
103 if (SpaceOffset != 0)
104 return BreakableToken::Split(SpaceOffset + 1, 0);
105 if (SlashOffset != 0)
106 return BreakableToken::Split(SlashOffset + 1, 0);
107 if (SplitPoint != 0)
108 return BreakableToken::Split(SplitPoint, 0);
109 return BreakableToken::Split(StringRef::npos, 0);
Alexander Kornienko919398b2013-04-17 17:34:05 +0000110}
111
Manuel Klimekde008c02013-05-27 15:23:34 +0000112} // namespace
Alexander Kornienko70ce7882013-04-15 14:28:00 +0000113
Manuel Klimekde008c02013-05-27 15:23:34 +0000114unsigned BreakableSingleLineToken::getLineCount() const { return 1; }
Alexander Kornienko70ce7882013-04-15 14:28:00 +0000115
Alexander Kornienko2785b9a2013-06-07 16:02:52 +0000116unsigned BreakableSingleLineToken::getLineLengthAfterSplit(
117 unsigned LineIndex, unsigned Offset, StringRef::size_type Length) const {
Alexander Kornienko00895102013-06-05 14:09:10 +0000118 return StartColumn + Prefix.size() + Postfix.size() +
Alexander Kornienko2785b9a2013-06-07 16:02:52 +0000119 encoding::getCodePointCount(Line.substr(Offset, Length), Encoding);
Alexander Kornienko70ce7882013-04-15 14:28:00 +0000120}
121
Manuel Klimekde008c02013-05-27 15:23:34 +0000122BreakableSingleLineToken::BreakableSingleLineToken(const FormatToken &Tok,
123 unsigned StartColumn,
124 StringRef Prefix,
Alexander Kornienko00895102013-06-05 14:09:10 +0000125 StringRef Postfix,
126 encoding::Encoding Encoding)
127 : BreakableToken(Tok, Encoding), StartColumn(StartColumn), Prefix(Prefix),
Manuel Klimekde008c02013-05-27 15:23:34 +0000128 Postfix(Postfix) {
129 assert(Tok.TokenText.startswith(Prefix) && Tok.TokenText.endswith(Postfix));
130 Line = Tok.TokenText.substr(
131 Prefix.size(), Tok.TokenText.size() - Prefix.size() - Postfix.size());
Alexander Kornienko70ce7882013-04-15 14:28:00 +0000132}
133
Manuel Klimekde008c02013-05-27 15:23:34 +0000134BreakableStringLiteral::BreakableStringLiteral(const FormatToken &Tok,
Alexander Kornienko00895102013-06-05 14:09:10 +0000135 unsigned StartColumn,
136 encoding::Encoding Encoding)
137 : BreakableSingleLineToken(Tok, StartColumn, "\"", "\"", Encoding) {}
Manuel Klimekde008c02013-05-27 15:23:34 +0000138
139BreakableToken::Split
140BreakableStringLiteral::getSplit(unsigned LineIndex, unsigned TailOffset,
141 unsigned ColumnLimit) const {
Alexander Kornienko00895102013-06-05 14:09:10 +0000142 return getStringSplit(Line.substr(TailOffset), StartColumn + 2, ColumnLimit,
143 Encoding);
Alexander Kornienko919398b2013-04-17 17:34:05 +0000144}
145
Alexander Kornienko2b2faa52013-06-11 16:01:49 +0000146void BreakableStringLiteral::insertBreak(unsigned LineIndex,
147 unsigned TailOffset, Split Split,
148 bool InPPDirective,
149 WhitespaceManager &Whitespaces) {
150 Whitespaces.replaceWhitespaceInToken(
151 Tok, Prefix.size() + TailOffset + Split.first, Split.second, Postfix,
152 Prefix, InPPDirective, 1, StartColumn);
153}
154
Manuel Klimekde008c02013-05-27 15:23:34 +0000155static StringRef getLineCommentPrefix(StringRef Comment) {
Alexander Kornienko919398b2013-04-17 17:34:05 +0000156 const char *KnownPrefixes[] = { "/// ", "///", "// ", "//" };
Manuel Klimekde008c02013-05-27 15:23:34 +0000157 for (size_t i = 0, e = llvm::array_lengthof(KnownPrefixes); i != e; ++i)
Alexander Kornienko919398b2013-04-17 17:34:05 +0000158 if (Comment.startswith(KnownPrefixes[i]))
159 return KnownPrefixes[i];
160 return "";
161}
162
Manuel Klimekde008c02013-05-27 15:23:34 +0000163BreakableLineComment::BreakableLineComment(const FormatToken &Token,
Alexander Kornienko00895102013-06-05 14:09:10 +0000164 unsigned StartColumn,
165 encoding::Encoding Encoding)
Manuel Klimekde008c02013-05-27 15:23:34 +0000166 : BreakableSingleLineToken(Token, StartColumn,
Alexander Kornienko00895102013-06-05 14:09:10 +0000167 getLineCommentPrefix(Token.TokenText), "",
Alexander Kornienko2b2faa52013-06-11 16:01:49 +0000168 Encoding) {
169 OriginalPrefix = Prefix;
170 if (Token.TokenText.size() > Prefix.size() &&
171 isAlphanumeric(Token.TokenText[Prefix.size()])) {
172 if (Prefix == "//")
173 Prefix = "// ";
174 else if (Prefix == "///")
175 Prefix = "/// ";
176 }
177}
Manuel Klimekde008c02013-05-27 15:23:34 +0000178
179BreakableToken::Split
180BreakableLineComment::getSplit(unsigned LineIndex, unsigned TailOffset,
181 unsigned ColumnLimit) const {
182 return getCommentSplit(Line.substr(TailOffset), StartColumn + Prefix.size(),
Alexander Kornienko00895102013-06-05 14:09:10 +0000183 ColumnLimit, Encoding);
Manuel Klimekde008c02013-05-27 15:23:34 +0000184}
185
Alexander Kornienko2b2faa52013-06-11 16:01:49 +0000186void BreakableLineComment::insertBreak(unsigned LineIndex, unsigned TailOffset,
187 Split Split, bool InPPDirective,
188 WhitespaceManager &Whitespaces) {
189 Whitespaces.replaceWhitespaceInToken(
190 Tok, OriginalPrefix.size() + TailOffset + Split.first, Split.second,
191 Postfix, Prefix, InPPDirective, 1, StartColumn);
192}
193
194void
195BreakableLineComment::replaceWhitespaceBefore(unsigned LineIndex,
196 unsigned InPPDirective,
197 WhitespaceManager &Whitespaces) {
198 if (OriginalPrefix != Prefix) {
199 Whitespaces.replaceWhitespaceInToken(Tok, OriginalPrefix.size(), 0, "", "",
200 false, 0, 1);
201 }
202}
203
Alexander Kornienko00895102013-06-05 14:09:10 +0000204BreakableBlockComment::BreakableBlockComment(
205 const FormatStyle &Style, const FormatToken &Token, unsigned StartColumn,
206 unsigned OriginalStartColumn, bool FirstInLine, encoding::Encoding Encoding)
207 : BreakableToken(Token, Encoding) {
Manuel Klimekde008c02013-05-27 15:23:34 +0000208 StringRef TokenText(Token.TokenText);
209 assert(TokenText.startswith("/*") && TokenText.endswith("*/"));
210 TokenText.substr(2, TokenText.size() - 4).split(Lines, "\n");
211
212 int IndentDelta = StartColumn - OriginalStartColumn;
213 bool NeedsStar = true;
214 LeadingWhitespace.resize(Lines.size());
215 StartOfLineColumn.resize(Lines.size());
216 if (Lines.size() == 1 && !FirstInLine) {
217 // Comments for which FirstInLine is false can start on arbitrary column,
218 // and available horizontal space can be too small to align consecutive
219 // lines with the first one.
220 // FIXME: We could, probably, align them to current indentation level, but
221 // now we just wrap them without stars.
222 NeedsStar = false;
223 }
224 StartOfLineColumn[0] = StartColumn + 2;
225 for (size_t i = 1; i < Lines.size(); ++i) {
226 adjustWhitespace(Style, i, IndentDelta);
227 if (Lines[i].empty())
228 // If the last line is empty, the closing "*/" will have a star.
229 NeedsStar = NeedsStar && i + 1 == Lines.size();
230 else
231 NeedsStar = NeedsStar && Lines[i][0] == '*';
232 }
233 Decoration = NeedsStar ? "* " : "";
234 IndentAtLineBreak = StartOfLineColumn[0] + 1;
235 for (size_t i = 1; i < Lines.size(); ++i) {
236 if (Lines[i].empty()) {
237 if (!NeedsStar && i + 1 != Lines.size())
238 // For all but the last line (which always ends in */), set the
239 // start column to 0 if they're empty, so we do not insert
240 // trailing whitespace anywhere.
241 StartOfLineColumn[i] = 0;
242 continue;
243 }
244 if (NeedsStar) {
245 // The first line already excludes the star.
246 // For all other lines, adjust the line to exclude the star and
247 // (optionally) the first whitespace.
248 int Offset = Lines[i].startswith("* ") ? 2 : 1;
249 StartOfLineColumn[i] += Offset;
250 Lines[i] = Lines[i].substr(Offset);
251 LeadingWhitespace[i] += Offset;
252 }
253 IndentAtLineBreak = std::min<int>(IndentAtLineBreak, StartOfLineColumn[i]);
254 }
Daniel Jaspercb4b40b2013-05-30 17:27:48 +0000255 IndentAtLineBreak = std::max<unsigned>(IndentAtLineBreak, Decoration.size());
Manuel Klimekde008c02013-05-27 15:23:34 +0000256 DEBUG({
257 for (size_t i = 0; i < Lines.size(); ++i) {
258 llvm::dbgs() << i << " |" << Lines[i] << "| " << LeadingWhitespace[i]
259 << "\n";
260 }
261 });
262}
263
264void BreakableBlockComment::adjustWhitespace(const FormatStyle &Style,
265 unsigned LineIndex,
266 int IndentDelta) {
267 // Calculate the end of the non-whitespace text in the previous line.
268 size_t EndOfPreviousLine = Lines[LineIndex - 1].find_last_not_of(" \\\t");
269 if (EndOfPreviousLine == StringRef::npos)
270 EndOfPreviousLine = 0;
271 else
272 ++EndOfPreviousLine;
273 // Calculate the start of the non-whitespace text in the current line.
274 size_t StartOfLine = Lines[LineIndex].find_first_not_of(" \t");
275 if (StartOfLine == StringRef::npos)
276 StartOfLine = Lines[LineIndex].size();
Manuel Klimekde008c02013-05-27 15:23:34 +0000277
278 // Adjust Lines to only contain relevant text.
279 Lines[LineIndex - 1] = Lines[LineIndex - 1].substr(0, EndOfPreviousLine);
280 Lines[LineIndex] = Lines[LineIndex].substr(StartOfLine);
281 // Adjust LeadingWhitespace to account all whitespace between the lines
282 // to the current line.
283 LeadingWhitespace[LineIndex] =
284 Lines[LineIndex].begin() - Lines[LineIndex - 1].end();
Manuel Klimekd63312b2013-05-28 10:01:59 +0000285
286 // FIXME: We currently count tabs as 1 character. To solve this, we need to
287 // get the correct indentation width of the start of the comment, which
288 // requires correct counting of the tab expansions before the comment, and
289 // a configurable tab width. Since the current implementation only breaks
290 // if leading tabs are intermixed with spaces, that is not a high priority.
291
Manuel Klimekde008c02013-05-27 15:23:34 +0000292 // Adjust the start column uniformly accross all lines.
Manuel Klimekd63312b2013-05-28 10:01:59 +0000293 StartOfLineColumn[LineIndex] = std::max<int>(0, StartOfLine + IndentDelta);
Manuel Klimekde008c02013-05-27 15:23:34 +0000294}
295
296unsigned BreakableBlockComment::getLineCount() const { return Lines.size(); }
297
Alexander Kornienko2785b9a2013-06-07 16:02:52 +0000298unsigned BreakableBlockComment::getLineLengthAfterSplit(
299 unsigned LineIndex, unsigned Offset, StringRef::size_type Length) const {
300 return getContentStartColumn(LineIndex, Offset) +
301 encoding::getCodePointCount(Lines[LineIndex].substr(Offset, Length),
Alexander Kornienko00895102013-06-05 14:09:10 +0000302 Encoding) +
Manuel Klimekde008c02013-05-27 15:23:34 +0000303 // The last line gets a "*/" postfix.
304 (LineIndex + 1 == Lines.size() ? 2 : 0);
305}
306
307BreakableToken::Split
308BreakableBlockComment::getSplit(unsigned LineIndex, unsigned TailOffset,
309 unsigned ColumnLimit) const {
310 return getCommentSplit(Lines[LineIndex].substr(TailOffset),
311 getContentStartColumn(LineIndex, TailOffset),
Alexander Kornienko00895102013-06-05 14:09:10 +0000312 ColumnLimit, Encoding);
Manuel Klimekde008c02013-05-27 15:23:34 +0000313}
314
315void BreakableBlockComment::insertBreak(unsigned LineIndex, unsigned TailOffset,
316 Split Split, bool InPPDirective,
317 WhitespaceManager &Whitespaces) {
318 StringRef Text = Lines[LineIndex].substr(TailOffset);
319 StringRef Prefix = Decoration;
320 if (LineIndex + 1 == Lines.size() &&
321 Text.size() == Split.first + Split.second) {
322 // For the last line we need to break before "*/", but not to add "* ".
323 Prefix = "";
324 }
325
326 unsigned BreakOffsetInToken =
327 Text.data() - Tok.TokenText.data() + Split.first;
328 unsigned CharsToRemove = Split.second;
Manuel Klimekb6dba332013-05-30 07:45:53 +0000329 assert(IndentAtLineBreak >= Decoration.size());
Alexander Kornienko2b2faa52013-06-11 16:01:49 +0000330 Whitespaces.replaceWhitespaceInToken(Tok, BreakOffsetInToken, CharsToRemove,
331 "", Prefix, InPPDirective, 1,
332 IndentAtLineBreak - Decoration.size());
Manuel Klimekde008c02013-05-27 15:23:34 +0000333}
334
335void
336BreakableBlockComment::replaceWhitespaceBefore(unsigned LineIndex,
337 unsigned InPPDirective,
338 WhitespaceManager &Whitespaces) {
339 if (LineIndex == 0)
340 return;
341 StringRef Prefix = Decoration;
Manuel Klimekc5cc4bf2013-05-28 08:55:01 +0000342 if (Lines[LineIndex].empty()) {
343 if (LineIndex + 1 == Lines.size()) {
344 // If the last line is empty, we don't need a prefix, as the */ will line
345 // up with the decoration (if it exists).
346 Prefix = "";
347 } else if (!Decoration.empty()) {
348 // For other empty lines, if we do have a decoration, adapt it to not
349 // contain a trailing whitespace.
350 Prefix = Prefix.substr(0, 1);
351 }
Daniel Jaspere2c482f2013-05-30 06:40:07 +0000352 } else {
353 if (StartOfLineColumn[LineIndex] == 1) {
354 // This lines starts immediately after the decorating *.
355 Prefix = Prefix.substr(0, 1);
356 }
Manuel Klimekc5cc4bf2013-05-28 08:55:01 +0000357 }
Manuel Klimekde008c02013-05-27 15:23:34 +0000358
359 unsigned WhitespaceOffsetInToken =
360 Lines[LineIndex].data() - Tok.TokenText.data() -
361 LeadingWhitespace[LineIndex];
Manuel Klimekb6dba332013-05-30 07:45:53 +0000362 assert(StartOfLineColumn[LineIndex] >= Prefix.size());
Alexander Kornienko2b2faa52013-06-11 16:01:49 +0000363 Whitespaces.replaceWhitespaceInToken(
Manuel Klimekde008c02013-05-27 15:23:34 +0000364 Tok, WhitespaceOffsetInToken, LeadingWhitespace[LineIndex], "", Prefix,
Alexander Kornienko2b2faa52013-06-11 16:01:49 +0000365 InPPDirective, 1, StartOfLineColumn[LineIndex] - Prefix.size());
Manuel Klimekde008c02013-05-27 15:23:34 +0000366}
367
368unsigned
369BreakableBlockComment::getContentStartColumn(unsigned LineIndex,
370 unsigned TailOffset) const {
371 // If we break, we always break at the predefined indent.
372 if (TailOffset != 0)
373 return IndentAtLineBreak;
374 return StartOfLineColumn[LineIndex];
375}
376
Alexander Kornienko70ce7882013-04-15 14:28:00 +0000377} // namespace format
378} // namespace clang