BreakableToken.cpp 18 KB

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