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