/src/llvm-project/clang/lib/Format/BreakableToken.cpp
Line | Count | Source (jump to first uncovered line) |
1 | | //===--- BreakableToken.cpp - Format C++ code -----------------------------===// |
2 | | // |
3 | | // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. |
4 | | // See https://llvm.org/LICENSE.txt for license information. |
5 | | // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
6 | | // |
7 | | //===----------------------------------------------------------------------===// |
8 | | /// |
9 | | /// \file |
10 | | /// Contains implementation of BreakableToken class and classes derived |
11 | | /// from it. |
12 | | /// |
13 | | //===----------------------------------------------------------------------===// |
14 | | |
15 | | #include "BreakableToken.h" |
16 | | #include "ContinuationIndenter.h" |
17 | | #include "clang/Basic/CharInfo.h" |
18 | | #include "clang/Format/Format.h" |
19 | | #include "llvm/ADT/STLExtras.h" |
20 | | #include "llvm/Support/Debug.h" |
21 | | #include <algorithm> |
22 | | |
23 | | #define DEBUG_TYPE "format-token-breaker" |
24 | | |
25 | | namespace clang { |
26 | | namespace format { |
27 | | |
28 | | static constexpr StringRef Blanks = " \t\v\f\r"; |
29 | 26.9M | static bool IsBlank(char C) { |
30 | 26.9M | switch (C) { |
31 | 163k | case ' ': |
32 | 164k | case '\t': |
33 | 164k | case '\v': |
34 | 164k | case '\f': |
35 | 164k | case '\r': |
36 | 164k | return true; |
37 | 26.7M | default: |
38 | 26.7M | return false; |
39 | 26.9M | } |
40 | 26.9M | } |
41 | | |
42 | | static StringRef getLineCommentIndentPrefix(StringRef Comment, |
43 | 21.8k | const FormatStyle &Style) { |
44 | 21.8k | static constexpr StringRef KnownCStylePrefixes[] = {"///<", "//!<", "///", |
45 | 21.8k | "//!", "//:", "//"}; |
46 | 21.8k | static constexpr StringRef KnownTextProtoPrefixes[] = {"####", "###", "##", |
47 | 21.8k | "//", "#"}; |
48 | 21.8k | ArrayRef<StringRef> KnownPrefixes(KnownCStylePrefixes); |
49 | 21.8k | if (Style.Language == FormatStyle::LK_TextProto) |
50 | 0 | KnownPrefixes = KnownTextProtoPrefixes; |
51 | | |
52 | 21.8k | assert( |
53 | 21.8k | llvm::is_sorted(KnownPrefixes, [](StringRef Lhs, StringRef Rhs) noexcept { |
54 | 21.8k | return Lhs.size() > Rhs.size(); |
55 | 21.8k | })); |
56 | | |
57 | 91.0k | for (StringRef KnownPrefix : KnownPrefixes) { |
58 | 91.0k | if (Comment.starts_with(KnownPrefix)) { |
59 | 21.8k | const auto PrefixLength = |
60 | 21.8k | Comment.find_first_not_of(' ', KnownPrefix.size()); |
61 | 21.8k | return Comment.substr(0, PrefixLength); |
62 | 21.8k | } |
63 | 91.0k | } |
64 | 0 | return {}; |
65 | 21.8k | } |
66 | | |
67 | | static BreakableToken::Split |
68 | | getCommentSplit(StringRef Text, unsigned ContentStartColumn, |
69 | | unsigned ColumnLimit, unsigned TabWidth, |
70 | | encoding::Encoding Encoding, const FormatStyle &Style, |
71 | 72.8k | bool DecorationEndsWithStar = false) { |
72 | 72.8k | LLVM_DEBUG(llvm::dbgs() << "Comment split: \"" << Text |
73 | 72.8k | << "\", Column limit: " << ColumnLimit |
74 | 72.8k | << ", Content start: " << ContentStartColumn << "\n"); |
75 | 72.8k | if (ColumnLimit <= ContentStartColumn + 1) |
76 | 23.6k | return BreakableToken::Split(StringRef::npos, 0); |
77 | | |
78 | 49.1k | unsigned MaxSplit = ColumnLimit - ContentStartColumn + 1; |
79 | 49.1k | unsigned MaxSplitBytes = 0; |
80 | | |
81 | 49.1k | for (unsigned NumChars = 0; |
82 | 1.82M | NumChars < MaxSplit && MaxSplitBytes < Text.size();) { |
83 | 1.77M | unsigned BytesInChar = |
84 | 1.77M | encoding::getCodePointNumBytes(Text[MaxSplitBytes], Encoding); |
85 | 1.77M | NumChars += encoding::columnWidthWithTabs( |
86 | 1.77M | Text.substr(MaxSplitBytes, BytesInChar), ContentStartColumn + NumChars, |
87 | 1.77M | TabWidth, Encoding); |
88 | 1.77M | MaxSplitBytes += BytesInChar; |
89 | 1.77M | } |
90 | | |
91 | | // In JavaScript, some @tags can be followed by {, and machinery that parses |
92 | | // these comments will fail to understand the comment if followed by a line |
93 | | // break. So avoid ever breaking before a {. |
94 | 49.1k | if (Style.isJavaScript()) { |
95 | 0 | StringRef::size_type SpaceOffset = |
96 | 0 | Text.find_first_of(Blanks, MaxSplitBytes); |
97 | 0 | if (SpaceOffset != StringRef::npos && SpaceOffset + 1 < Text.size() && |
98 | 0 | Text[SpaceOffset + 1] == '{') { |
99 | 0 | MaxSplitBytes = SpaceOffset + 1; |
100 | 0 | } |
101 | 0 | } |
102 | | |
103 | 49.1k | StringRef::size_type SpaceOffset = Text.find_last_of(Blanks, MaxSplitBytes); |
104 | | |
105 | 49.1k | static const auto kNumberedListRegexp = llvm::Regex("^[1-9][0-9]?\\."); |
106 | | // Some spaces are unacceptable to break on, rewind past them. |
107 | 49.2k | while (SpaceOffset != StringRef::npos) { |
108 | | // If a line-comment ends with `\`, the next line continues the comment, |
109 | | // whether or not it starts with `//`. This is confusing and triggers |
110 | | // -Wcomment. |
111 | | // Avoid introducing multiline comments by not allowing a break right |
112 | | // after '\'. |
113 | 23.8k | if (Style.isCpp()) { |
114 | 23.8k | StringRef::size_type LastNonBlank = |
115 | 23.8k | Text.find_last_not_of(Blanks, SpaceOffset); |
116 | 23.8k | if (LastNonBlank != StringRef::npos && Text[LastNonBlank] == '\\') { |
117 | 8 | SpaceOffset = Text.find_last_of(Blanks, LastNonBlank); |
118 | 8 | continue; |
119 | 8 | } |
120 | 23.8k | } |
121 | | |
122 | | // Do not split before a number followed by a dot: this would be interpreted |
123 | | // as a numbered list, which would prevent re-flowing in subsequent passes. |
124 | 23.8k | if (kNumberedListRegexp.match(Text.substr(SpaceOffset).ltrim(Blanks))) { |
125 | 4 | SpaceOffset = Text.find_last_of(Blanks, SpaceOffset); |
126 | 4 | continue; |
127 | 4 | } |
128 | | |
129 | | // Avoid ever breaking before a @tag or a { in JavaScript. |
130 | 23.8k | if (Style.isJavaScript() && SpaceOffset + 1 < Text.size() && |
131 | 23.8k | (Text[SpaceOffset + 1] == '{' || Text[SpaceOffset + 1] == '@')) { |
132 | 0 | SpaceOffset = Text.find_last_of(Blanks, SpaceOffset); |
133 | 0 | continue; |
134 | 0 | } |
135 | | |
136 | 23.8k | break; |
137 | 23.8k | } |
138 | | |
139 | 49.1k | if (SpaceOffset == StringRef::npos || |
140 | | // Don't break at leading whitespace. |
141 | 49.1k | Text.find_last_not_of(Blanks, SpaceOffset) == StringRef::npos) { |
142 | | // Make sure that we don't break at leading whitespace that |
143 | | // reaches past MaxSplit. |
144 | 25.4k | StringRef::size_type FirstNonWhitespace = Text.find_first_not_of(Blanks); |
145 | 25.4k | if (FirstNonWhitespace == StringRef::npos) { |
146 | | // If the comment is only whitespace, we cannot split. |
147 | 0 | return BreakableToken::Split(StringRef::npos, 0); |
148 | 0 | } |
149 | 25.4k | SpaceOffset = Text.find_first_of( |
150 | 25.4k | Blanks, std::max<unsigned>(MaxSplitBytes, FirstNonWhitespace)); |
151 | 25.4k | } |
152 | 49.1k | if (SpaceOffset != StringRef::npos && SpaceOffset != 0) { |
153 | | // adaptStartOfLine will break after lines starting with /** if the comment |
154 | | // is broken anywhere. Avoid emitting this break twice here. |
155 | | // Example: in /** longtextcomesherethatbreaks */ (with ColumnLimit 20) will |
156 | | // insert a break after /**, so this code must not insert the same break. |
157 | 43.3k | if (SpaceOffset == 1 && Text[SpaceOffset - 1] == '*') |
158 | 0 | return BreakableToken::Split(StringRef::npos, 0); |
159 | 43.3k | StringRef BeforeCut = Text.substr(0, SpaceOffset).rtrim(Blanks); |
160 | 43.3k | StringRef AfterCut = Text.substr(SpaceOffset); |
161 | | // Don't trim the leading blanks if it would create a */ after the break. |
162 | 43.3k | if (!DecorationEndsWithStar || AfterCut.size() <= 1 || AfterCut[1] != '/') |
163 | 43.3k | AfterCut = AfterCut.ltrim(Blanks); |
164 | 43.3k | return BreakableToken::Split(BeforeCut.size(), |
165 | 43.3k | AfterCut.begin() - BeforeCut.end()); |
166 | 43.3k | } |
167 | 5.80k | return BreakableToken::Split(StringRef::npos, 0); |
168 | 49.1k | } |
169 | | |
170 | | static BreakableToken::Split |
171 | | getStringSplit(StringRef Text, unsigned UsedColumns, unsigned ColumnLimit, |
172 | 574k | unsigned TabWidth, encoding::Encoding Encoding) { |
173 | | // FIXME: Reduce unit test case. |
174 | 574k | if (Text.empty()) |
175 | 611 | return BreakableToken::Split(StringRef::npos, 0); |
176 | 573k | if (ColumnLimit <= UsedColumns) |
177 | 4.70k | return BreakableToken::Split(StringRef::npos, 0); |
178 | 569k | unsigned MaxSplit = ColumnLimit - UsedColumns; |
179 | 569k | StringRef::size_type SpaceOffset = 0; |
180 | 569k | StringRef::size_type SlashOffset = 0; |
181 | 569k | StringRef::size_type WordStartOffset = 0; |
182 | 569k | StringRef::size_type SplitPoint = 0; |
183 | 27.4M | for (unsigned Chars = 0;;) { |
184 | 27.4M | unsigned Advance; |
185 | 27.4M | if (Text[0] == '\\') { |
186 | 66.7k | Advance = encoding::getEscapeSequenceLength(Text); |
187 | 66.7k | Chars += Advance; |
188 | 27.4M | } else { |
189 | 27.4M | Advance = encoding::getCodePointNumBytes(Text[0], Encoding); |
190 | 27.4M | Chars += encoding::columnWidthWithTabs( |
191 | 27.4M | Text.substr(0, Advance), UsedColumns + Chars, TabWidth, Encoding); |
192 | 27.4M | } |
193 | | |
194 | 27.4M | if (Chars > MaxSplit || Text.size() <= Advance) |
195 | 569k | break; |
196 | | |
197 | 26.9M | if (IsBlank(Text[0])) |
198 | 164k | SpaceOffset = SplitPoint; |
199 | 26.9M | if (Text[0] == '/') |
200 | 210k | SlashOffset = SplitPoint; |
201 | 26.9M | if (Advance == 1 && !isAlphanumeric(Text[0])) |
202 | 6.57M | WordStartOffset = SplitPoint; |
203 | | |
204 | 26.9M | SplitPoint += Advance; |
205 | 26.9M | Text = Text.substr(Advance); |
206 | 26.9M | } |
207 | | |
208 | 569k | if (SpaceOffset != 0) |
209 | 14.6k | return BreakableToken::Split(SpaceOffset + 1, 0); |
210 | 554k | if (SlashOffset != 0) |
211 | 11.5k | return BreakableToken::Split(SlashOffset + 1, 0); |
212 | 542k | if (WordStartOffset != 0) |
213 | 196k | return BreakableToken::Split(WordStartOffset + 1, 0); |
214 | 346k | if (SplitPoint != 0) |
215 | 345k | return BreakableToken::Split(SplitPoint, 0); |
216 | 714 | return BreakableToken::Split(StringRef::npos, 0); |
217 | 346k | } |
218 | | |
219 | 38.9k | bool switchesFormatting(const FormatToken &Token) { |
220 | 38.9k | assert((Token.is(TT_BlockComment) || Token.is(TT_LineComment)) && |
221 | 38.9k | "formatting regions are switched by comment tokens"); |
222 | 0 | StringRef Content = Token.TokenText.substr(2).ltrim(); |
223 | 38.9k | return Content.starts_with("clang-format on") || |
224 | 38.9k | Content.starts_with("clang-format off"); |
225 | 38.9k | } |
226 | | |
227 | | unsigned |
228 | | BreakableToken::getLengthAfterCompression(unsigned RemainingTokenColumns, |
229 | 29.1k | Split Split) const { |
230 | | // Example: consider the content |
231 | | // lala lala |
232 | | // - RemainingTokenColumns is the original number of columns, 10; |
233 | | // - Split is (4, 2), denoting the two spaces between the two words; |
234 | | // |
235 | | // We compute the number of columns when the split is compressed into a single |
236 | | // space, like: |
237 | | // lala lala |
238 | | // |
239 | | // FIXME: Correctly measure the length of whitespace in Split.second so it |
240 | | // works with tabs. |
241 | 29.1k | return RemainingTokenColumns + 1 - Split.second; |
242 | 29.1k | } |
243 | | |
244 | 177k | unsigned BreakableStringLiteral::getLineCount() const { return 1; } |
245 | | |
246 | | unsigned BreakableStringLiteral::getRangeLength(unsigned LineIndex, |
247 | | unsigned Offset, |
248 | | StringRef::size_type Length, |
249 | 0 | unsigned StartColumn) const { |
250 | 0 | llvm_unreachable("Getting the length of a part of the string literal " |
251 | 0 | "indicates that the code tries to reflow it."); |
252 | 0 | } |
253 | | |
254 | | unsigned |
255 | | BreakableStringLiteral::getRemainingLength(unsigned LineIndex, unsigned Offset, |
256 | 656k | unsigned StartColumn) const { |
257 | 656k | return UnbreakableTailLength + Postfix.size() + |
258 | 656k | encoding::columnWidthWithTabs(Line.substr(Offset), StartColumn, |
259 | 656k | Style.TabWidth, Encoding); |
260 | 656k | } |
261 | | |
262 | | unsigned BreakableStringLiteral::getContentStartColumn(unsigned LineIndex, |
263 | 656k | bool Break) const { |
264 | 656k | return StartColumn + Prefix.size(); |
265 | 656k | } |
266 | | |
267 | | BreakableStringLiteral::BreakableStringLiteral( |
268 | | const FormatToken &Tok, unsigned StartColumn, StringRef Prefix, |
269 | | StringRef Postfix, unsigned UnbreakableTailLength, bool InPPDirective, |
270 | | encoding::Encoding Encoding, const FormatStyle &Style) |
271 | | : BreakableToken(Tok, InPPDirective, Encoding, Style), |
272 | | StartColumn(StartColumn), Prefix(Prefix), Postfix(Postfix), |
273 | 88.7k | UnbreakableTailLength(UnbreakableTailLength) { |
274 | 88.7k | assert(Tok.TokenText.starts_with(Prefix) && Tok.TokenText.ends_with(Postfix)); |
275 | 0 | Line = Tok.TokenText.substr( |
276 | 88.7k | Prefix.size(), Tok.TokenText.size() - Prefix.size() - Postfix.size()); |
277 | 88.7k | } |
278 | | |
279 | | BreakableToken::Split BreakableStringLiteral::getSplit( |
280 | | unsigned LineIndex, unsigned TailOffset, unsigned ColumnLimit, |
281 | 574k | unsigned ContentStartColumn, const llvm::Regex &CommentPragmasRegex) const { |
282 | 574k | return getStringSplit(Line.substr(TailOffset), ContentStartColumn, |
283 | 574k | ColumnLimit - Postfix.size(), Style.TabWidth, Encoding); |
284 | 574k | } |
285 | | |
286 | | void BreakableStringLiteral::insertBreak(unsigned LineIndex, |
287 | | unsigned TailOffset, Split Split, |
288 | | unsigned ContentIndent, |
289 | 75.5k | WhitespaceManager &Whitespaces) const { |
290 | 75.5k | Whitespaces.replaceWhitespaceInToken( |
291 | 75.5k | Tok, Prefix.size() + TailOffset + Split.first, Split.second, Postfix, |
292 | 75.5k | Prefix, InPPDirective, 1, StartColumn); |
293 | 75.5k | } |
294 | | |
295 | | BreakableStringLiteralUsingOperators::BreakableStringLiteralUsingOperators( |
296 | | const FormatToken &Tok, QuoteStyleType QuoteStyle, bool UnindentPlus, |
297 | | unsigned StartColumn, unsigned UnbreakableTailLength, bool InPPDirective, |
298 | | encoding::Encoding Encoding, const FormatStyle &Style) |
299 | | : BreakableStringLiteral( |
300 | | Tok, StartColumn, /*Prefix=*/QuoteStyle == SingleQuotes ? "'" |
301 | | : QuoteStyle == AtDoubleQuotes ? "@\"" |
302 | | : "\"", |
303 | | /*Postfix=*/QuoteStyle == SingleQuotes ? "'" : "\"", |
304 | | UnbreakableTailLength, InPPDirective, Encoding, Style), |
305 | | BracesNeeded(Tok.isNot(TT_StringInConcatenation)), |
306 | 0 | QuoteStyle(QuoteStyle) { |
307 | | // Find the replacement text for inserting braces and quotes and line breaks. |
308 | | // We don't create an allocated string concatenated from parts here because it |
309 | | // has to outlive the BreakableStringliteral object. The brace replacements |
310 | | // include a quote so that WhitespaceManager can tell it apart from whitespace |
311 | | // replacements between the string and surrounding tokens. |
312 | | |
313 | | // The option is not implemented in JavaScript. |
314 | 0 | bool SignOnNewLine = |
315 | 0 | !Style.isJavaScript() && |
316 | 0 | Style.BreakBeforeBinaryOperators != FormatStyle::BOS_None; |
317 | |
|
318 | 0 | if (Style.isVerilog()) { |
319 | | // In Verilog, all strings are quoted by double quotes, joined by commas, |
320 | | // and wrapped in braces. The comma is always before the newline. |
321 | 0 | assert(QuoteStyle == DoubleQuotes); |
322 | 0 | LeftBraceQuote = Style.Cpp11BracedListStyle ? "{\"" : "{ \""; |
323 | 0 | RightBraceQuote = Style.Cpp11BracedListStyle ? "\"}" : "\" }"; |
324 | 0 | Postfix = "\","; |
325 | 0 | Prefix = "\""; |
326 | 0 | } else { |
327 | | // The plus sign may be on either line. And also C# and JavaScript have |
328 | | // several quoting styles. |
329 | 0 | if (QuoteStyle == SingleQuotes) { |
330 | 0 | LeftBraceQuote = Style.SpacesInParensOptions.Other ? "( '" : "('"; |
331 | 0 | RightBraceQuote = Style.SpacesInParensOptions.Other ? "' )" : "')"; |
332 | 0 | Postfix = SignOnNewLine ? "'" : "' +"; |
333 | 0 | Prefix = SignOnNewLine ? "+ '" : "'"; |
334 | 0 | } else { |
335 | 0 | if (QuoteStyle == AtDoubleQuotes) { |
336 | 0 | LeftBraceQuote = Style.SpacesInParensOptions.Other ? "( @" : "(@"; |
337 | 0 | Prefix = SignOnNewLine ? "+ @\"" : "@\""; |
338 | 0 | } else { |
339 | 0 | LeftBraceQuote = Style.SpacesInParensOptions.Other ? "( \"" : "(\""; |
340 | 0 | Prefix = SignOnNewLine ? "+ \"" : "\""; |
341 | 0 | } |
342 | 0 | RightBraceQuote = Style.SpacesInParensOptions.Other ? "\" )" : "\")"; |
343 | 0 | Postfix = SignOnNewLine ? "\"" : "\" +"; |
344 | 0 | } |
345 | 0 | } |
346 | | |
347 | | // Following lines are indented by the width of the brace and space if any. |
348 | 0 | ContinuationIndent = BracesNeeded ? LeftBraceQuote.size() - 1 : 0; |
349 | | // The plus sign may need to be unindented depending on the style. |
350 | | // FIXME: Add support for DontAlign. |
351 | 0 | if (!Style.isVerilog() && SignOnNewLine && !BracesNeeded && UnindentPlus && |
352 | 0 | Style.AlignOperands == FormatStyle::OAS_AlignAfterOperator) { |
353 | 0 | ContinuationIndent -= 2; |
354 | 0 | } |
355 | 0 | } |
356 | | |
357 | | unsigned BreakableStringLiteralUsingOperators::getRemainingLength( |
358 | 0 | unsigned LineIndex, unsigned Offset, unsigned StartColumn) const { |
359 | 0 | return UnbreakableTailLength + (BracesNeeded ? RightBraceQuote.size() : 1) + |
360 | 0 | encoding::columnWidthWithTabs(Line.substr(Offset), StartColumn, |
361 | 0 | Style.TabWidth, Encoding); |
362 | 0 | } |
363 | | |
364 | | unsigned |
365 | | BreakableStringLiteralUsingOperators::getContentStartColumn(unsigned LineIndex, |
366 | 0 | bool Break) const { |
367 | 0 | return std::max( |
368 | 0 | 0, |
369 | 0 | static_cast<int>(StartColumn) + |
370 | 0 | (Break ? ContinuationIndent + static_cast<int>(Prefix.size()) |
371 | 0 | : (BracesNeeded ? static_cast<int>(LeftBraceQuote.size()) - 1 |
372 | 0 | : 0) + |
373 | 0 | (QuoteStyle == AtDoubleQuotes ? 2 : 1))); |
374 | 0 | } |
375 | | |
376 | | void BreakableStringLiteralUsingOperators::insertBreak( |
377 | | unsigned LineIndex, unsigned TailOffset, Split Split, |
378 | 0 | unsigned ContentIndent, WhitespaceManager &Whitespaces) const { |
379 | 0 | Whitespaces.replaceWhitespaceInToken( |
380 | 0 | Tok, /*Offset=*/(QuoteStyle == AtDoubleQuotes ? 2 : 1) + TailOffset + |
381 | 0 | Split.first, |
382 | 0 | /*ReplaceChars=*/Split.second, /*PreviousPostfix=*/Postfix, |
383 | 0 | /*CurrentPrefix=*/Prefix, InPPDirective, /*NewLines=*/1, |
384 | | /*Spaces=*/ |
385 | 0 | std::max(0, static_cast<int>(StartColumn) + ContinuationIndent)); |
386 | 0 | } |
387 | | |
388 | | void BreakableStringLiteralUsingOperators::updateAfterBroken( |
389 | 0 | WhitespaceManager &Whitespaces) const { |
390 | | // Add the braces required for breaking the token if they are needed. |
391 | 0 | if (!BracesNeeded) |
392 | 0 | return; |
393 | | |
394 | | // To add a brace or parenthesis, we replace the quote (or the at sign) with a |
395 | | // brace and another quote. This is because the rest of the program requires |
396 | | // one replacement for each source range. If we replace the empty strings |
397 | | // around the string, it may conflict with whitespace replacements between the |
398 | | // string and adjacent tokens. |
399 | 0 | Whitespaces.replaceWhitespaceInToken( |
400 | 0 | Tok, /*Offset=*/0, /*ReplaceChars=*/1, /*PreviousPostfix=*/"", |
401 | 0 | /*CurrentPrefix=*/LeftBraceQuote, InPPDirective, /*NewLines=*/0, |
402 | 0 | /*Spaces=*/0); |
403 | 0 | Whitespaces.replaceWhitespaceInToken( |
404 | 0 | Tok, /*Offset=*/Tok.TokenText.size() - 1, /*ReplaceChars=*/1, |
405 | 0 | /*PreviousPostfix=*/RightBraceQuote, |
406 | 0 | /*CurrentPrefix=*/"", InPPDirective, /*NewLines=*/0, /*Spaces=*/0); |
407 | 0 | } |
408 | | |
409 | | BreakableComment::BreakableComment(const FormatToken &Token, |
410 | | unsigned StartColumn, bool InPPDirective, |
411 | | encoding::Encoding Encoding, |
412 | | const FormatStyle &Style) |
413 | | : BreakableToken(Token, InPPDirective, Encoding, Style), |
414 | 36.7k | StartColumn(StartColumn) {} |
415 | | |
416 | 73.5k | unsigned BreakableComment::getLineCount() const { return Lines.size(); } |
417 | | |
418 | | BreakableToken::Split |
419 | | BreakableComment::getSplit(unsigned LineIndex, unsigned TailOffset, |
420 | | unsigned ColumnLimit, unsigned ContentStartColumn, |
421 | 13.4k | const llvm::Regex &CommentPragmasRegex) const { |
422 | | // Don't break lines matching the comment pragmas regex. |
423 | 13.4k | if (CommentPragmasRegex.match(Content[LineIndex])) |
424 | 0 | return Split(StringRef::npos, 0); |
425 | 13.4k | return getCommentSplit(Content[LineIndex].substr(TailOffset), |
426 | 13.4k | ContentStartColumn, ColumnLimit, Style.TabWidth, |
427 | 13.4k | Encoding, Style); |
428 | 13.4k | } |
429 | | |
430 | | void BreakableComment::compressWhitespace( |
431 | | unsigned LineIndex, unsigned TailOffset, Split Split, |
432 | 83 | WhitespaceManager &Whitespaces) const { |
433 | 83 | StringRef Text = Content[LineIndex].substr(TailOffset); |
434 | | // Text is relative to the content line, but Whitespaces operates relative to |
435 | | // the start of the corresponding token, so compute the start of the Split |
436 | | // that needs to be compressed into a single space relative to the start of |
437 | | // its token. |
438 | 83 | unsigned BreakOffsetInToken = |
439 | 83 | Text.data() - tokenAt(LineIndex).TokenText.data() + Split.first; |
440 | 83 | unsigned CharsToRemove = Split.second; |
441 | 83 | Whitespaces.replaceWhitespaceInToken( |
442 | 83 | tokenAt(LineIndex), BreakOffsetInToken, CharsToRemove, "", "", |
443 | 83 | /*InPPDirective=*/false, /*Newlines=*/0, /*Spaces=*/1); |
444 | 83 | } |
445 | | |
446 | 81.9k | const FormatToken &BreakableComment::tokenAt(unsigned LineIndex) const { |
447 | 81.9k | return Tokens[LineIndex] ? *Tokens[LineIndex] : Tok; |
448 | 81.9k | } |
449 | | |
450 | 3.90k | static bool mayReflowContent(StringRef Content) { |
451 | 3.90k | Content = Content.trim(Blanks); |
452 | | // Lines starting with '@' commonly have special meaning. |
453 | | // Lines starting with '-', '-#', '+' or '*' are bulleted/numbered lists. |
454 | 3.90k | bool hasSpecialMeaningPrefix = false; |
455 | 3.90k | for (StringRef Prefix : |
456 | 31.2k | {"@", "TODO", "FIXME", "XXX", "-# ", "- ", "+ ", "* "}) { |
457 | 31.2k | if (Content.starts_with(Prefix)) { |
458 | 79 | hasSpecialMeaningPrefix = true; |
459 | 79 | break; |
460 | 79 | } |
461 | 31.2k | } |
462 | | |
463 | | // Numbered lists may also start with a number followed by '.' |
464 | | // To avoid issues if a line starts with a number which is actually the end |
465 | | // of a previous line, we only consider numbers with up to 2 digits. |
466 | 3.90k | static const auto kNumberedListRegexp = llvm::Regex("^[1-9][0-9]?\\. "); |
467 | 3.90k | hasSpecialMeaningPrefix = |
468 | 3.90k | hasSpecialMeaningPrefix || kNumberedListRegexp.match(Content); |
469 | | |
470 | | // Simple heuristic for what to reflow: content should contain at least two |
471 | | // characters and either the first or second character must be |
472 | | // non-punctuation. |
473 | 3.90k | return Content.size() >= 2 && !hasSpecialMeaningPrefix && |
474 | 3.90k | !Content.ends_with("\\") && |
475 | | // Note that this is UTF-8 safe, since if isPunctuation(Content[0]) is |
476 | | // true, then the first code point must be 1 byte long. |
477 | 3.90k | (!isPunctuation(Content[0]) || !isPunctuation(Content[1])); |
478 | 3.90k | } |
479 | | |
480 | | BreakableBlockComment::BreakableBlockComment( |
481 | | const FormatToken &Token, unsigned StartColumn, |
482 | | unsigned OriginalStartColumn, bool FirstInLine, bool InPPDirective, |
483 | | encoding::Encoding Encoding, const FormatStyle &Style, bool UseCRLF) |
484 | | : BreakableComment(Token, StartColumn, InPPDirective, Encoding, Style), |
485 | | DelimitersOnNewline(false), |
486 | 15.0k | UnbreakableTailLength(Token.UnbreakableTailLength) { |
487 | 15.0k | assert(Tok.is(TT_BlockComment) && |
488 | 15.0k | "block comment section must start with a block comment"); |
489 | | |
490 | 0 | StringRef TokenText(Tok.TokenText); |
491 | 15.0k | assert(TokenText.starts_with("/*") && TokenText.ends_with("*/")); |
492 | 0 | TokenText.substr(2, TokenText.size() - 4) |
493 | 15.0k | .split(Lines, UseCRLF ? "\r\n" : "\n"); |
494 | | |
495 | 15.0k | int IndentDelta = StartColumn - OriginalStartColumn; |
496 | 15.0k | Content.resize(Lines.size()); |
497 | 15.0k | Content[0] = Lines[0]; |
498 | 15.0k | ContentColumn.resize(Lines.size()); |
499 | | // Account for the initial '/*'. |
500 | 15.0k | ContentColumn[0] = StartColumn + 2; |
501 | 15.0k | Tokens.resize(Lines.size()); |
502 | 323k | for (size_t i = 1; i < Lines.size(); ++i) |
503 | 308k | adjustWhitespace(i, IndentDelta); |
504 | | |
505 | | // Align decorations with the column of the star on the first line, |
506 | | // that is one column after the start "/*". |
507 | 15.0k | DecorationColumn = StartColumn + 1; |
508 | | |
509 | | // Account for comment decoration patterns like this: |
510 | | // |
511 | | // /* |
512 | | // ** blah blah blah |
513 | | // */ |
514 | 15.0k | if (Lines.size() >= 2 && Content[1].starts_with("**") && |
515 | 15.0k | static_cast<unsigned>(ContentColumn[1]) == StartColumn) { |
516 | 0 | DecorationColumn = StartColumn; |
517 | 0 | } |
518 | | |
519 | 15.0k | Decoration = "* "; |
520 | 15.0k | if (Lines.size() == 1 && !FirstInLine) { |
521 | | // Comments for which FirstInLine is false can start on arbitrary column, |
522 | | // and available horizontal space can be too small to align consecutive |
523 | | // lines with the first one. |
524 | | // FIXME: We could, probably, align them to current indentation level, but |
525 | | // now we just wrap them without stars. |
526 | 11.9k | Decoration = ""; |
527 | 11.9k | } |
528 | 15.3k | for (size_t i = 1, e = Content.size(); i < e && !Decoration.empty(); ++i) { |
529 | 315 | const StringRef &Text = Content[i]; |
530 | 315 | if (i + 1 == e) { |
531 | | // If the last line is empty, the closing "*/" will have a star. |
532 | 26 | if (Text.empty()) |
533 | 21 | break; |
534 | 289 | } else if (!Text.empty() && Decoration.starts_with(Text)) { |
535 | 0 | continue; |
536 | 0 | } |
537 | 808 | while (!Text.starts_with(Decoration)) |
538 | 514 | Decoration = Decoration.drop_back(1); |
539 | 294 | } |
540 | | |
541 | 15.0k | LastLineNeedsDecoration = true; |
542 | 15.0k | IndentAtLineBreak = ContentColumn[0] + 1; |
543 | 323k | for (size_t i = 1, e = Lines.size(); i < e; ++i) { |
544 | 308k | if (Content[i].empty()) { |
545 | 34.1k | if (i + 1 == e) { |
546 | | // Empty last line means that we already have a star as a part of the |
547 | | // trailing */. We also need to preserve whitespace, so that */ is |
548 | | // correctly indented. |
549 | 39 | LastLineNeedsDecoration = false; |
550 | | // Align the star in the last '*/' with the stars on the previous lines. |
551 | 39 | if (e >= 2 && !Decoration.empty()) |
552 | 21 | ContentColumn[i] = DecorationColumn; |
553 | 34.0k | } else if (Decoration.empty()) { |
554 | | // For all other lines, set the start column to 0 if they're empty, so |
555 | | // we do not insert trailing whitespace anywhere. |
556 | 34.0k | ContentColumn[i] = 0; |
557 | 34.0k | } |
558 | 34.1k | continue; |
559 | 34.1k | } |
560 | | |
561 | | // The first line already excludes the star. |
562 | | // The last line excludes the star if LastLineNeedsDecoration is false. |
563 | | // For all other lines, adjust the line to exclude the star and |
564 | | // (optionally) the first whitespace. |
565 | 274k | unsigned DecorationSize = Decoration.starts_with(Content[i]) |
566 | 274k | ? Content[i].size() |
567 | 274k | : Decoration.size(); |
568 | 274k | if (DecorationSize) |
569 | 36 | ContentColumn[i] = DecorationColumn + DecorationSize; |
570 | 274k | Content[i] = Content[i].substr(DecorationSize); |
571 | 274k | if (!Decoration.starts_with(Content[i])) { |
572 | 274k | IndentAtLineBreak = |
573 | 274k | std::min<int>(IndentAtLineBreak, std::max(0, ContentColumn[i])); |
574 | 274k | } |
575 | 274k | } |
576 | 15.0k | IndentAtLineBreak = std::max<unsigned>(IndentAtLineBreak, Decoration.size()); |
577 | | |
578 | | // Detect a multiline jsdoc comment and set DelimitersOnNewline in that case. |
579 | 15.0k | if (Style.isJavaScript() || Style.Language == FormatStyle::LK_Java) { |
580 | 0 | if ((Lines[0] == "*" || Lines[0].starts_with("* ")) && Lines.size() > 1) { |
581 | | // This is a multiline jsdoc comment. |
582 | 0 | DelimitersOnNewline = true; |
583 | 0 | } else if (Lines[0].starts_with("* ") && Lines.size() == 1) { |
584 | | // Detect a long single-line comment, like: |
585 | | // /** long long long */ |
586 | | // Below, '2' is the width of '*/'. |
587 | 0 | unsigned EndColumn = |
588 | 0 | ContentColumn[0] + |
589 | 0 | encoding::columnWidthWithTabs(Lines[0], ContentColumn[0], |
590 | 0 | Style.TabWidth, Encoding) + |
591 | 0 | 2; |
592 | 0 | DelimitersOnNewline = EndColumn > Style.ColumnLimit; |
593 | 0 | } |
594 | 0 | } |
595 | | |
596 | 15.0k | LLVM_DEBUG({ |
597 | 15.0k | llvm::dbgs() << "IndentAtLineBreak " << IndentAtLineBreak << "\n"; |
598 | 15.0k | llvm::dbgs() << "DelimitersOnNewline " << DelimitersOnNewline << "\n"; |
599 | 15.0k | for (size_t i = 0; i < Lines.size(); ++i) { |
600 | 15.0k | llvm::dbgs() << i << " |" << Content[i] << "| " |
601 | 15.0k | << "CC=" << ContentColumn[i] << "| " |
602 | 15.0k | << "IN=" << (Content[i].data() - Lines[i].data()) << "\n"; |
603 | 15.0k | } |
604 | 15.0k | }); |
605 | 15.0k | } |
606 | | |
607 | | BreakableToken::Split BreakableBlockComment::getSplit( |
608 | | unsigned LineIndex, unsigned TailOffset, unsigned ColumnLimit, |
609 | 59.4k | unsigned ContentStartColumn, const llvm::Regex &CommentPragmasRegex) const { |
610 | | // Don't break lines matching the comment pragmas regex. |
611 | 59.4k | if (CommentPragmasRegex.match(Content[LineIndex])) |
612 | 0 | return Split(StringRef::npos, 0); |
613 | 59.4k | return getCommentSplit(Content[LineIndex].substr(TailOffset), |
614 | 59.4k | ContentStartColumn, ColumnLimit, Style.TabWidth, |
615 | 59.4k | Encoding, Style, Decoration.ends_with("*")); |
616 | 59.4k | } |
617 | | |
618 | | void BreakableBlockComment::adjustWhitespace(unsigned LineIndex, |
619 | 308k | int IndentDelta) { |
620 | | // When in a preprocessor directive, the trailing backslash in a block comment |
621 | | // is not needed, but can serve a purpose of uniformity with necessary escaped |
622 | | // newlines outside the comment. In this case we remove it here before |
623 | | // trimming the trailing whitespace. The backslash will be re-added later when |
624 | | // inserting a line break. |
625 | 308k | size_t EndOfPreviousLine = Lines[LineIndex - 1].size(); |
626 | 308k | if (InPPDirective && Lines[LineIndex - 1].ends_with("\\")) |
627 | 0 | --EndOfPreviousLine; |
628 | | |
629 | | // Calculate the end of the non-whitespace text in the previous line. |
630 | 308k | EndOfPreviousLine = |
631 | 308k | Lines[LineIndex - 1].find_last_not_of(Blanks, EndOfPreviousLine); |
632 | 308k | if (EndOfPreviousLine == StringRef::npos) |
633 | 34.1k | EndOfPreviousLine = 0; |
634 | 274k | else |
635 | 274k | ++EndOfPreviousLine; |
636 | | // Calculate the start of the non-whitespace text in the current line. |
637 | 308k | size_t StartOfLine = Lines[LineIndex].find_first_not_of(Blanks); |
638 | 308k | if (StartOfLine == StringRef::npos) |
639 | 34.1k | StartOfLine = Lines[LineIndex].size(); |
640 | | |
641 | 308k | StringRef Whitespace = Lines[LineIndex].substr(0, StartOfLine); |
642 | | // Adjust Lines to only contain relevant text. |
643 | 308k | size_t PreviousContentOffset = |
644 | 308k | Content[LineIndex - 1].data() - Lines[LineIndex - 1].data(); |
645 | 308k | Content[LineIndex - 1] = Lines[LineIndex - 1].substr( |
646 | 308k | PreviousContentOffset, EndOfPreviousLine - PreviousContentOffset); |
647 | 308k | Content[LineIndex] = Lines[LineIndex].substr(StartOfLine); |
648 | | |
649 | | // Adjust the start column uniformly across all lines. |
650 | 308k | ContentColumn[LineIndex] = |
651 | 308k | encoding::columnWidthWithTabs(Whitespace, 0, Style.TabWidth, Encoding) + |
652 | 308k | IndentDelta; |
653 | 308k | } |
654 | | |
655 | | unsigned BreakableBlockComment::getRangeLength(unsigned LineIndex, |
656 | | unsigned Offset, |
657 | | StringRef::size_type Length, |
658 | 403k | unsigned StartColumn) const { |
659 | 403k | return encoding::columnWidthWithTabs( |
660 | 403k | Content[LineIndex].substr(Offset, Length), StartColumn, Style.TabWidth, |
661 | 403k | Encoding); |
662 | 403k | } |
663 | | |
664 | | unsigned BreakableBlockComment::getRemainingLength(unsigned LineIndex, |
665 | | unsigned Offset, |
666 | 363k | unsigned StartColumn) const { |
667 | 363k | unsigned LineLength = |
668 | 363k | UnbreakableTailLength + |
669 | 363k | getRangeLength(LineIndex, Offset, StringRef::npos, StartColumn); |
670 | 363k | if (LineIndex + 1 == Lines.size()) { |
671 | 39.8k | LineLength += 2; |
672 | | // We never need a decoration when breaking just the trailing "*/" postfix. |
673 | 39.8k | bool HasRemainingText = Offset < Content[LineIndex].size(); |
674 | 39.8k | if (!HasRemainingText) { |
675 | 900 | bool HasDecoration = Lines[LineIndex].ltrim().starts_with(Decoration); |
676 | 900 | if (HasDecoration) |
677 | 713 | LineLength -= Decoration.size(); |
678 | 900 | } |
679 | 39.8k | } |
680 | 363k | return LineLength; |
681 | 363k | } |
682 | | |
683 | | unsigned BreakableBlockComment::getContentStartColumn(unsigned LineIndex, |
684 | 347k | bool Break) const { |
685 | 347k | if (Break) |
686 | 25.6k | return IndentAtLineBreak; |
687 | 322k | return std::max(0, ContentColumn[LineIndex]); |
688 | 347k | } |
689 | | |
690 | | const llvm::StringSet<> |
691 | | BreakableBlockComment::ContentIndentingJavadocAnnotations = { |
692 | | "@param", "@return", "@returns", "@throws", "@type", "@template", |
693 | | "@see", "@deprecated", "@define", "@exports", "@mods", "@private", |
694 | | }; |
695 | | |
696 | 25.9k | unsigned BreakableBlockComment::getContentIndent(unsigned LineIndex) const { |
697 | 25.9k | if (Style.Language != FormatStyle::LK_Java && !Style.isJavaScript()) |
698 | 25.9k | return 0; |
699 | | // The content at LineIndex 0 of a comment like: |
700 | | // /** line 0 */ |
701 | | // is "* line 0", so we need to skip over the decoration in that case. |
702 | 0 | StringRef ContentWithNoDecoration = Content[LineIndex]; |
703 | 0 | if (LineIndex == 0 && ContentWithNoDecoration.starts_with("*")) |
704 | 0 | ContentWithNoDecoration = ContentWithNoDecoration.substr(1).ltrim(Blanks); |
705 | 0 | StringRef FirstWord = ContentWithNoDecoration.substr( |
706 | 0 | 0, ContentWithNoDecoration.find_first_of(Blanks)); |
707 | 0 | if (ContentIndentingJavadocAnnotations.contains(FirstWord)) |
708 | 0 | return Style.ContinuationIndentWidth; |
709 | 0 | return 0; |
710 | 0 | } |
711 | | |
712 | | void BreakableBlockComment::insertBreak(unsigned LineIndex, unsigned TailOffset, |
713 | | Split Split, unsigned ContentIndent, |
714 | 6.53k | WhitespaceManager &Whitespaces) const { |
715 | 6.53k | StringRef Text = Content[LineIndex].substr(TailOffset); |
716 | 6.53k | StringRef Prefix = Decoration; |
717 | | // We need this to account for the case when we have a decoration "* " for all |
718 | | // the lines except for the last one, where the star in "*/" acts as a |
719 | | // decoration. |
720 | 6.53k | unsigned LocalIndentAtLineBreak = IndentAtLineBreak; |
721 | 6.53k | if (LineIndex + 1 == Lines.size() && |
722 | 6.53k | Text.size() == Split.first + Split.second) { |
723 | | // For the last line we need to break before "*/", but not to add "* ". |
724 | 245 | Prefix = ""; |
725 | 245 | if (LocalIndentAtLineBreak >= 2) |
726 | 237 | LocalIndentAtLineBreak -= 2; |
727 | 245 | } |
728 | | // The split offset is from the beginning of the line. Convert it to an offset |
729 | | // from the beginning of the token text. |
730 | 6.53k | unsigned BreakOffsetInToken = |
731 | 6.53k | Text.data() - tokenAt(LineIndex).TokenText.data() + Split.first; |
732 | 6.53k | unsigned CharsToRemove = Split.second; |
733 | 6.53k | assert(LocalIndentAtLineBreak >= Prefix.size()); |
734 | 0 | std::string PrefixWithTrailingIndent = std::string(Prefix); |
735 | 6.53k | PrefixWithTrailingIndent.append(ContentIndent, ' '); |
736 | 6.53k | Whitespaces.replaceWhitespaceInToken( |
737 | 6.53k | tokenAt(LineIndex), BreakOffsetInToken, CharsToRemove, "", |
738 | 6.53k | PrefixWithTrailingIndent, InPPDirective, /*Newlines=*/1, |
739 | 6.53k | /*Spaces=*/LocalIndentAtLineBreak + ContentIndent - |
740 | 6.53k | PrefixWithTrailingIndent.size()); |
741 | 6.53k | } |
742 | | |
743 | | BreakableToken::Split BreakableBlockComment::getReflowSplit( |
744 | 3.89k | unsigned LineIndex, const llvm::Regex &CommentPragmasRegex) const { |
745 | 3.89k | if (!mayReflow(LineIndex, CommentPragmasRegex)) |
746 | 1.78k | return Split(StringRef::npos, 0); |
747 | | |
748 | | // If we're reflowing into a line with content indent, only reflow the next |
749 | | // line if its starting whitespace matches the content indent. |
750 | 2.11k | size_t Trimmed = Content[LineIndex].find_first_not_of(Blanks); |
751 | 2.11k | if (LineIndex) { |
752 | 2.11k | unsigned PreviousContentIndent = getContentIndent(LineIndex - 1); |
753 | 2.11k | if (PreviousContentIndent && Trimmed != StringRef::npos && |
754 | 2.11k | Trimmed != PreviousContentIndent) { |
755 | 0 | return Split(StringRef::npos, 0); |
756 | 0 | } |
757 | 2.11k | } |
758 | | |
759 | 2.11k | return Split(0, Trimmed != StringRef::npos ? Trimmed : 0); |
760 | 2.11k | } |
761 | | |
762 | 15.0k | bool BreakableBlockComment::introducesBreakBeforeToken() const { |
763 | | // A break is introduced when we want delimiters on newline. |
764 | 15.0k | return DelimitersOnNewline && |
765 | 15.0k | Lines[0].substr(1).find_first_not_of(Blanks) != StringRef::npos; |
766 | 15.0k | } |
767 | | |
768 | | void BreakableBlockComment::reflow(unsigned LineIndex, |
769 | 325 | WhitespaceManager &Whitespaces) const { |
770 | 325 | StringRef TrimmedContent = Content[LineIndex].ltrim(Blanks); |
771 | | // Here we need to reflow. |
772 | 325 | assert(Tokens[LineIndex - 1] == Tokens[LineIndex] && |
773 | 325 | "Reflowing whitespace within a token"); |
774 | | // This is the offset of the end of the last line relative to the start of |
775 | | // the token text in the token. |
776 | 0 | unsigned WhitespaceOffsetInToken = Content[LineIndex - 1].data() + |
777 | 325 | Content[LineIndex - 1].size() - |
778 | 325 | tokenAt(LineIndex).TokenText.data(); |
779 | 325 | unsigned WhitespaceLength = TrimmedContent.data() - |
780 | 325 | tokenAt(LineIndex).TokenText.data() - |
781 | 325 | WhitespaceOffsetInToken; |
782 | 325 | Whitespaces.replaceWhitespaceInToken( |
783 | 325 | tokenAt(LineIndex), WhitespaceOffsetInToken, |
784 | 325 | /*ReplaceChars=*/WhitespaceLength, /*PreviousPostfix=*/"", |
785 | 325 | /*CurrentPrefix=*/ReflowPrefix, InPPDirective, /*Newlines=*/0, |
786 | 325 | /*Spaces=*/0); |
787 | 325 | } |
788 | | |
789 | | void BreakableBlockComment::adaptStartOfLine( |
790 | 22.2k | unsigned LineIndex, WhitespaceManager &Whitespaces) const { |
791 | 22.2k | if (LineIndex == 0) { |
792 | 3.02k | if (DelimitersOnNewline) { |
793 | | // Since we're breaking at index 1 below, the break position and the |
794 | | // break length are the same. |
795 | | // Note: this works because getCommentSplit is careful never to split at |
796 | | // the beginning of a line. |
797 | 0 | size_t BreakLength = Lines[0].substr(1).find_first_not_of(Blanks); |
798 | 0 | if (BreakLength != StringRef::npos) { |
799 | 0 | insertBreak(LineIndex, 0, Split(1, BreakLength), /*ContentIndent=*/0, |
800 | 0 | Whitespaces); |
801 | 0 | } |
802 | 0 | } |
803 | 3.02k | return; |
804 | 3.02k | } |
805 | | // Here no reflow with the previous line will happen. |
806 | | // Fix the decoration of the line at LineIndex. |
807 | 19.2k | StringRef Prefix = Decoration; |
808 | 19.2k | if (Content[LineIndex].empty()) { |
809 | 16.1k | if (LineIndex + 1 == Lines.size()) { |
810 | 14 | if (!LastLineNeedsDecoration) { |
811 | | // If the last line was empty, we don't need a prefix, as the */ will |
812 | | // line up with the decoration (if it exists). |
813 | 14 | Prefix = ""; |
814 | 14 | } |
815 | 16.1k | } else if (!Decoration.empty()) { |
816 | | // For other empty lines, if we do have a decoration, adapt it to not |
817 | | // contain a trailing whitespace. |
818 | 0 | Prefix = Prefix.substr(0, 1); |
819 | 0 | } |
820 | 16.1k | } else if (ContentColumn[LineIndex] == 1) { |
821 | | // This line starts immediately after the decorating *. |
822 | 3 | Prefix = Prefix.substr(0, 1); |
823 | 3 | } |
824 | | // This is the offset of the end of the last line relative to the start of the |
825 | | // token text in the token. |
826 | 19.2k | unsigned WhitespaceOffsetInToken = Content[LineIndex - 1].data() + |
827 | 19.2k | Content[LineIndex - 1].size() - |
828 | 19.2k | tokenAt(LineIndex).TokenText.data(); |
829 | 19.2k | unsigned WhitespaceLength = Content[LineIndex].data() - |
830 | 19.2k | tokenAt(LineIndex).TokenText.data() - |
831 | 19.2k | WhitespaceOffsetInToken; |
832 | 19.2k | Whitespaces.replaceWhitespaceInToken( |
833 | 19.2k | tokenAt(LineIndex), WhitespaceOffsetInToken, WhitespaceLength, "", Prefix, |
834 | 19.2k | InPPDirective, /*Newlines=*/1, ContentColumn[LineIndex] - Prefix.size()); |
835 | 19.2k | } |
836 | | |
837 | | BreakableToken::Split |
838 | 15.0k | BreakableBlockComment::getSplitAfterLastLine(unsigned TailOffset) const { |
839 | 15.0k | if (DelimitersOnNewline) { |
840 | | // Replace the trailing whitespace of the last line with a newline. |
841 | | // In case the last line is empty, the ending '*/' is already on its own |
842 | | // line. |
843 | 0 | StringRef Line = Content.back().substr(TailOffset); |
844 | 0 | StringRef TrimmedLine = Line.rtrim(Blanks); |
845 | 0 | if (!TrimmedLine.empty()) |
846 | 0 | return Split(TrimmedLine.size(), Line.size() - TrimmedLine.size()); |
847 | 0 | } |
848 | 15.0k | return Split(StringRef::npos, 0); |
849 | 15.0k | } |
850 | | |
851 | | bool BreakableBlockComment::mayReflow( |
852 | 3.89k | unsigned LineIndex, const llvm::Regex &CommentPragmasRegex) const { |
853 | | // Content[LineIndex] may exclude the indent after the '*' decoration. In that |
854 | | // case, we compute the start of the comment pragma manually. |
855 | 3.89k | StringRef IndentContent = Content[LineIndex]; |
856 | 3.89k | if (Lines[LineIndex].ltrim(Blanks).starts_with("*")) |
857 | 105 | IndentContent = Lines[LineIndex].ltrim(Blanks).substr(1); |
858 | 3.89k | return LineIndex > 0 && !CommentPragmasRegex.match(IndentContent) && |
859 | 3.89k | mayReflowContent(Content[LineIndex]) && !Tok.Finalized && |
860 | 3.89k | !switchesFormatting(tokenAt(LineIndex)); |
861 | 3.89k | } |
862 | | |
863 | | BreakableLineCommentSection::BreakableLineCommentSection( |
864 | | const FormatToken &Token, unsigned StartColumn, bool InPPDirective, |
865 | | encoding::Encoding Encoding, const FormatStyle &Style) |
866 | 21.7k | : BreakableComment(Token, StartColumn, InPPDirective, Encoding, Style) { |
867 | 21.7k | assert(Tok.is(TT_LineComment) && |
868 | 21.7k | "line comment section must start with a line comment"); |
869 | 0 | FormatToken *LineTok = nullptr; |
870 | 21.7k | const int Minimum = Style.SpacesInLineCommentPrefix.Minimum; |
871 | | // How many spaces we changed in the first line of the section, this will be |
872 | | // applied in all following lines |
873 | 21.7k | int FirstLineSpaceChange = 0; |
874 | 21.7k | for (const FormatToken *CurrentTok = &Tok; |
875 | 22.2k | CurrentTok && CurrentTok->is(TT_LineComment); |
876 | 21.8k | CurrentTok = CurrentTok->Next) { |
877 | 21.8k | LastLineTok = LineTok; |
878 | 21.8k | StringRef TokenText(CurrentTok->TokenText); |
879 | 21.8k | assert((TokenText.starts_with("//") || TokenText.starts_with("#")) && |
880 | 21.8k | "unsupported line comment prefix, '//' and '#' are supported"); |
881 | 0 | size_t FirstLineIndex = Lines.size(); |
882 | 21.8k | TokenText.split(Lines, "\n"); |
883 | 21.8k | Content.resize(Lines.size()); |
884 | 21.8k | ContentColumn.resize(Lines.size()); |
885 | 21.8k | PrefixSpaceChange.resize(Lines.size()); |
886 | 21.8k | Tokens.resize(Lines.size()); |
887 | 21.8k | Prefix.resize(Lines.size()); |
888 | 21.8k | OriginalPrefix.resize(Lines.size()); |
889 | 43.6k | for (size_t i = FirstLineIndex, e = Lines.size(); i < e; ++i) { |
890 | 21.8k | Lines[i] = Lines[i].ltrim(Blanks); |
891 | 21.8k | StringRef IndentPrefix = getLineCommentIndentPrefix(Lines[i], Style); |
892 | 21.8k | OriginalPrefix[i] = IndentPrefix; |
893 | 21.8k | const int SpacesInPrefix = llvm::count(IndentPrefix, ' '); |
894 | | |
895 | | // This lambda also considers multibyte character that is not handled in |
896 | | // functions like isPunctuation provided by CharInfo. |
897 | 42.7k | const auto NoSpaceBeforeFirstCommentChar = [&]() { |
898 | 42.7k | assert(Lines[i].size() > IndentPrefix.size()); |
899 | 0 | const char FirstCommentChar = Lines[i][IndentPrefix.size()]; |
900 | 42.7k | const unsigned FirstCharByteSize = |
901 | 42.7k | encoding::getCodePointNumBytes(FirstCommentChar, Encoding); |
902 | 42.7k | if (encoding::columnWidth( |
903 | 42.7k | Lines[i].substr(IndentPrefix.size(), FirstCharByteSize), |
904 | 42.7k | Encoding) != 1) { |
905 | 0 | return false; |
906 | 0 | } |
907 | | // In C-like comments, add a space before #. For example this is useful |
908 | | // to preserve the relative indentation when commenting out code with |
909 | | // #includes. |
910 | | // |
911 | | // In languages using # as the comment leader such as proto, don't |
912 | | // add a space to support patterns like: |
913 | | // ######### |
914 | | // # section |
915 | | // ######### |
916 | 42.7k | if (FirstCommentChar == '#' && !TokenText.starts_with("#")) |
917 | 0 | return false; |
918 | 42.7k | return FirstCommentChar == '\\' || isPunctuation(FirstCommentChar) || |
919 | 42.7k | isHorizontalWhitespace(FirstCommentChar); |
920 | 42.7k | }; |
921 | | |
922 | | // On the first line of the comment section we calculate how many spaces |
923 | | // are to be added or removed, all lines after that just get only the |
924 | | // change and we will not look at the maximum anymore. Additionally to the |
925 | | // actual first line, we calculate that when the non space Prefix changes, |
926 | | // e.g. from "///" to "//". |
927 | 21.8k | if (i == 0 || OriginalPrefix[i].rtrim(Blanks) != |
928 | 21.7k | OriginalPrefix[i - 1].rtrim(Blanks)) { |
929 | 21.7k | if (SpacesInPrefix < Minimum && Lines[i].size() > IndentPrefix.size() && |
930 | 21.7k | !NoSpaceBeforeFirstCommentChar()) { |
931 | 18.8k | FirstLineSpaceChange = Minimum - SpacesInPrefix; |
932 | 18.8k | } else if (static_cast<unsigned>(SpacesInPrefix) > |
933 | 2.88k | Style.SpacesInLineCommentPrefix.Maximum) { |
934 | 0 | FirstLineSpaceChange = |
935 | 0 | Style.SpacesInLineCommentPrefix.Maximum - SpacesInPrefix; |
936 | 2.88k | } else { |
937 | 2.88k | FirstLineSpaceChange = 0; |
938 | 2.88k | } |
939 | 21.7k | } |
940 | | |
941 | 21.8k | if (Lines[i].size() != IndentPrefix.size()) { |
942 | 21.3k | PrefixSpaceChange[i] = FirstLineSpaceChange; |
943 | | |
944 | 21.3k | if (SpacesInPrefix + PrefixSpaceChange[i] < Minimum) { |
945 | 2.52k | PrefixSpaceChange[i] += |
946 | 2.52k | Minimum - (SpacesInPrefix + PrefixSpaceChange[i]); |
947 | 2.52k | } |
948 | | |
949 | 21.3k | assert(Lines[i].size() > IndentPrefix.size()); |
950 | 0 | const auto FirstNonSpace = Lines[i][IndentPrefix.size()]; |
951 | 21.3k | const bool IsFormatComment = LineTok && switchesFormatting(*LineTok); |
952 | 21.3k | const bool LineRequiresLeadingSpace = |
953 | 21.3k | !NoSpaceBeforeFirstCommentChar() || |
954 | 21.3k | (FirstNonSpace == '}' && FirstLineSpaceChange != 0); |
955 | 21.3k | const bool AllowsSpaceChange = |
956 | 21.3k | !IsFormatComment && |
957 | 21.3k | (SpacesInPrefix != 0 || LineRequiresLeadingSpace); |
958 | | |
959 | 21.3k | if (PrefixSpaceChange[i] > 0 && AllowsSpaceChange) { |
960 | 18.8k | Prefix[i] = IndentPrefix.str(); |
961 | 18.8k | Prefix[i].append(PrefixSpaceChange[i], ' '); |
962 | 18.8k | } else if (PrefixSpaceChange[i] < 0 && AllowsSpaceChange) { |
963 | 0 | Prefix[i] = IndentPrefix |
964 | 0 | .drop_back(std::min<std::size_t>( |
965 | 0 | -PrefixSpaceChange[i], SpacesInPrefix)) |
966 | 0 | .str(); |
967 | 2.51k | } else { |
968 | 2.51k | Prefix[i] = IndentPrefix.str(); |
969 | 2.51k | } |
970 | 21.3k | } else { |
971 | | // If the IndentPrefix is the whole line, there is no content and we |
972 | | // drop just all space |
973 | 430 | Prefix[i] = IndentPrefix.drop_back(SpacesInPrefix).str(); |
974 | 430 | } |
975 | | |
976 | 0 | Tokens[i] = LineTok; |
977 | 21.8k | Content[i] = Lines[i].substr(IndentPrefix.size()); |
978 | 21.8k | ContentColumn[i] = |
979 | 21.8k | StartColumn + encoding::columnWidthWithTabs(Prefix[i], StartColumn, |
980 | 21.8k | Style.TabWidth, Encoding); |
981 | | |
982 | | // Calculate the end of the non-whitespace text in this line. |
983 | 21.8k | size_t EndOfLine = Content[i].find_last_not_of(Blanks); |
984 | 21.8k | if (EndOfLine == StringRef::npos) |
985 | 430 | EndOfLine = Content[i].size(); |
986 | 21.3k | else |
987 | 21.3k | ++EndOfLine; |
988 | 21.8k | Content[i] = Content[i].substr(0, EndOfLine); |
989 | 21.8k | } |
990 | 21.8k | LineTok = CurrentTok->Next; |
991 | 21.8k | if (CurrentTok->Next && !CurrentTok->Next->ContinuesLineCommentSection) { |
992 | | // A line comment section needs to broken by a line comment that is |
993 | | // preceded by at least two newlines. Note that we put this break here |
994 | | // instead of breaking at a previous stage during parsing, since that |
995 | | // would split the contents of the enum into two unwrapped lines in this |
996 | | // example, which is undesirable: |
997 | | // enum A { |
998 | | // a, // comment about a |
999 | | // |
1000 | | // // comment about b |
1001 | | // b |
1002 | | // }; |
1003 | | // |
1004 | | // FIXME: Consider putting separate line comment sections as children to |
1005 | | // the unwrapped line instead. |
1006 | 21.3k | break; |
1007 | 21.3k | } |
1008 | 21.8k | } |
1009 | 21.7k | } |
1010 | | |
1011 | | unsigned |
1012 | | BreakableLineCommentSection::getRangeLength(unsigned LineIndex, unsigned Offset, |
1013 | | StringRef::size_type Length, |
1014 | 31.8k | unsigned StartColumn) const { |
1015 | 31.8k | return encoding::columnWidthWithTabs( |
1016 | 31.8k | Content[LineIndex].substr(Offset, Length), StartColumn, Style.TabWidth, |
1017 | 31.8k | Encoding); |
1018 | 31.8k | } |
1019 | | |
1020 | | unsigned |
1021 | | BreakableLineCommentSection::getContentStartColumn(unsigned LineIndex, |
1022 | 25.1k | bool /*Break*/) const { |
1023 | 25.1k | return ContentColumn[LineIndex]; |
1024 | 25.1k | } |
1025 | | |
1026 | | void BreakableLineCommentSection::insertBreak( |
1027 | | unsigned LineIndex, unsigned TailOffset, Split Split, |
1028 | 1.00k | unsigned ContentIndent, WhitespaceManager &Whitespaces) const { |
1029 | 1.00k | StringRef Text = Content[LineIndex].substr(TailOffset); |
1030 | | // Compute the offset of the split relative to the beginning of the token |
1031 | | // text. |
1032 | 1.00k | unsigned BreakOffsetInToken = |
1033 | 1.00k | Text.data() - tokenAt(LineIndex).TokenText.data() + Split.first; |
1034 | 1.00k | unsigned CharsToRemove = Split.second; |
1035 | 1.00k | Whitespaces.replaceWhitespaceInToken( |
1036 | 1.00k | tokenAt(LineIndex), BreakOffsetInToken, CharsToRemove, "", |
1037 | 1.00k | Prefix[LineIndex], InPPDirective, /*Newlines=*/1, |
1038 | 1.00k | /*Spaces=*/ContentColumn[LineIndex] - Prefix[LineIndex].size()); |
1039 | 1.00k | } |
1040 | | |
1041 | | BreakableComment::Split BreakableLineCommentSection::getReflowSplit( |
1042 | 13 | unsigned LineIndex, const llvm::Regex &CommentPragmasRegex) const { |
1043 | 13 | if (!mayReflow(LineIndex, CommentPragmasRegex)) |
1044 | 13 | return Split(StringRef::npos, 0); |
1045 | | |
1046 | 0 | size_t Trimmed = Content[LineIndex].find_first_not_of(Blanks); |
1047 | | |
1048 | | // In a line comment section each line is a separate token; thus, after a |
1049 | | // split we replace all whitespace before the current line comment token |
1050 | | // (which does not need to be included in the split), plus the start of the |
1051 | | // line up to where the content starts. |
1052 | 0 | return Split(0, Trimmed != StringRef::npos ? Trimmed : 0); |
1053 | 13 | } |
1054 | | |
1055 | | void BreakableLineCommentSection::reflow(unsigned LineIndex, |
1056 | 0 | WhitespaceManager &Whitespaces) const { |
1057 | 0 | if (LineIndex > 0 && Tokens[LineIndex] != Tokens[LineIndex - 1]) { |
1058 | | // Reflow happens between tokens. Replace the whitespace between the |
1059 | | // tokens by the empty string. |
1060 | 0 | Whitespaces.replaceWhitespace( |
1061 | 0 | *Tokens[LineIndex], /*Newlines=*/0, /*Spaces=*/0, |
1062 | 0 | /*StartOfTokenColumn=*/StartColumn, /*IsAligned=*/true, |
1063 | 0 | /*InPPDirective=*/false); |
1064 | 0 | } else if (LineIndex > 0) { |
1065 | | // In case we're reflowing after the '\' in: |
1066 | | // |
1067 | | // // line comment \ |
1068 | | // // line 2 |
1069 | | // |
1070 | | // the reflow happens inside the single comment token (it is a single line |
1071 | | // comment with an unescaped newline). |
1072 | | // Replace the whitespace between the '\' and '//' with the empty string. |
1073 | | // |
1074 | | // Offset points to after the '\' relative to start of the token. |
1075 | 0 | unsigned Offset = Lines[LineIndex - 1].data() + |
1076 | 0 | Lines[LineIndex - 1].size() - |
1077 | 0 | tokenAt(LineIndex - 1).TokenText.data(); |
1078 | | // WhitespaceLength is the number of chars between the '\' and the '//' on |
1079 | | // the next line. |
1080 | 0 | unsigned WhitespaceLength = |
1081 | 0 | Lines[LineIndex].data() - tokenAt(LineIndex).TokenText.data() - Offset; |
1082 | 0 | Whitespaces.replaceWhitespaceInToken(*Tokens[LineIndex], Offset, |
1083 | 0 | /*ReplaceChars=*/WhitespaceLength, |
1084 | 0 | /*PreviousPostfix=*/"", |
1085 | 0 | /*CurrentPrefix=*/"", |
1086 | 0 | /*InPPDirective=*/false, |
1087 | 0 | /*Newlines=*/0, |
1088 | 0 | /*Spaces=*/0); |
1089 | 0 | } |
1090 | | // Replace the indent and prefix of the token with the reflow prefix. |
1091 | 0 | unsigned Offset = |
1092 | 0 | Lines[LineIndex].data() - tokenAt(LineIndex).TokenText.data(); |
1093 | 0 | unsigned WhitespaceLength = |
1094 | 0 | Content[LineIndex].data() - Lines[LineIndex].data(); |
1095 | 0 | Whitespaces.replaceWhitespaceInToken(*Tokens[LineIndex], Offset, |
1096 | 0 | /*ReplaceChars=*/WhitespaceLength, |
1097 | 0 | /*PreviousPostfix=*/"", |
1098 | 0 | /*CurrentPrefix=*/ReflowPrefix, |
1099 | 0 | /*InPPDirective=*/false, |
1100 | 0 | /*Newlines=*/0, |
1101 | 0 | /*Spaces=*/0); |
1102 | 0 | } |
1103 | | |
1104 | | void BreakableLineCommentSection::adaptStartOfLine( |
1105 | 6.47k | unsigned LineIndex, WhitespaceManager &Whitespaces) const { |
1106 | | // If this is the first line of a token, we need to inform Whitespace Manager |
1107 | | // about it: either adapt the whitespace range preceding it, or mark it as an |
1108 | | // untouchable token. |
1109 | | // This happens for instance here: |
1110 | | // // line 1 \ |
1111 | | // // line 2 |
1112 | 6.47k | if (LineIndex > 0 && Tokens[LineIndex] != Tokens[LineIndex - 1]) { |
1113 | | // This is the first line for the current token, but no reflow with the |
1114 | | // previous token is necessary. However, we still may need to adjust the |
1115 | | // start column. Note that ContentColumn[LineIndex] is the expected |
1116 | | // content column after a possible update to the prefix, hence the prefix |
1117 | | // length change is included. |
1118 | 17 | unsigned LineColumn = |
1119 | 17 | ContentColumn[LineIndex] - |
1120 | 17 | (Content[LineIndex].data() - Lines[LineIndex].data()) + |
1121 | 17 | (OriginalPrefix[LineIndex].size() - Prefix[LineIndex].size()); |
1122 | | |
1123 | | // We always want to create a replacement instead of adding an untouchable |
1124 | | // token, even if LineColumn is the same as the original column of the |
1125 | | // token. This is because WhitespaceManager doesn't align trailing |
1126 | | // comments if they are untouchable. |
1127 | 17 | Whitespaces.replaceWhitespace(*Tokens[LineIndex], |
1128 | 17 | /*Newlines=*/1, |
1129 | 17 | /*Spaces=*/LineColumn, |
1130 | 17 | /*StartOfTokenColumn=*/LineColumn, |
1131 | 17 | /*IsAligned=*/true, |
1132 | 17 | /*InPPDirective=*/false); |
1133 | 17 | } |
1134 | 6.47k | if (OriginalPrefix[LineIndex] != Prefix[LineIndex]) { |
1135 | | // Adjust the prefix if necessary. |
1136 | 5.78k | const auto SpacesToRemove = -std::min(PrefixSpaceChange[LineIndex], 0); |
1137 | 5.78k | const auto SpacesToAdd = std::max(PrefixSpaceChange[LineIndex], 0); |
1138 | 5.78k | Whitespaces.replaceWhitespaceInToken( |
1139 | 5.78k | tokenAt(LineIndex), OriginalPrefix[LineIndex].size() - SpacesToRemove, |
1140 | 5.78k | /*ReplaceChars=*/SpacesToRemove, "", "", /*InPPDirective=*/false, |
1141 | 5.78k | /*Newlines=*/0, /*Spaces=*/SpacesToAdd); |
1142 | 5.78k | } |
1143 | 6.47k | } |
1144 | | |
1145 | 21.7k | void BreakableLineCommentSection::updateNextToken(LineState &State) const { |
1146 | 21.7k | if (LastLineTok) |
1147 | 13 | State.NextToken = LastLineTok->Next; |
1148 | 21.7k | } |
1149 | | |
1150 | | bool BreakableLineCommentSection::mayReflow( |
1151 | 13 | unsigned LineIndex, const llvm::Regex &CommentPragmasRegex) const { |
1152 | | // Line comments have the indent as part of the prefix, so we need to |
1153 | | // recompute the start of the line. |
1154 | 13 | StringRef IndentContent = Content[LineIndex]; |
1155 | 13 | if (Lines[LineIndex].starts_with("//")) |
1156 | 13 | IndentContent = Lines[LineIndex].substr(2); |
1157 | | // FIXME: Decide whether we want to reflow non-regular indents: |
1158 | | // Currently, we only reflow when the OriginalPrefix[LineIndex] matches the |
1159 | | // OriginalPrefix[LineIndex-1]. That means we don't reflow |
1160 | | // // text that protrudes |
1161 | | // // into text with different indent |
1162 | | // We do reflow in that case in block comments. |
1163 | 13 | return LineIndex > 0 && !CommentPragmasRegex.match(IndentContent) && |
1164 | 13 | mayReflowContent(Content[LineIndex]) && !Tok.Finalized && |
1165 | 13 | !switchesFormatting(tokenAt(LineIndex)) && |
1166 | 13 | OriginalPrefix[LineIndex] == OriginalPrefix[LineIndex - 1]; |
1167 | 13 | } |
1168 | | |
1169 | | } // namespace format |
1170 | | } // namespace clang |