blob: 72d2078797e5ab474ecbb1654a85db0fd3f221e3 [file] [log] [blame]
Alexander Kornienkocb45bc12013-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
16#include "BreakableToken.h"
Krasimir Georgiev91834222017-01-25 13:58:58 +000017#include "ContinuationIndenter.h"
Alexander Kornienko555efc32013-06-11 16:01:49 +000018#include "clang/Basic/CharInfo.h"
Manuel Klimek9043c742013-05-27 15:23:34 +000019#include "clang/Format/Format.h"
Alexander Kornienko9e90b622013-04-17 17:34:05 +000020#include "llvm/ADT/STLExtras.h"
Manuel Klimek9043c742013-05-27 15:23:34 +000021#include "llvm/Support/Debug.h"
Alexander Kornienkocb45bc12013-04-15 14:28:00 +000022#include <algorithm>
23
Chandler Carruth10346662014-04-22 03:17:02 +000024#define DEBUG_TYPE "format-token-breaker"
25
Alexander Kornienkocb45bc12013-04-15 14:28:00 +000026namespace clang {
27namespace format {
28
Daniel Jasper580da272013-10-30 07:36:40 +000029static const char *const Blanks = " \t\v\f\r";
Alexander Kornienkob93062e2013-06-20 13:58:37 +000030static bool IsBlank(char C) {
31 switch (C) {
Daniel Jasper3ac9b9e2013-07-08 14:34:09 +000032 case ' ':
33 case '\t':
34 case '\v':
35 case '\f':
Daniel Jasper580da272013-10-30 07:36:40 +000036 case '\r':
Daniel Jasper3ac9b9e2013-07-08 14:34:09 +000037 return true;
38 default:
39 return false;
Alexander Kornienkob93062e2013-06-20 13:58:37 +000040 }
41}
42
Krasimir Georgiev410ed242017-11-10 12:50:09 +000043static StringRef getLineCommentIndentPrefix(StringRef Comment,
44 const FormatStyle &Style) {
45 static const char *const KnownCStylePrefixes[] = {"///<", "//!<", "///", "//",
46 "//!"};
47 static const char *const KnownTextProtoPrefixes[] = {"//", "#"};
48 ArrayRef<const char *> KnownPrefixes(KnownCStylePrefixes);
49 if (Style.Language == FormatStyle::LK_TextProto)
50 KnownPrefixes = KnownTextProtoPrefixes;
51
Krasimir Georgiev91834222017-01-25 13:58:58 +000052 StringRef LongestPrefix;
53 for (StringRef KnownPrefix : KnownPrefixes) {
54 if (Comment.startswith(KnownPrefix)) {
55 size_t PrefixLength = KnownPrefix.size();
56 while (PrefixLength < Comment.size() && Comment[PrefixLength] == ' ')
57 ++PrefixLength;
58 if (PrefixLength > LongestPrefix.size())
59 LongestPrefix = Comment.substr(0, PrefixLength);
60 }
61 }
62 return LongestPrefix;
63}
64
Craig Topperbfb5c402013-07-01 03:38:29 +000065static BreakableToken::Split getCommentSplit(StringRef Text,
66 unsigned ContentStartColumn,
67 unsigned ColumnLimit,
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +000068 unsigned TabWidth,
Craig Topperbfb5c402013-07-01 03:38:29 +000069 encoding::Encoding Encoding) {
Manuel Klimek93699f42017-11-29 14:29:43 +000070 DEBUG(llvm::dbgs() << "Comment split: \"" << Text << ", " << ColumnLimit
71 << "\", Content start: " << ContentStartColumn << "\n");
Alexander Kornienko9e90b622013-04-17 17:34:05 +000072 if (ColumnLimit <= ContentStartColumn + 1)
Manuel Klimek9043c742013-05-27 15:23:34 +000073 return BreakableToken::Split(StringRef::npos, 0);
Alexander Kornienko9e90b622013-04-17 17:34:05 +000074
75 unsigned MaxSplit = ColumnLimit - ContentStartColumn + 1;
Alexander Kornienkoffcc0102013-06-05 14:09:10 +000076 unsigned MaxSplitBytes = 0;
77
78 for (unsigned NumChars = 0;
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +000079 NumChars < MaxSplit && MaxSplitBytes < Text.size();) {
80 unsigned BytesInChar =
Alexander Kornienkoffcc0102013-06-05 14:09:10 +000081 encoding::getCodePointNumBytes(Text[MaxSplitBytes], Encoding);
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +000082 NumChars +=
83 encoding::columnWidthWithTabs(Text.substr(MaxSplitBytes, BytesInChar),
84 ContentStartColumn, TabWidth, Encoding);
85 MaxSplitBytes += BytesInChar;
86 }
Alexander Kornienkoffcc0102013-06-05 14:09:10 +000087
Alexander Kornienkob93062e2013-06-20 13:58:37 +000088 StringRef::size_type SpaceOffset = Text.find_last_of(Blanks, MaxSplitBytes);
Francois Ferranda881be82017-05-22 14:47:17 +000089
90 // Do not split before a number followed by a dot: this would be interpreted
91 // as a numbered list, which would prevent re-flowing in subsequent passes.
92 static llvm::Regex kNumberedListRegexp = llvm::Regex("^[1-9][0-9]?\\.");
93 if (SpaceOffset != StringRef::npos &&
94 kNumberedListRegexp.match(Text.substr(SpaceOffset).ltrim(Blanks)))
95 SpaceOffset = Text.find_last_of(Blanks, SpaceOffset);
96
Alexander Kornienko9e90b622013-04-17 17:34:05 +000097 if (SpaceOffset == StringRef::npos ||
Manuel Klimek9043c742013-05-27 15:23:34 +000098 // Don't break at leading whitespace.
Alexander Kornienkob93062e2013-06-20 13:58:37 +000099 Text.find_last_not_of(Blanks, SpaceOffset) == StringRef::npos) {
Manuel Klimekae1fbfb2013-05-29 22:06:18 +0000100 // Make sure that we don't break at leading whitespace that
101 // reaches past MaxSplit.
Alexander Kornienkob93062e2013-06-20 13:58:37 +0000102 StringRef::size_type FirstNonWhitespace = Text.find_first_not_of(Blanks);
Manuel Klimekae1fbfb2013-05-29 22:06:18 +0000103 if (FirstNonWhitespace == StringRef::npos)
104 // If the comment is only whitespace, we cannot split.
105 return BreakableToken::Split(StringRef::npos, 0);
Alexander Kornienkob93062e2013-06-20 13:58:37 +0000106 SpaceOffset = Text.find_first_of(
107 Blanks, std::max<unsigned>(MaxSplitBytes, FirstNonWhitespace));
Manuel Klimekae1fbfb2013-05-29 22:06:18 +0000108 }
Alexander Kornienko9e90b622013-04-17 17:34:05 +0000109 if (SpaceOffset != StringRef::npos && SpaceOffset != 0) {
Alexander Kornienkob93062e2013-06-20 13:58:37 +0000110 StringRef BeforeCut = Text.substr(0, SpaceOffset).rtrim(Blanks);
111 StringRef AfterCut = Text.substr(SpaceOffset).ltrim(Blanks);
Alexander Kornienko9e90b622013-04-17 17:34:05 +0000112 return BreakableToken::Split(BeforeCut.size(),
113 AfterCut.begin() - BeforeCut.end());
114 }
115 return BreakableToken::Split(StringRef::npos, 0);
116}
117
Daniel Jasperb05a81d2014-05-09 13:11:16 +0000118static BreakableToken::Split
119getStringSplit(StringRef Text, unsigned UsedColumns, unsigned ColumnLimit,
120 unsigned TabWidth, encoding::Encoding Encoding) {
Manuel Klimek9043c742013-05-27 15:23:34 +0000121 // FIXME: Reduce unit test case.
122 if (Text.empty())
123 return BreakableToken::Split(StringRef::npos, 0);
Alexander Kornienko81e32942013-09-16 20:20:49 +0000124 if (ColumnLimit <= UsedColumns)
Manuel Klimek9043c742013-05-27 15:23:34 +0000125 return BreakableToken::Split(StringRef::npos, 0);
Alexander Kornienko71d95d62013-11-26 10:38:53 +0000126 unsigned MaxSplit = ColumnLimit - UsedColumns;
Alexander Kornienkoffcc0102013-06-05 14:09:10 +0000127 StringRef::size_type SpaceOffset = 0;
128 StringRef::size_type SlashOffset = 0;
Alexander Kornienko72852072013-06-19 14:22:47 +0000129 StringRef::size_type WordStartOffset = 0;
Alexander Kornienkoffcc0102013-06-05 14:09:10 +0000130 StringRef::size_type SplitPoint = 0;
131 for (unsigned Chars = 0;;) {
132 unsigned Advance;
133 if (Text[0] == '\\') {
134 Advance = encoding::getEscapeSequenceLength(Text);
135 Chars += Advance;
136 } else {
137 Advance = encoding::getCodePointNumBytes(Text[0], Encoding);
Alexander Kornienko81e32942013-09-16 20:20:49 +0000138 Chars += encoding::columnWidthWithTabs(
139 Text.substr(0, Advance), UsedColumns + Chars, TabWidth, Encoding);
Alexander Kornienkoffcc0102013-06-05 14:09:10 +0000140 }
141
Daniel Jaspere4b48c62015-01-21 19:50:35 +0000142 if (Chars > MaxSplit || Text.size() <= Advance)
Alexander Kornienkoffcc0102013-06-05 14:09:10 +0000143 break;
144
Alexander Kornienkob93062e2013-06-20 13:58:37 +0000145 if (IsBlank(Text[0]))
Alexander Kornienkoffcc0102013-06-05 14:09:10 +0000146 SpaceOffset = SplitPoint;
147 if (Text[0] == '/')
148 SlashOffset = SplitPoint;
Alexander Kornienkob93062e2013-06-20 13:58:37 +0000149 if (Advance == 1 && !isAlphanumeric(Text[0]))
Alexander Kornienko72852072013-06-19 14:22:47 +0000150 WordStartOffset = SplitPoint;
Alexander Kornienkoffcc0102013-06-05 14:09:10 +0000151
152 SplitPoint += Advance;
153 Text = Text.substr(Advance);
154 }
155
156 if (SpaceOffset != 0)
157 return BreakableToken::Split(SpaceOffset + 1, 0);
158 if (SlashOffset != 0)
159 return BreakableToken::Split(SlashOffset + 1, 0);
Alexander Kornienko72852072013-06-19 14:22:47 +0000160 if (WordStartOffset != 0)
161 return BreakableToken::Split(WordStartOffset + 1, 0);
Alexander Kornienkoffcc0102013-06-05 14:09:10 +0000162 if (SplitPoint != 0)
163 return BreakableToken::Split(SplitPoint, 0);
164 return BreakableToken::Split(StringRef::npos, 0);
Alexander Kornienko9e90b622013-04-17 17:34:05 +0000165}
166
Krasimir Georgiev91834222017-01-25 13:58:58 +0000167bool switchesFormatting(const FormatToken &Token) {
168 assert((Token.is(TT_BlockComment) || Token.is(TT_LineComment)) &&
169 "formatting regions are switched by comment tokens");
170 StringRef Content = Token.TokenText.substr(2).ltrim();
171 return Content.startswith("clang-format on") ||
172 Content.startswith("clang-format off");
173}
174
175unsigned
Manuel Klimek93699f42017-11-29 14:29:43 +0000176BreakableToken::getLengthAfterCompression(unsigned RemainingTokenColumns,
Krasimir Georgiev91834222017-01-25 13:58:58 +0000177 Split Split) const {
178 // Example: consider the content
179 // lala lala
180 // - RemainingTokenColumns is the original number of columns, 10;
181 // - Split is (4, 2), denoting the two spaces between the two words;
182 //
183 // We compute the number of columns when the split is compressed into a single
184 // space, like:
185 // lala lala
Manuel Klimek93699f42017-11-29 14:29:43 +0000186 //
187 // FIXME: Correctly measure the length of whitespace in Split.second so it
188 // works with tabs.
Krasimir Georgiev91834222017-01-25 13:58:58 +0000189 return RemainingTokenColumns + 1 - Split.second;
190}
191
Manuel Klimek93699f42017-11-29 14:29:43 +0000192unsigned BreakableStringLiteral::getLineCount() const { return 1; }
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000193
Manuel Klimek93699f42017-11-29 14:29:43 +0000194unsigned BreakableStringLiteral::getRangeLength(unsigned LineIndex,
195 unsigned Offset,
196 StringRef::size_type Length,
197 unsigned StartColumn) const {
Manuel Klimek477f3692017-11-29 15:09:12 +0000198 llvm_unreachable("Getting the length of a part of the string literal "
199 "indicates that the code tries to reflow it.");
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000200}
201
Manuel Klimek93699f42017-11-29 14:29:43 +0000202unsigned
203BreakableStringLiteral::getRemainingLength(unsigned LineIndex, unsigned Offset,
204 unsigned StartColumn) const {
205 return UnbreakableTailLength + Postfix.size() +
206 encoding::columnWidthWithTabs(Line.substr(Offset, StringRef::npos),
207 StartColumn, Style.TabWidth, Encoding);
208}
209
210unsigned BreakableStringLiteral::getContentStartColumn(unsigned LineIndex,
211 bool Break) const {
212 return StartColumn + Prefix.size();
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000213}
214
Alexander Kornienko81e32942013-09-16 20:20:49 +0000215BreakableStringLiteral::BreakableStringLiteral(
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000216 const FormatToken &Tok, unsigned StartColumn, StringRef Prefix,
Krasimir Georgiev55c23a12018-01-23 11:26:19 +0000217 StringRef Postfix, unsigned UnbreakableTailLength, bool InPPDirective,
218 encoding::Encoding Encoding, const FormatStyle &Style)
Manuel Klimek93699f42017-11-29 14:29:43 +0000219 : BreakableToken(Tok, InPPDirective, Encoding, Style),
220 StartColumn(StartColumn), Prefix(Prefix), Postfix(Postfix),
Krasimir Georgiev55c23a12018-01-23 11:26:19 +0000221 UnbreakableTailLength(UnbreakableTailLength) {
Manuel Klimek93699f42017-11-29 14:29:43 +0000222 assert(Tok.TokenText.startswith(Prefix) && Tok.TokenText.endswith(Postfix));
223 Line = Tok.TokenText.substr(
224 Prefix.size(), Tok.TokenText.size() - Prefix.size() - Postfix.size());
225}
Manuel Klimek9043c742013-05-27 15:23:34 +0000226
Manuel Klimek93699f42017-11-29 14:29:43 +0000227BreakableToken::Split BreakableStringLiteral::getSplit(
228 unsigned LineIndex, unsigned TailOffset, unsigned ColumnLimit,
229 unsigned ContentStartColumn, llvm::Regex &CommentPragmasRegex) const {
230 return getStringSplit(Line.substr(TailOffset), ContentStartColumn,
231 ColumnLimit - Postfix.size(), Style.TabWidth, Encoding);
Alexander Kornienko9e90b622013-04-17 17:34:05 +0000232}
233
Alexander Kornienko555efc32013-06-11 16:01:49 +0000234void BreakableStringLiteral::insertBreak(unsigned LineIndex,
235 unsigned TailOffset, Split Split,
Manuel Klimek93699f42017-11-29 14:29:43 +0000236 WhitespaceManager &Whitespaces) const {
Alexander Kornienko555efc32013-06-11 16:01:49 +0000237 Whitespaces.replaceWhitespaceInToken(
238 Tok, Prefix.size() + TailOffset + Split.first, Split.second, Postfix,
Alexander Kornienkod4fa2e62017-04-11 09:55:00 +0000239 Prefix, InPPDirective, 1, StartColumn);
Alexander Kornienko555efc32013-06-11 16:01:49 +0000240}
241
Krasimir Georgiev91834222017-01-25 13:58:58 +0000242BreakableComment::BreakableComment(const FormatToken &Token,
Manuel Klimek89628f62017-09-20 09:51:03 +0000243 unsigned StartColumn, bool InPPDirective,
Krasimir Georgiev91834222017-01-25 13:58:58 +0000244 encoding::Encoding Encoding,
245 const FormatStyle &Style)
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000246 : BreakableToken(Token, InPPDirective, Encoding, Style),
Krasimir Georgiev4b159222017-02-21 10:54:50 +0000247 StartColumn(StartColumn) {}
Manuel Klimek9043c742013-05-27 15:23:34 +0000248
Krasimir Georgiev91834222017-01-25 13:58:58 +0000249unsigned BreakableComment::getLineCount() const { return Lines.size(); }
250
Krasimir Georgiev17725d82017-03-08 08:55:12 +0000251BreakableToken::Split
252BreakableComment::getSplit(unsigned LineIndex, unsigned TailOffset,
Manuel Klimek93699f42017-11-29 14:29:43 +0000253 unsigned ColumnLimit, unsigned ContentStartColumn,
Krasimir Georgiev17725d82017-03-08 08:55:12 +0000254 llvm::Regex &CommentPragmasRegex) const {
255 // Don't break lines matching the comment pragmas regex.
256 if (CommentPragmasRegex.match(Content[LineIndex]))
257 return Split(StringRef::npos, 0);
Krasimir Georgiev91834222017-01-25 13:58:58 +0000258 return getCommentSplit(Content[LineIndex].substr(TailOffset),
Manuel Klimek93699f42017-11-29 14:29:43 +0000259 ContentStartColumn, ColumnLimit, Style.TabWidth,
260 Encoding);
Manuel Klimek9043c742013-05-27 15:23:34 +0000261}
262
Manuel Klimek93699f42017-11-29 14:29:43 +0000263void BreakableComment::compressWhitespace(
264 unsigned LineIndex, unsigned TailOffset, Split Split,
265 WhitespaceManager &Whitespaces) const {
Krasimir Georgiev91834222017-01-25 13:58:58 +0000266 StringRef Text = Content[LineIndex].substr(TailOffset);
267 // Text is relative to the content line, but Whitespaces operates relative to
268 // the start of the corresponding token, so compute the start of the Split
269 // that needs to be compressed into a single space relative to the start of
270 // its token.
271 unsigned BreakOffsetInToken =
272 Text.data() - tokenAt(LineIndex).TokenText.data() + Split.first;
273 unsigned CharsToRemove = Split.second;
Alexander Kornienko555efc32013-06-11 16:01:49 +0000274 Whitespaces.replaceWhitespaceInToken(
Krasimir Georgiev91834222017-01-25 13:58:58 +0000275 tokenAt(LineIndex), BreakOffsetInToken, CharsToRemove, "", "",
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000276 /*InPPDirective=*/false, /*Newlines=*/0, /*Spaces=*/1);
Alexander Kornienko875395f2013-11-12 17:50:13 +0000277}
278
Krasimir Georgiev91834222017-01-25 13:58:58 +0000279const FormatToken &BreakableComment::tokenAt(unsigned LineIndex) const {
280 return Tokens[LineIndex] ? *Tokens[LineIndex] : Tok;
281}
282
283static bool mayReflowContent(StringRef Content) {
284 Content = Content.trim(Blanks);
Krasimir Georgiev28912c02017-02-02 10:52:08 +0000285 // Lines starting with '@' commonly have special meaning.
Francois Ferranda881be82017-05-22 14:47:17 +0000286 // Lines starting with '-', '-#', '+' or '*' are bulleted/numbered lists.
287 static const SmallVector<StringRef, 8> kSpecialMeaningPrefixes = {
Manuel Klimek89628f62017-09-20 09:51:03 +0000288 "@", "TODO", "FIXME", "XXX", "-# ", "- ", "+ ", "* "};
Krasimir Georgiev28912c02017-02-02 10:52:08 +0000289 bool hasSpecialMeaningPrefix = false;
290 for (StringRef Prefix : kSpecialMeaningPrefixes) {
291 if (Content.startswith(Prefix)) {
292 hasSpecialMeaningPrefix = true;
293 break;
294 }
295 }
Francois Ferranda881be82017-05-22 14:47:17 +0000296
297 // Numbered lists may also start with a number followed by '.'
298 // To avoid issues if a line starts with a number which is actually the end
299 // of a previous line, we only consider numbers with up to 2 digits.
300 static llvm::Regex kNumberedListRegexp = llvm::Regex("^[1-9][0-9]?\\. ");
Manuel Klimek89628f62017-09-20 09:51:03 +0000301 hasSpecialMeaningPrefix =
302 hasSpecialMeaningPrefix || kNumberedListRegexp.match(Content);
Francois Ferranda881be82017-05-22 14:47:17 +0000303
Krasimir Georgiev91834222017-01-25 13:58:58 +0000304 // Simple heuristic for what to reflow: content should contain at least two
305 // characters and either the first or second character must be
306 // non-punctuation.
Krasimir Georgiev28912c02017-02-02 10:52:08 +0000307 return Content.size() >= 2 && !hasSpecialMeaningPrefix &&
308 !Content.endswith("\\") &&
Krasimir Georgiev91834222017-01-25 13:58:58 +0000309 // Note that this is UTF-8 safe, since if isPunctuation(Content[0]) is
310 // true, then the first code point must be 1 byte long.
311 (!isPunctuation(Content[0]) || !isPunctuation(Content[1]));
312}
313
Alexander Kornienkoffcc0102013-06-05 14:09:10 +0000314BreakableBlockComment::BreakableBlockComment(
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000315 const FormatToken &Token, unsigned StartColumn,
Alexander Kornienkobe633902013-06-14 11:46:10 +0000316 unsigned OriginalStartColumn, bool FirstInLine, bool InPPDirective,
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +0000317 encoding::Encoding Encoding, const FormatStyle &Style)
Krasimir Georgiev22d7e6b2017-07-20 22:29:39 +0000318 : BreakableComment(Token, StartColumn, InPPDirective, Encoding, Style),
Manuel Klimek48c930c2017-12-04 08:53:16 +0000319 DelimitersOnNewline(false),
320 UnbreakableTailLength(Token.UnbreakableTailLength) {
Krasimir Georgiev91834222017-01-25 13:58:58 +0000321 assert(Tok.is(TT_BlockComment) &&
322 "block comment section must start with a block comment");
323
324 StringRef TokenText(Tok.TokenText);
Manuel Klimek9043c742013-05-27 15:23:34 +0000325 assert(TokenText.startswith("/*") && TokenText.endswith("*/"));
326 TokenText.substr(2, TokenText.size() - 4).split(Lines, "\n");
327
328 int IndentDelta = StartColumn - OriginalStartColumn;
Krasimir Georgiev91834222017-01-25 13:58:58 +0000329 Content.resize(Lines.size());
330 Content[0] = Lines[0];
331 ContentColumn.resize(Lines.size());
332 // Account for the initial '/*'.
333 ContentColumn[0] = StartColumn + 2;
334 Tokens.resize(Lines.size());
Alexander Kornienko614d96a2013-07-08 14:12:07 +0000335 for (size_t i = 1; i < Lines.size(); ++i)
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +0000336 adjustWhitespace(i, IndentDelta);
Alexander Kornienko614d96a2013-07-08 14:12:07 +0000337
Krasimir Georgievbb99a362017-02-16 12:39:31 +0000338 // Align decorations with the column of the star on the first line,
339 // that is one column after the start "/*".
340 DecorationColumn = StartColumn + 1;
341
342 // Account for comment decoration patterns like this:
343 //
344 // /*
345 // ** blah blah blah
346 // */
347 if (Lines.size() >= 2 && Content[1].startswith("**") &&
348 static_cast<unsigned>(ContentColumn[1]) == StartColumn) {
349 DecorationColumn = StartColumn;
350 }
351
Alexander Kornienko614d96a2013-07-08 14:12:07 +0000352 Decoration = "* ";
Manuel Klimek9043c742013-05-27 15:23:34 +0000353 if (Lines.size() == 1 && !FirstInLine) {
354 // Comments for which FirstInLine is false can start on arbitrary column,
355 // and available horizontal space can be too small to align consecutive
356 // lines with the first one.
357 // FIXME: We could, probably, align them to current indentation level, but
358 // now we just wrap them without stars.
Alexander Kornienko614d96a2013-07-08 14:12:07 +0000359 Decoration = "";
Manuel Klimek9043c742013-05-27 15:23:34 +0000360 }
Alexander Kornienko614d96a2013-07-08 14:12:07 +0000361 for (size_t i = 1, e = Lines.size(); i < e && !Decoration.empty(); ++i) {
362 // If the last line is empty, the closing "*/" will have a star.
Krasimir Georgiev91834222017-01-25 13:58:58 +0000363 if (i + 1 == e && Content[i].empty())
Alexander Kornienko614d96a2013-07-08 14:12:07 +0000364 break;
Manuel Klimek89628f62017-09-20 09:51:03 +0000365 if (!Content[i].empty() && i + 1 != e && Decoration.startswith(Content[i]))
Daniel Jasper6d9b88d2015-05-06 07:17:22 +0000366 continue;
Krasimir Georgiev91834222017-01-25 13:58:58 +0000367 while (!Content[i].startswith(Decoration))
Alexander Kornienko614d96a2013-07-08 14:12:07 +0000368 Decoration = Decoration.substr(0, Decoration.size() - 1);
Manuel Klimek9043c742013-05-27 15:23:34 +0000369 }
Alexander Kornienko614d96a2013-07-08 14:12:07 +0000370
371 LastLineNeedsDecoration = true;
Krasimir Georgiev91834222017-01-25 13:58:58 +0000372 IndentAtLineBreak = ContentColumn[0] + 1;
373 for (size_t i = 1, e = Lines.size(); i < e; ++i) {
374 if (Content[i].empty()) {
375 if (i + 1 == e) {
Alexander Kornienko614d96a2013-07-08 14:12:07 +0000376 // Empty last line means that we already have a star as a part of the
377 // trailing */. We also need to preserve whitespace, so that */ is
378 // correctly indented.
379 LastLineNeedsDecoration = false;
Krasimir Georgievbb99a362017-02-16 12:39:31 +0000380 // Align the star in the last '*/' with the stars on the previous lines.
381 if (e >= 2 && !Decoration.empty()) {
382 ContentColumn[i] = DecorationColumn;
383 }
Alexander Kornienko614d96a2013-07-08 14:12:07 +0000384 } else if (Decoration.empty()) {
385 // For all other lines, set the start column to 0 if they're empty, so
386 // we do not insert trailing whitespace anywhere.
Krasimir Georgiev91834222017-01-25 13:58:58 +0000387 ContentColumn[i] = 0;
Alexander Kornienko614d96a2013-07-08 14:12:07 +0000388 }
Manuel Klimek9043c742013-05-27 15:23:34 +0000389 continue;
390 }
Daniel Jasper6d9b88d2015-05-06 07:17:22 +0000391
Alexander Kornienko614d96a2013-07-08 14:12:07 +0000392 // The first line already excludes the star.
Krasimir Georgievbb99a362017-02-16 12:39:31 +0000393 // The last line excludes the star if LastLineNeedsDecoration is false.
Alexander Kornienko614d96a2013-07-08 14:12:07 +0000394 // For all other lines, adjust the line to exclude the star and
395 // (optionally) the first whitespace.
Krasimir Georgiev91834222017-01-25 13:58:58 +0000396 unsigned DecorationSize = Decoration.startswith(Content[i])
397 ? Content[i].size()
398 : Decoration.size();
Krasimir Georgievbb99a362017-02-16 12:39:31 +0000399 if (DecorationSize) {
400 ContentColumn[i] = DecorationColumn + DecorationSize;
401 }
Krasimir Georgiev91834222017-01-25 13:58:58 +0000402 Content[i] = Content[i].substr(DecorationSize);
403 if (!Decoration.startswith(Content[i]))
Daniel Jasper6d9b88d2015-05-06 07:17:22 +0000404 IndentAtLineBreak =
Krasimir Georgiev91834222017-01-25 13:58:58 +0000405 std::min<int>(IndentAtLineBreak, std::max(0, ContentColumn[i]));
Manuel Klimek9043c742013-05-27 15:23:34 +0000406 }
Manuel Klimek89628f62017-09-20 09:51:03 +0000407 IndentAtLineBreak = std::max<unsigned>(IndentAtLineBreak, Decoration.size());
Krasimir Georgiev91834222017-01-25 13:58:58 +0000408
Krasimir Georgiev22d7e6b2017-07-20 22:29:39 +0000409 // Detect a multiline jsdoc comment and set DelimitersOnNewline in that case.
410 if (Style.Language == FormatStyle::LK_JavaScript ||
411 Style.Language == FormatStyle::LK_Java) {
412 if ((Lines[0] == "*" || Lines[0].startswith("* ")) && Lines.size() > 1) {
413 // This is a multiline jsdoc comment.
414 DelimitersOnNewline = true;
415 } else if (Lines[0].startswith("* ") && Lines.size() == 1) {
416 // Detect a long single-line comment, like:
417 // /** long long long */
418 // Below, '2' is the width of '*/'.
Manuel Klimek89628f62017-09-20 09:51:03 +0000419 unsigned EndColumn =
420 ContentColumn[0] +
421 encoding::columnWidthWithTabs(Lines[0], ContentColumn[0],
422 Style.TabWidth, Encoding) +
423 2;
Krasimir Georgiev22d7e6b2017-07-20 22:29:39 +0000424 DelimitersOnNewline = EndColumn > Style.ColumnLimit;
425 }
426 }
427
Manuel Klimek9043c742013-05-27 15:23:34 +0000428 DEBUG({
Alexander Kornienko614d96a2013-07-08 14:12:07 +0000429 llvm::dbgs() << "IndentAtLineBreak " << IndentAtLineBreak << "\n";
Krasimir Georgiev22d7e6b2017-07-20 22:29:39 +0000430 llvm::dbgs() << "DelimitersOnNewline " << DelimitersOnNewline << "\n";
Manuel Klimek9043c742013-05-27 15:23:34 +0000431 for (size_t i = 0; i < Lines.size(); ++i) {
Krasimir Georgiev91834222017-01-25 13:58:58 +0000432 llvm::dbgs() << i << " |" << Content[i] << "| "
Krasimir Georgievbb99a362017-02-16 12:39:31 +0000433 << "CC=" << ContentColumn[i] << "| "
434 << "IN=" << (Content[i].data() - Lines[i].data()) << "\n";
Manuel Klimek9043c742013-05-27 15:23:34 +0000435 }
436 });
437}
438
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +0000439void BreakableBlockComment::adjustWhitespace(unsigned LineIndex,
Manuel Klimek9043c742013-05-27 15:23:34 +0000440 int IndentDelta) {
Alexander Kornienkobe633902013-06-14 11:46:10 +0000441 // When in a preprocessor directive, the trailing backslash in a block comment
442 // is not needed, but can serve a purpose of uniformity with necessary escaped
443 // newlines outside the comment. In this case we remove it here before
444 // trimming the trailing whitespace. The backslash will be re-added later when
445 // inserting a line break.
446 size_t EndOfPreviousLine = Lines[LineIndex - 1].size();
447 if (InPPDirective && Lines[LineIndex - 1].endswith("\\"))
448 --EndOfPreviousLine;
449
Manuel Klimek9043c742013-05-27 15:23:34 +0000450 // Calculate the end of the non-whitespace text in the previous line.
Alexander Kornienkobe633902013-06-14 11:46:10 +0000451 EndOfPreviousLine =
Alexander Kornienkob93062e2013-06-20 13:58:37 +0000452 Lines[LineIndex - 1].find_last_not_of(Blanks, EndOfPreviousLine);
Manuel Klimek9043c742013-05-27 15:23:34 +0000453 if (EndOfPreviousLine == StringRef::npos)
454 EndOfPreviousLine = 0;
455 else
456 ++EndOfPreviousLine;
457 // Calculate the start of the non-whitespace text in the current line.
Alexander Kornienkob93062e2013-06-20 13:58:37 +0000458 size_t StartOfLine = Lines[LineIndex].find_first_not_of(Blanks);
Manuel Klimek9043c742013-05-27 15:23:34 +0000459 if (StartOfLine == StringRef::npos)
Daniel Jasperd6e61882015-06-17 12:23:15 +0000460 StartOfLine = Lines[LineIndex].rtrim("\r\n").size();
Manuel Klimek9043c742013-05-27 15:23:34 +0000461
Alexander Kornienkoebb43ca2013-09-05 14:08:34 +0000462 StringRef Whitespace = Lines[LineIndex].substr(0, StartOfLine);
Manuel Klimek9043c742013-05-27 15:23:34 +0000463 // Adjust Lines to only contain relevant text.
Krasimir Georgiev91834222017-01-25 13:58:58 +0000464 size_t PreviousContentOffset =
465 Content[LineIndex - 1].data() - Lines[LineIndex - 1].data();
466 Content[LineIndex - 1] = Lines[LineIndex - 1].substr(
467 PreviousContentOffset, EndOfPreviousLine - PreviousContentOffset);
468 Content[LineIndex] = Lines[LineIndex].substr(StartOfLine);
Manuel Klimek34d15152013-05-28 10:01:59 +0000469
Alp Tokerf6a24ce2013-12-05 16:25:25 +0000470 // Adjust the start column uniformly across all lines.
Krasimir Georgiev91834222017-01-25 13:58:58 +0000471 ContentColumn[LineIndex] =
Alexander Kornienko39856b72013-09-10 09:38:25 +0000472 encoding::columnWidthWithTabs(Whitespace, 0, Style.TabWidth, Encoding) +
Alexander Kornienko67d9c8c2014-04-17 16:12:46 +0000473 IndentDelta;
Manuel Klimek9043c742013-05-27 15:23:34 +0000474}
475
Manuel Klimek93699f42017-11-29 14:29:43 +0000476unsigned BreakableBlockComment::getRangeLength(unsigned LineIndex,
477 unsigned Offset,
478 StringRef::size_type Length,
479 unsigned StartColumn) const {
Krasimir Georgiev91834222017-01-25 13:58:58 +0000480 unsigned LineLength =
Manuel Klimek93699f42017-11-29 14:29:43 +0000481 encoding::columnWidthWithTabs(Content[LineIndex].substr(Offset, Length),
482 StartColumn, Style.TabWidth, Encoding);
483 // FIXME: This should go into getRemainingLength instead, but we currently
484 // break tests when putting it there. Investigate how to fix those tests.
Krasimir Georgiev91834222017-01-25 13:58:58 +0000485 // The last line gets a "*/" postfix.
486 if (LineIndex + 1 == Lines.size()) {
487 LineLength += 2;
488 // We never need a decoration when breaking just the trailing "*/" postfix.
489 // Note that checking that Length == 0 is not enough, since Length could
490 // also be StringRef::npos.
Manuel Klimek93699f42017-11-29 14:29:43 +0000491 if (Content[LineIndex].substr(Offset, StringRef::npos).empty()) {
Krasimir Georgiev91834222017-01-25 13:58:58 +0000492 LineLength -= Decoration.size();
493 }
494 }
495 return LineLength;
Manuel Klimek9043c742013-05-27 15:23:34 +0000496}
497
Manuel Klimek93699f42017-11-29 14:29:43 +0000498unsigned BreakableBlockComment::getRemainingLength(unsigned LineIndex,
499 unsigned Offset,
500 unsigned StartColumn) const {
Manuel Klimek48c930c2017-12-04 08:53:16 +0000501 return UnbreakableTailLength +
502 getRangeLength(LineIndex, Offset, StringRef::npos, StartColumn);
Manuel Klimek93699f42017-11-29 14:29:43 +0000503}
504
505unsigned BreakableBlockComment::getContentStartColumn(unsigned LineIndex,
506 bool Break) const {
507 if (Break)
508 return IndentAtLineBreak;
509 return std::max(0, ContentColumn[LineIndex]);
510}
511
Manuel Klimek9043c742013-05-27 15:23:34 +0000512void BreakableBlockComment::insertBreak(unsigned LineIndex, unsigned TailOffset,
Alexander Kornienkobe633902013-06-14 11:46:10 +0000513 Split Split,
Manuel Klimek93699f42017-11-29 14:29:43 +0000514 WhitespaceManager &Whitespaces) const {
Krasimir Georgiev91834222017-01-25 13:58:58 +0000515 StringRef Text = Content[LineIndex].substr(TailOffset);
Manuel Klimek9043c742013-05-27 15:23:34 +0000516 StringRef Prefix = Decoration;
Krasimir Georgiev91834222017-01-25 13:58:58 +0000517 // We need this to account for the case when we have a decoration "* " for all
518 // the lines except for the last one, where the star in "*/" acts as a
519 // decoration.
520 unsigned LocalIndentAtLineBreak = IndentAtLineBreak;
Manuel Klimek9043c742013-05-27 15:23:34 +0000521 if (LineIndex + 1 == Lines.size() &&
522 Text.size() == Split.first + Split.second) {
523 // For the last line we need to break before "*/", but not to add "* ".
524 Prefix = "";
Krasimir Georgiev91834222017-01-25 13:58:58 +0000525 if (LocalIndentAtLineBreak >= 2)
526 LocalIndentAtLineBreak -= 2;
527 }
528 // The split offset is from the beginning of the line. Convert it to an offset
529 // from the beginning of the token text.
530 unsigned BreakOffsetInToken =
531 Text.data() - tokenAt(LineIndex).TokenText.data() + Split.first;
532 unsigned CharsToRemove = Split.second;
533 assert(LocalIndentAtLineBreak >= Prefix.size());
534 Whitespaces.replaceWhitespaceInToken(
535 tokenAt(LineIndex), BreakOffsetInToken, CharsToRemove, "", Prefix,
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000536 InPPDirective, /*Newlines=*/1,
Krasimir Georgiev91834222017-01-25 13:58:58 +0000537 /*Spaces=*/LocalIndentAtLineBreak - Prefix.size());
538}
539
Manuel Klimek93699f42017-11-29 14:29:43 +0000540BreakableToken::Split
541BreakableBlockComment::getReflowSplit(unsigned LineIndex,
542 llvm::Regex &CommentPragmasRegex) const {
Krasimir Georgiev00c5c722017-02-02 15:32:19 +0000543 if (!mayReflow(LineIndex, CommentPragmasRegex))
Krasimir Georgiev91834222017-01-25 13:58:58 +0000544 return Split(StringRef::npos, 0);
Krasimir Georgiev91834222017-01-25 13:58:58 +0000545
Manuel Klimek93699f42017-11-29 14:29:43 +0000546 size_t Trimmed = Content[LineIndex].find_first_not_of(Blanks);
547 return Split(0, Trimmed != StringRef::npos ? Trimmed : 0);
Krasimir Georgiev91834222017-01-25 13:58:58 +0000548}
Krasimir Georgiev22d7e6b2017-07-20 22:29:39 +0000549
Manuel Klimek77866142017-11-17 11:17:15 +0000550bool BreakableBlockComment::introducesBreakBeforeToken() const {
Krasimir Georgiev35599fd2017-10-16 09:08:53 +0000551 // A break is introduced when we want delimiters on newline.
Manuel Klimek77866142017-11-17 11:17:15 +0000552 return DelimitersOnNewline &&
Krasimir Georgiev35599fd2017-10-16 09:08:53 +0000553 Lines[0].substr(1).find_first_not_of(Blanks) != StringRef::npos;
554}
555
Manuel Klimek93699f42017-11-29 14:29:43 +0000556void BreakableBlockComment::reflow(unsigned LineIndex,
557 WhitespaceManager &Whitespaces) const {
558 StringRef TrimmedContent = Content[LineIndex].ltrim(Blanks);
559 // Here we need to reflow.
560 assert(Tokens[LineIndex - 1] == Tokens[LineIndex] &&
561 "Reflowing whitespace within a token");
562 // This is the offset of the end of the last line relative to the start of
563 // the token text in the token.
564 unsigned WhitespaceOffsetInToken = Content[LineIndex - 1].data() +
565 Content[LineIndex - 1].size() -
566 tokenAt(LineIndex).TokenText.data();
567 unsigned WhitespaceLength = TrimmedContent.data() -
568 tokenAt(LineIndex).TokenText.data() -
569 WhitespaceOffsetInToken;
570 Whitespaces.replaceWhitespaceInToken(
571 tokenAt(LineIndex), WhitespaceOffsetInToken,
572 /*ReplaceChars=*/WhitespaceLength, /*PreviousPostfix=*/"",
573 /*CurrentPrefix=*/ReflowPrefix, InPPDirective, /*Newlines=*/0,
574 /*Spaces=*/0);
575}
576
577void BreakableBlockComment::adaptStartOfLine(
578 unsigned LineIndex, WhitespaceManager &Whitespaces) const {
Krasimir Georgiev22d7e6b2017-07-20 22:29:39 +0000579 if (LineIndex == 0) {
580 if (DelimitersOnNewline) {
Manuel Klimek93699f42017-11-29 14:29:43 +0000581 // Since we're breaking at index 1 below, the break position and the
Manuel Klimek89628f62017-09-20 09:51:03 +0000582 // break length are the same.
583 size_t BreakLength = Lines[0].substr(1).find_first_not_of(Blanks);
Manuel Klimek93699f42017-11-29 14:29:43 +0000584 if (BreakLength != StringRef::npos)
Manuel Klimek89628f62017-09-20 09:51:03 +0000585 insertBreak(LineIndex, 0, Split(1, BreakLength), Whitespaces);
Krasimir Georgiev22d7e6b2017-07-20 22:29:39 +0000586 }
587 return;
588 }
Krasimir Georgiev91834222017-01-25 13:58:58 +0000589 // Here no reflow with the previous line will happen.
590 // Fix the decoration of the line at LineIndex.
Manuel Klimek9043c742013-05-27 15:23:34 +0000591 StringRef Prefix = Decoration;
Krasimir Georgiev91834222017-01-25 13:58:58 +0000592 if (Content[LineIndex].empty()) {
Manuel Klimek281dcbe2013-05-28 08:55:01 +0000593 if (LineIndex + 1 == Lines.size()) {
Alexander Kornienko614d96a2013-07-08 14:12:07 +0000594 if (!LastLineNeedsDecoration) {
595 // If the last line was empty, we don't need a prefix, as the */ will
596 // line up with the decoration (if it exists).
597 Prefix = "";
598 }
Manuel Klimek281dcbe2013-05-28 08:55:01 +0000599 } else if (!Decoration.empty()) {
600 // For other empty lines, if we do have a decoration, adapt it to not
601 // contain a trailing whitespace.
602 Prefix = Prefix.substr(0, 1);
603 }
Daniel Jasper51fb2b22013-05-30 06:40:07 +0000604 } else {
Krasimir Georgiev91834222017-01-25 13:58:58 +0000605 if (ContentColumn[LineIndex] == 1) {
Alexander Kornienko614d96a2013-07-08 14:12:07 +0000606 // This line starts immediately after the decorating *.
Daniel Jasper51fb2b22013-05-30 06:40:07 +0000607 Prefix = Prefix.substr(0, 1);
608 }
Manuel Klimek281dcbe2013-05-28 08:55:01 +0000609 }
Krasimir Georgiev91834222017-01-25 13:58:58 +0000610 // This is the offset of the end of the last line relative to the start of the
611 // token text in the token.
612 unsigned WhitespaceOffsetInToken = Content[LineIndex - 1].data() +
613 Content[LineIndex - 1].size() -
614 tokenAt(LineIndex).TokenText.data();
615 unsigned WhitespaceLength = Content[LineIndex].data() -
616 tokenAt(LineIndex).TokenText.data() -
617 WhitespaceOffsetInToken;
Alexander Kornienko555efc32013-06-11 16:01:49 +0000618 Whitespaces.replaceWhitespaceInToken(
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000619 tokenAt(LineIndex), WhitespaceOffsetInToken, WhitespaceLength, "", Prefix,
620 InPPDirective, /*Newlines=*/1, ContentColumn[LineIndex] - Prefix.size());
Manuel Klimek9043c742013-05-27 15:23:34 +0000621}
622
Krasimir Georgiev3b865342017-08-09 09:42:32 +0000623BreakableToken::Split
Manuel Klimek93699f42017-11-29 14:29:43 +0000624BreakableBlockComment::getSplitAfterLastLine(unsigned TailOffset) const {
Krasimir Georgiev3b865342017-08-09 09:42:32 +0000625 if (DelimitersOnNewline) {
626 // Replace the trailing whitespace of the last line with a newline.
627 // In case the last line is empty, the ending '*/' is already on its own
628 // line.
629 StringRef Line = Content.back().substr(TailOffset);
630 StringRef TrimmedLine = Line.rtrim(Blanks);
631 if (!TrimmedLine.empty())
632 return Split(TrimmedLine.size(), Line.size() - TrimmedLine.size());
633 }
Krasimir Georgiev22d7e6b2017-07-20 22:29:39 +0000634 return Split(StringRef::npos, 0);
635}
636
Krasimir Georgiev00c5c722017-02-02 15:32:19 +0000637bool BreakableBlockComment::mayReflow(unsigned LineIndex,
638 llvm::Regex &CommentPragmasRegex) const {
639 // Content[LineIndex] may exclude the indent after the '*' decoration. In that
640 // case, we compute the start of the comment pragma manually.
641 StringRef IndentContent = Content[LineIndex];
642 if (Lines[LineIndex].ltrim(Blanks).startswith("*")) {
643 IndentContent = Lines[LineIndex].ltrim(Blanks).substr(1);
644 }
645 return LineIndex > 0 && !CommentPragmasRegex.match(IndentContent) &&
646 mayReflowContent(Content[LineIndex]) && !Tok.Finalized &&
647 !switchesFormatting(tokenAt(LineIndex));
648}
649
Krasimir Georgiev91834222017-01-25 13:58:58 +0000650BreakableLineCommentSection::BreakableLineCommentSection(
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000651 const FormatToken &Token, unsigned StartColumn,
Krasimir Georgiev91834222017-01-25 13:58:58 +0000652 unsigned OriginalStartColumn, bool FirstInLine, bool InPPDirective,
653 encoding::Encoding Encoding, const FormatStyle &Style)
Krasimir Georgiev4b159222017-02-21 10:54:50 +0000654 : BreakableComment(Token, StartColumn, InPPDirective, Encoding, Style) {
Krasimir Georgiev91834222017-01-25 13:58:58 +0000655 assert(Tok.is(TT_LineComment) &&
656 "line comment section must start with a line comment");
657 FormatToken *LineTok = nullptr;
658 for (const FormatToken *CurrentTok = &Tok;
659 CurrentTok && CurrentTok->is(TT_LineComment);
660 CurrentTok = CurrentTok->Next) {
661 LastLineTok = LineTok;
662 StringRef TokenText(CurrentTok->TokenText);
Krasimir Georgiev410ed242017-11-10 12:50:09 +0000663 assert((TokenText.startswith("//") || TokenText.startswith("#")) &&
664 "unsupported line comment prefix, '//' and '#' are supported");
Krasimir Georgiev91834222017-01-25 13:58:58 +0000665 size_t FirstLineIndex = Lines.size();
666 TokenText.split(Lines, "\n");
667 Content.resize(Lines.size());
668 ContentColumn.resize(Lines.size());
669 OriginalContentColumn.resize(Lines.size());
670 Tokens.resize(Lines.size());
671 Prefix.resize(Lines.size());
672 OriginalPrefix.resize(Lines.size());
673 for (size_t i = FirstLineIndex, e = Lines.size(); i < e; ++i) {
Manuel Klimek45ab5592017-11-14 09:19:53 +0000674 Lines[i] = Lines[i].ltrim(Blanks);
Krasimir Georgieve518e0b2017-01-30 21:00:01 +0000675 // We need to trim the blanks in case this is not the first line in a
676 // multiline comment. Then the indent is included in Lines[i].
677 StringRef IndentPrefix =
Krasimir Georgiev410ed242017-11-10 12:50:09 +0000678 getLineCommentIndentPrefix(Lines[i].ltrim(Blanks), Style);
679 assert((TokenText.startswith("//") || TokenText.startswith("#")) &&
680 "unsupported line comment prefix, '//' and '#' are supported");
Krasimir Georgiev91834222017-01-25 13:58:58 +0000681 OriginalPrefix[i] = Prefix[i] = IndentPrefix;
682 if (Lines[i].size() > Prefix[i].size() &&
683 isAlphanumeric(Lines[i][Prefix[i].size()])) {
684 if (Prefix[i] == "//")
685 Prefix[i] = "// ";
686 else if (Prefix[i] == "///")
687 Prefix[i] = "/// ";
688 else if (Prefix[i] == "//!")
689 Prefix[i] = "//! ";
Krasimir Georgievba6b3152017-05-18 07:36:21 +0000690 else if (Prefix[i] == "///<")
691 Prefix[i] = "///< ";
692 else if (Prefix[i] == "//!<")
693 Prefix[i] = "//!< ";
Krasimir Georgiev410ed242017-11-10 12:50:09 +0000694 else if (Prefix[i] == "#" &&
695 Style.Language == FormatStyle::LK_TextProto)
696 Prefix[i] = "# ";
Krasimir Georgiev91834222017-01-25 13:58:58 +0000697 }
698
699 Tokens[i] = LineTok;
700 Content[i] = Lines[i].substr(IndentPrefix.size());
701 OriginalContentColumn[i] =
Manuel Klimek89628f62017-09-20 09:51:03 +0000702 StartColumn + encoding::columnWidthWithTabs(OriginalPrefix[i],
703 StartColumn,
704 Style.TabWidth, Encoding);
Krasimir Georgiev91834222017-01-25 13:58:58 +0000705 ContentColumn[i] =
Manuel Klimek89628f62017-09-20 09:51:03 +0000706 StartColumn + encoding::columnWidthWithTabs(Prefix[i], StartColumn,
707 Style.TabWidth, Encoding);
Krasimir Georgiev91834222017-01-25 13:58:58 +0000708
709 // Calculate the end of the non-whitespace text in this line.
710 size_t EndOfLine = Content[i].find_last_not_of(Blanks);
711 if (EndOfLine == StringRef::npos)
712 EndOfLine = Content[i].size();
713 else
714 ++EndOfLine;
715 Content[i] = Content[i].substr(0, EndOfLine);
716 }
717 LineTok = CurrentTok->Next;
Krasimir Georgievb6ccd382017-02-02 14:36:50 +0000718 if (CurrentTok->Next && !CurrentTok->Next->ContinuesLineCommentSection) {
Krasimir Georgiev753625b2017-01-31 13:32:38 +0000719 // A line comment section needs to broken by a line comment that is
720 // preceded by at least two newlines. Note that we put this break here
721 // instead of breaking at a previous stage during parsing, since that
722 // would split the contents of the enum into two unwrapped lines in this
723 // example, which is undesirable:
724 // enum A {
725 // a, // comment about a
726 //
727 // // comment about b
728 // b
729 // };
730 //
731 // FIXME: Consider putting separate line comment sections as children to
732 // the unwrapped line instead.
733 break;
734 }
Krasimir Georgiev91834222017-01-25 13:58:58 +0000735 }
736}
737
Manuel Klimek93699f42017-11-29 14:29:43 +0000738unsigned
739BreakableLineCommentSection::getRangeLength(unsigned LineIndex, unsigned Offset,
740 StringRef::size_type Length,
741 unsigned StartColumn) const {
742 return encoding::columnWidthWithTabs(
743 Content[LineIndex].substr(Offset, Length), StartColumn, Style.TabWidth,
744 Encoding);
Krasimir Georgiev91834222017-01-25 13:58:58 +0000745}
746
Manuel Klimek93699f42017-11-29 14:29:43 +0000747unsigned BreakableLineCommentSection::getContentStartColumn(unsigned LineIndex,
748 bool Break) const {
749 if (Break)
750 return OriginalContentColumn[LineIndex];
751 return ContentColumn[LineIndex];
752}
753
754void BreakableLineCommentSection::insertBreak(
755 unsigned LineIndex, unsigned TailOffset, Split Split,
756 WhitespaceManager &Whitespaces) const {
Krasimir Georgiev91834222017-01-25 13:58:58 +0000757 StringRef Text = Content[LineIndex].substr(TailOffset);
758 // Compute the offset of the split relative to the beginning of the token
759 // text.
760 unsigned BreakOffsetInToken =
761 Text.data() - tokenAt(LineIndex).TokenText.data() + Split.first;
762 unsigned CharsToRemove = Split.second;
763 // Compute the size of the new indent, including the size of the new prefix of
764 // the newly broken line.
765 unsigned IndentAtLineBreak = OriginalContentColumn[LineIndex] +
766 Prefix[LineIndex].size() -
767 OriginalPrefix[LineIndex].size();
768 assert(IndentAtLineBreak >= Prefix[LineIndex].size());
769 Whitespaces.replaceWhitespaceInToken(
770 tokenAt(LineIndex), BreakOffsetInToken, CharsToRemove, "",
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000771 Prefix[LineIndex], InPPDirective, /*Newlines=*/1,
Krasimir Georgiev91834222017-01-25 13:58:58 +0000772 /*Spaces=*/IndentAtLineBreak - Prefix[LineIndex].size());
773}
774
Manuel Klimek93699f42017-11-29 14:29:43 +0000775BreakableComment::Split BreakableLineCommentSection::getReflowSplit(
776 unsigned LineIndex, llvm::Regex &CommentPragmasRegex) const {
Krasimir Georgiev00c5c722017-02-02 15:32:19 +0000777 if (!mayReflow(LineIndex, CommentPragmasRegex))
778 return Split(StringRef::npos, 0);
Manuel Klimek93699f42017-11-29 14:29:43 +0000779
780 size_t Trimmed = Content[LineIndex].find_first_not_of(Blanks);
781
782 // In a line comment section each line is a separate token; thus, after a
783 // split we replace all whitespace before the current line comment token
784 // (which does not need to be included in the split), plus the start of the
785 // line up to where the content starts.
786 return Split(0, Trimmed != StringRef::npos ? Trimmed : 0);
Krasimir Georgiev91834222017-01-25 13:58:58 +0000787}
788
Manuel Klimek93699f42017-11-29 14:29:43 +0000789void BreakableLineCommentSection::reflow(unsigned LineIndex,
790 WhitespaceManager &Whitespaces) const {
791 // Reflow happens between tokens. Replace the whitespace between the
792 // tokens by the empty string.
793 Whitespaces.replaceWhitespace(
794 *Tokens[LineIndex], /*Newlines=*/0, /*Spaces=*/0,
795 /*StartOfTokenColumn=*/StartColumn, /*InPPDirective=*/false);
796 // Replace the indent and prefix of the token with the reflow prefix.
797 unsigned WhitespaceLength =
798 Content[LineIndex].data() - tokenAt(LineIndex).TokenText.data();
799 Whitespaces.replaceWhitespaceInToken(*Tokens[LineIndex],
800 /*Offset=*/0,
801 /*ReplaceChars=*/WhitespaceLength,
802 /*PreviousPostfix=*/"",
803 /*CurrentPrefix=*/ReflowPrefix,
804 /*InPPDirective=*/false,
805 /*Newlines=*/0,
806 /*Spaces=*/0);
Krasimir Georgiev91834222017-01-25 13:58:58 +0000807}
808
Manuel Klimek93699f42017-11-29 14:29:43 +0000809void BreakableLineCommentSection::adaptStartOfLine(
810 unsigned LineIndex, WhitespaceManager &Whitespaces) const {
Krasimir Georgiev91834222017-01-25 13:58:58 +0000811 // If this is the first line of a token, we need to inform Whitespace Manager
812 // about it: either adapt the whitespace range preceding it, or mark it as an
813 // untouchable token.
814 // This happens for instance here:
815 // // line 1 \
816 // // line 2
817 if (LineIndex > 0 && Tokens[LineIndex] != Tokens[LineIndex - 1]) {
Manuel Klimek93699f42017-11-29 14:29:43 +0000818 // This is the first line for the current token, but no reflow with the
819 // previous token is necessary. However, we still may need to adjust the
820 // start column. Note that ContentColumn[LineIndex] is the expected
821 // content column after a possible update to the prefix, hence the prefix
822 // length change is included.
823 unsigned LineColumn =
824 ContentColumn[LineIndex] -
825 (Content[LineIndex].data() - Lines[LineIndex].data()) +
826 (OriginalPrefix[LineIndex].size() - Prefix[LineIndex].size());
Krasimir Georgiev13dbaa02017-02-01 10:10:04 +0000827
Manuel Klimek93699f42017-11-29 14:29:43 +0000828 // We always want to create a replacement instead of adding an untouchable
829 // token, even if LineColumn is the same as the original column of the
830 // token. This is because WhitespaceManager doesn't align trailing
831 // comments if they are untouchable.
832 Whitespaces.replaceWhitespace(*Tokens[LineIndex],
833 /*Newlines=*/1,
834 /*Spaces=*/LineColumn,
835 /*StartOfTokenColumn=*/LineColumn,
836 /*InPPDirective=*/false);
Krasimir Georgievb796ceb2017-01-31 15:40:15 +0000837 }
838 if (OriginalPrefix[LineIndex] != Prefix[LineIndex]) {
839 // Adjust the prefix if necessary.
Krasimir Georgiev91834222017-01-25 13:58:58 +0000840
841 // Take care of the space possibly introduced after a decoration.
842 assert(Prefix[LineIndex] == (OriginalPrefix[LineIndex] + " ").str() &&
Krasimir Georgievb796ceb2017-01-31 15:40:15 +0000843 "Expecting a line comment prefix to differ from original by at most "
844 "a space");
Krasimir Georgiev91834222017-01-25 13:58:58 +0000845 Whitespaces.replaceWhitespaceInToken(
846 tokenAt(LineIndex), OriginalPrefix[LineIndex].size(), 0, "", "",
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000847 /*InPPDirective=*/false, /*Newlines=*/0, /*Spaces=*/1);
Krasimir Georgiev91834222017-01-25 13:58:58 +0000848 }
Krasimir Georgiev91834222017-01-25 13:58:58 +0000849}
850
Manuel Klimek89628f62017-09-20 09:51:03 +0000851void BreakableLineCommentSection::updateNextToken(LineState &State) const {
Krasimir Georgiev91834222017-01-25 13:58:58 +0000852 if (LastLineTok) {
853 State.NextToken = LastLineTok->Next;
854 }
855}
856
Krasimir Georgiev00c5c722017-02-02 15:32:19 +0000857bool BreakableLineCommentSection::mayReflow(
858 unsigned LineIndex, llvm::Regex &CommentPragmasRegex) const {
859 // Line comments have the indent as part of the prefix, so we need to
860 // recompute the start of the line.
861 StringRef IndentContent = Content[LineIndex];
862 if (Lines[LineIndex].startswith("//")) {
863 IndentContent = Lines[LineIndex].substr(2);
864 }
Manuel Klimek93699f42017-11-29 14:29:43 +0000865 // FIXME: Decide whether we want to reflow non-regular indents:
866 // Currently, we only reflow when the OriginalPrefix[LineIndex] matches the
867 // OriginalPrefix[LineIndex-1]. That means we don't reflow
868 // // text that protrudes
869 // // into text with different indent
870 // We do reflow in that case in block comments.
Krasimir Georgiev00c5c722017-02-02 15:32:19 +0000871 return LineIndex > 0 && !CommentPragmasRegex.match(IndentContent) &&
872 mayReflowContent(Content[LineIndex]) && !Tok.Finalized &&
873 !switchesFormatting(tokenAt(LineIndex)) &&
874 OriginalPrefix[LineIndex] == OriginalPrefix[LineIndex - 1];
875}
876
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000877} // namespace format
878} // namespace clang