BreakableToken.cpp 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906
  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 "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. #define DEBUG_TYPE "format-token-breaker"
  23. namespace clang {
  24. namespace format {
  25. static const char *const Blanks = " \t\v\f\r";
  26. static bool IsBlank(char C) {
  27. switch (C) {
  28. case ' ':
  29. case '\t':
  30. case '\v':
  31. case '\f':
  32. case '\r':
  33. return true;
  34. default:
  35. return false;
  36. }
  37. }
  38. static StringRef getLineCommentIndentPrefix(StringRef Comment) {
  39. static const char *const KnownPrefixes[] = {"///", "//", "//!"};
  40. StringRef LongestPrefix;
  41. for (StringRef KnownPrefix : KnownPrefixes) {
  42. if (Comment.startswith(KnownPrefix)) {
  43. size_t PrefixLength = KnownPrefix.size();
  44. while (PrefixLength < Comment.size() && Comment[PrefixLength] == ' ')
  45. ++PrefixLength;
  46. if (PrefixLength > LongestPrefix.size())
  47. LongestPrefix = Comment.substr(0, PrefixLength);
  48. }
  49. }
  50. return LongestPrefix;
  51. }
  52. static BreakableToken::Split getCommentSplit(StringRef Text,
  53. unsigned ContentStartColumn,
  54. unsigned ColumnLimit,
  55. unsigned TabWidth,
  56. encoding::Encoding Encoding) {
  57. if (ColumnLimit <= ContentStartColumn + 1)
  58. return BreakableToken::Split(StringRef::npos, 0);
  59. unsigned MaxSplit = ColumnLimit - ContentStartColumn + 1;
  60. unsigned MaxSplitBytes = 0;
  61. for (unsigned NumChars = 0;
  62. NumChars < MaxSplit && MaxSplitBytes < Text.size();) {
  63. unsigned BytesInChar =
  64. encoding::getCodePointNumBytes(Text[MaxSplitBytes], Encoding);
  65. NumChars +=
  66. encoding::columnWidthWithTabs(Text.substr(MaxSplitBytes, BytesInChar),
  67. ContentStartColumn, TabWidth, Encoding);
  68. MaxSplitBytes += BytesInChar;
  69. }
  70. StringRef::size_type SpaceOffset = Text.find_last_of(Blanks, MaxSplitBytes);
  71. if (SpaceOffset == StringRef::npos ||
  72. // Don't break at leading whitespace.
  73. Text.find_last_not_of(Blanks, SpaceOffset) == StringRef::npos) {
  74. // Make sure that we don't break at leading whitespace that
  75. // reaches past MaxSplit.
  76. StringRef::size_type FirstNonWhitespace = Text.find_first_not_of(Blanks);
  77. if (FirstNonWhitespace == StringRef::npos)
  78. // If the comment is only whitespace, we cannot split.
  79. return BreakableToken::Split(StringRef::npos, 0);
  80. SpaceOffset = Text.find_first_of(
  81. Blanks, std::max<unsigned>(MaxSplitBytes, FirstNonWhitespace));
  82. }
  83. if (SpaceOffset != StringRef::npos && SpaceOffset != 0) {
  84. StringRef BeforeCut = Text.substr(0, SpaceOffset).rtrim(Blanks);
  85. StringRef AfterCut = Text.substr(SpaceOffset).ltrim(Blanks);
  86. return BreakableToken::Split(BeforeCut.size(),
  87. AfterCut.begin() - BeforeCut.end());
  88. }
  89. return BreakableToken::Split(StringRef::npos, 0);
  90. }
  91. static BreakableToken::Split
  92. getStringSplit(StringRef Text, unsigned UsedColumns, unsigned ColumnLimit,
  93. unsigned TabWidth, encoding::Encoding Encoding) {
  94. // FIXME: Reduce unit test case.
  95. if (Text.empty())
  96. return BreakableToken::Split(StringRef::npos, 0);
  97. if (ColumnLimit <= UsedColumns)
  98. return BreakableToken::Split(StringRef::npos, 0);
  99. unsigned MaxSplit = ColumnLimit - UsedColumns;
  100. StringRef::size_type SpaceOffset = 0;
  101. StringRef::size_type SlashOffset = 0;
  102. StringRef::size_type WordStartOffset = 0;
  103. StringRef::size_type SplitPoint = 0;
  104. for (unsigned Chars = 0;;) {
  105. unsigned Advance;
  106. if (Text[0] == '\\') {
  107. Advance = encoding::getEscapeSequenceLength(Text);
  108. Chars += Advance;
  109. } else {
  110. Advance = encoding::getCodePointNumBytes(Text[0], Encoding);
  111. Chars += encoding::columnWidthWithTabs(
  112. Text.substr(0, Advance), UsedColumns + Chars, TabWidth, Encoding);
  113. }
  114. if (Chars > MaxSplit || Text.size() <= Advance)
  115. break;
  116. if (IsBlank(Text[0]))
  117. SpaceOffset = SplitPoint;
  118. if (Text[0] == '/')
  119. SlashOffset = SplitPoint;
  120. if (Advance == 1 && !isAlphanumeric(Text[0]))
  121. WordStartOffset = SplitPoint;
  122. SplitPoint += Advance;
  123. Text = Text.substr(Advance);
  124. }
  125. if (SpaceOffset != 0)
  126. return BreakableToken::Split(SpaceOffset + 1, 0);
  127. if (SlashOffset != 0)
  128. return BreakableToken::Split(SlashOffset + 1, 0);
  129. if (WordStartOffset != 0)
  130. return BreakableToken::Split(WordStartOffset + 1, 0);
  131. if (SplitPoint != 0)
  132. return BreakableToken::Split(SplitPoint, 0);
  133. return BreakableToken::Split(StringRef::npos, 0);
  134. }
  135. bool switchesFormatting(const FormatToken &Token) {
  136. assert((Token.is(TT_BlockComment) || Token.is(TT_LineComment)) &&
  137. "formatting regions are switched by comment tokens");
  138. StringRef Content = Token.TokenText.substr(2).ltrim();
  139. return Content.startswith("clang-format on") ||
  140. Content.startswith("clang-format off");
  141. }
  142. unsigned
  143. BreakableToken::getLineLengthAfterCompression(unsigned RemainingTokenColumns,
  144. Split Split) const {
  145. // Example: consider the content
  146. // lala lala
  147. // - RemainingTokenColumns is the original number of columns, 10;
  148. // - Split is (4, 2), denoting the two spaces between the two words;
  149. //
  150. // We compute the number of columns when the split is compressed into a single
  151. // space, like:
  152. // lala lala
  153. return RemainingTokenColumns + 1 - Split.second;
  154. }
  155. unsigned BreakableSingleLineToken::getLineCount() const { return 1; }
  156. unsigned BreakableSingleLineToken::getLineLengthAfterSplit(
  157. unsigned LineIndex, unsigned TailOffset,
  158. StringRef::size_type Length) const {
  159. return StartColumn + Prefix.size() + Postfix.size() +
  160. encoding::columnWidthWithTabs(Line.substr(TailOffset, Length),
  161. StartColumn + Prefix.size(),
  162. Style.TabWidth, Encoding);
  163. }
  164. BreakableSingleLineToken::BreakableSingleLineToken(
  165. const FormatToken &Tok, unsigned StartColumn, StringRef Prefix,
  166. StringRef Postfix, bool InPPDirective, encoding::Encoding Encoding,
  167. const FormatStyle &Style)
  168. : BreakableToken(Tok, InPPDirective, Encoding, Style),
  169. StartColumn(StartColumn), Prefix(Prefix), Postfix(Postfix) {
  170. assert(Tok.TokenText.endswith(Postfix));
  171. Line = Tok.TokenText.substr(
  172. Prefix.size(), Tok.TokenText.size() - Prefix.size() - Postfix.size());
  173. }
  174. BreakableStringLiteral::BreakableStringLiteral(
  175. const FormatToken &Tok, unsigned StartColumn, StringRef Prefix,
  176. StringRef Postfix, bool InPPDirective, encoding::Encoding Encoding,
  177. const FormatStyle &Style)
  178. : BreakableSingleLineToken(Tok, StartColumn, Prefix, Postfix, InPPDirective,
  179. Encoding, Style) {}
  180. BreakableToken::Split
  181. BreakableStringLiteral::getSplit(unsigned LineIndex, unsigned TailOffset,
  182. unsigned ColumnLimit) const {
  183. return getStringSplit(Line.substr(TailOffset),
  184. StartColumn + Prefix.size() + Postfix.size(),
  185. ColumnLimit, Style.TabWidth, Encoding);
  186. }
  187. void BreakableStringLiteral::insertBreak(unsigned LineIndex,
  188. unsigned TailOffset, Split Split,
  189. WhitespaceManager &Whitespaces) {
  190. unsigned LeadingSpaces = StartColumn;
  191. // The '@' of an ObjC string literal (@"Test") does not become part of the
  192. // string token.
  193. // FIXME: It might be a cleaner solution to merge the tokens as a
  194. // precomputation step.
  195. if (Prefix.startswith("@"))
  196. --LeadingSpaces;
  197. Whitespaces.replaceWhitespaceInToken(
  198. Tok, Prefix.size() + TailOffset + Split.first, Split.second, Postfix,
  199. Prefix, InPPDirective, 1, LeadingSpaces);
  200. }
  201. BreakableComment::BreakableComment(const FormatToken &Token,
  202. unsigned StartColumn,
  203. unsigned OriginalStartColumn,
  204. bool FirstInLine, bool InPPDirective,
  205. encoding::Encoding Encoding,
  206. const FormatStyle &Style)
  207. : BreakableToken(Token, InPPDirective, Encoding, Style),
  208. StartColumn(StartColumn), OriginalStartColumn(OriginalStartColumn),
  209. FirstInLine(FirstInLine) {}
  210. unsigned BreakableComment::getLineCount() const { return Lines.size(); }
  211. BreakableToken::Split BreakableComment::getSplit(unsigned LineIndex,
  212. unsigned TailOffset,
  213. unsigned ColumnLimit) const {
  214. return getCommentSplit(Content[LineIndex].substr(TailOffset),
  215. getContentStartColumn(LineIndex, TailOffset),
  216. ColumnLimit, Style.TabWidth, Encoding);
  217. }
  218. void BreakableComment::compressWhitespace(unsigned LineIndex,
  219. unsigned TailOffset, Split Split,
  220. WhitespaceManager &Whitespaces) {
  221. StringRef Text = Content[LineIndex].substr(TailOffset);
  222. // Text is relative to the content line, but Whitespaces operates relative to
  223. // the start of the corresponding token, so compute the start of the Split
  224. // that needs to be compressed into a single space relative to the start of
  225. // its token.
  226. unsigned BreakOffsetInToken =
  227. Text.data() - tokenAt(LineIndex).TokenText.data() + Split.first;
  228. unsigned CharsToRemove = Split.second;
  229. Whitespaces.replaceWhitespaceInToken(
  230. tokenAt(LineIndex), BreakOffsetInToken, CharsToRemove, "", "",
  231. /*InPPDirective=*/false, /*Newlines=*/0, /*Spaces=*/1);
  232. }
  233. BreakableToken::Split
  234. BreakableComment::getReflowSplit(StringRef Text, StringRef ReflowPrefix,
  235. unsigned PreviousEndColumn,
  236. unsigned ColumnLimit) const {
  237. unsigned ReflowStartColumn = PreviousEndColumn + ReflowPrefix.size();
  238. StringRef TrimmedText = Text.rtrim(Blanks);
  239. // This is the width of the resulting line in case the full line of Text gets
  240. // reflown up starting at ReflowStartColumn.
  241. unsigned FullWidth = ReflowStartColumn + encoding::columnWidthWithTabs(
  242. TrimmedText, ReflowStartColumn,
  243. Style.TabWidth, Encoding);
  244. // If the full line fits up, we return a reflow split after it,
  245. // otherwise we compute the largest piece of text that fits after
  246. // ReflowStartColumn.
  247. Split ReflowSplit =
  248. FullWidth <= ColumnLimit
  249. ? Split(TrimmedText.size(), Text.size() - TrimmedText.size())
  250. : getCommentSplit(Text, ReflowStartColumn, ColumnLimit,
  251. Style.TabWidth, Encoding);
  252. // We need to be extra careful here, because while it's OK to keep a long line
  253. // if it can't be broken into smaller pieces (like when the first word of a
  254. // long line is longer than the column limit), it's not OK to reflow that long
  255. // word up. So we recompute the size of the previous line after reflowing and
  256. // only return the reflow split if that's under the line limit.
  257. if (ReflowSplit.first != StringRef::npos &&
  258. // Check if the width of the newly reflown line is under the limit.
  259. PreviousEndColumn + ReflowPrefix.size() +
  260. encoding::columnWidthWithTabs(Text.substr(0, ReflowSplit.first),
  261. PreviousEndColumn +
  262. ReflowPrefix.size(),
  263. Style.TabWidth, Encoding) <=
  264. ColumnLimit) {
  265. return ReflowSplit;
  266. }
  267. return Split(StringRef::npos, 0);
  268. }
  269. const FormatToken &BreakableComment::tokenAt(unsigned LineIndex) const {
  270. return Tokens[LineIndex] ? *Tokens[LineIndex] : Tok;
  271. }
  272. static bool mayReflowContent(StringRef Content) {
  273. Content = Content.trim(Blanks);
  274. // Lines starting with '@' commonly have special meaning.
  275. static const SmallVector<StringRef, 4> kSpecialMeaningPrefixes = {
  276. "@", "TODO", "FIXME", "XXX"};
  277. bool hasSpecialMeaningPrefix = false;
  278. for (StringRef Prefix : kSpecialMeaningPrefixes) {
  279. if (Content.startswith(Prefix)) {
  280. hasSpecialMeaningPrefix = true;
  281. break;
  282. }
  283. }
  284. // Simple heuristic for what to reflow: content should contain at least two
  285. // characters and either the first or second character must be
  286. // non-punctuation.
  287. return Content.size() >= 2 && !hasSpecialMeaningPrefix &&
  288. !Content.endswith("\\") &&
  289. // Note that this is UTF-8 safe, since if isPunctuation(Content[0]) is
  290. // true, then the first code point must be 1 byte long.
  291. (!isPunctuation(Content[0]) || !isPunctuation(Content[1]));
  292. }
  293. BreakableBlockComment::BreakableBlockComment(
  294. const FormatToken &Token, unsigned StartColumn,
  295. unsigned OriginalStartColumn, bool FirstInLine, bool InPPDirective,
  296. encoding::Encoding Encoding, const FormatStyle &Style)
  297. : BreakableComment(Token, StartColumn, OriginalStartColumn, FirstInLine,
  298. InPPDirective, Encoding, Style) {
  299. assert(Tok.is(TT_BlockComment) &&
  300. "block comment section must start with a block comment");
  301. StringRef TokenText(Tok.TokenText);
  302. assert(TokenText.startswith("/*") && TokenText.endswith("*/"));
  303. TokenText.substr(2, TokenText.size() - 4).split(Lines, "\n");
  304. int IndentDelta = StartColumn - OriginalStartColumn;
  305. Content.resize(Lines.size());
  306. Content[0] = Lines[0];
  307. ContentColumn.resize(Lines.size());
  308. // Account for the initial '/*'.
  309. ContentColumn[0] = StartColumn + 2;
  310. Tokens.resize(Lines.size());
  311. for (size_t i = 1; i < Lines.size(); ++i)
  312. adjustWhitespace(i, IndentDelta);
  313. // Align decorations with the column of the star on the first line,
  314. // that is one column after the start "/*".
  315. DecorationColumn = StartColumn + 1;
  316. // Account for comment decoration patterns like this:
  317. //
  318. // /*
  319. // ** blah blah blah
  320. // */
  321. if (Lines.size() >= 2 && Content[1].startswith("**") &&
  322. static_cast<unsigned>(ContentColumn[1]) == StartColumn) {
  323. DecorationColumn = StartColumn;
  324. }
  325. Decoration = "* ";
  326. if (Lines.size() == 1 && !FirstInLine) {
  327. // Comments for which FirstInLine is false can start on arbitrary column,
  328. // and available horizontal space can be too small to align consecutive
  329. // lines with the first one.
  330. // FIXME: We could, probably, align them to current indentation level, but
  331. // now we just wrap them without stars.
  332. Decoration = "";
  333. }
  334. for (size_t i = 1, e = Lines.size(); i < e && !Decoration.empty(); ++i) {
  335. // If the last line is empty, the closing "*/" will have a star.
  336. if (i + 1 == e && Content[i].empty())
  337. break;
  338. if (!Content[i].empty() && i + 1 != e &&
  339. Decoration.startswith(Content[i]))
  340. continue;
  341. while (!Content[i].startswith(Decoration))
  342. Decoration = Decoration.substr(0, Decoration.size() - 1);
  343. }
  344. LastLineNeedsDecoration = true;
  345. IndentAtLineBreak = ContentColumn[0] + 1;
  346. for (size_t i = 1, e = Lines.size(); i < e; ++i) {
  347. if (Content[i].empty()) {
  348. if (i + 1 == e) {
  349. // Empty last line means that we already have a star as a part of the
  350. // trailing */. We also need to preserve whitespace, so that */ is
  351. // correctly indented.
  352. LastLineNeedsDecoration = false;
  353. // Align the star in the last '*/' with the stars on the previous lines.
  354. if (e >= 2 && !Decoration.empty()) {
  355. ContentColumn[i] = DecorationColumn;
  356. }
  357. } else if (Decoration.empty()) {
  358. // For all other lines, set the start column to 0 if they're empty, so
  359. // we do not insert trailing whitespace anywhere.
  360. ContentColumn[i] = 0;
  361. }
  362. continue;
  363. }
  364. // The first line already excludes the star.
  365. // The last line excludes the star if LastLineNeedsDecoration is false.
  366. // For all other lines, adjust the line to exclude the star and
  367. // (optionally) the first whitespace.
  368. unsigned DecorationSize = Decoration.startswith(Content[i])
  369. ? Content[i].size()
  370. : Decoration.size();
  371. if (DecorationSize) {
  372. ContentColumn[i] = DecorationColumn + DecorationSize;
  373. }
  374. Content[i] = Content[i].substr(DecorationSize);
  375. if (!Decoration.startswith(Content[i]))
  376. IndentAtLineBreak =
  377. std::min<int>(IndentAtLineBreak, std::max(0, ContentColumn[i]));
  378. }
  379. IndentAtLineBreak =
  380. std::max<unsigned>(IndentAtLineBreak, Decoration.size());
  381. DEBUG({
  382. llvm::dbgs() << "IndentAtLineBreak " << IndentAtLineBreak << "\n";
  383. for (size_t i = 0; i < Lines.size(); ++i) {
  384. llvm::dbgs() << i << " |" << Content[i] << "| "
  385. << "CC=" << ContentColumn[i] << "| "
  386. << "IN=" << (Content[i].data() - Lines[i].data()) << "\n";
  387. }
  388. });
  389. }
  390. void BreakableBlockComment::adjustWhitespace(unsigned LineIndex,
  391. int IndentDelta) {
  392. // When in a preprocessor directive, the trailing backslash in a block comment
  393. // is not needed, but can serve a purpose of uniformity with necessary escaped
  394. // newlines outside the comment. In this case we remove it here before
  395. // trimming the trailing whitespace. The backslash will be re-added later when
  396. // inserting a line break.
  397. size_t EndOfPreviousLine = Lines[LineIndex - 1].size();
  398. if (InPPDirective && Lines[LineIndex - 1].endswith("\\"))
  399. --EndOfPreviousLine;
  400. // Calculate the end of the non-whitespace text in the previous line.
  401. EndOfPreviousLine =
  402. Lines[LineIndex - 1].find_last_not_of(Blanks, EndOfPreviousLine);
  403. if (EndOfPreviousLine == StringRef::npos)
  404. EndOfPreviousLine = 0;
  405. else
  406. ++EndOfPreviousLine;
  407. // Calculate the start of the non-whitespace text in the current line.
  408. size_t StartOfLine = Lines[LineIndex].find_first_not_of(Blanks);
  409. if (StartOfLine == StringRef::npos)
  410. StartOfLine = Lines[LineIndex].rtrim("\r\n").size();
  411. StringRef Whitespace = Lines[LineIndex].substr(0, StartOfLine);
  412. // Adjust Lines to only contain relevant text.
  413. size_t PreviousContentOffset =
  414. Content[LineIndex - 1].data() - Lines[LineIndex - 1].data();
  415. Content[LineIndex - 1] = Lines[LineIndex - 1].substr(
  416. PreviousContentOffset, EndOfPreviousLine - PreviousContentOffset);
  417. Content[LineIndex] = Lines[LineIndex].substr(StartOfLine);
  418. // Adjust the start column uniformly across all lines.
  419. ContentColumn[LineIndex] =
  420. encoding::columnWidthWithTabs(Whitespace, 0, Style.TabWidth, Encoding) +
  421. IndentDelta;
  422. }
  423. unsigned BreakableBlockComment::getLineLengthAfterSplit(
  424. unsigned LineIndex, unsigned TailOffset,
  425. StringRef::size_type Length) const {
  426. unsigned ContentStartColumn = getContentStartColumn(LineIndex, TailOffset);
  427. unsigned LineLength =
  428. ContentStartColumn + encoding::columnWidthWithTabs(
  429. Content[LineIndex].substr(TailOffset, Length),
  430. ContentStartColumn, Style.TabWidth, Encoding);
  431. // The last line gets a "*/" postfix.
  432. if (LineIndex + 1 == Lines.size()) {
  433. LineLength += 2;
  434. // We never need a decoration when breaking just the trailing "*/" postfix.
  435. // Note that checking that Length == 0 is not enough, since Length could
  436. // also be StringRef::npos.
  437. if (Content[LineIndex].substr(TailOffset, Length).empty()) {
  438. LineLength -= Decoration.size();
  439. }
  440. }
  441. return LineLength;
  442. }
  443. void BreakableBlockComment::insertBreak(unsigned LineIndex, unsigned TailOffset,
  444. Split Split,
  445. WhitespaceManager &Whitespaces) {
  446. StringRef Text = Content[LineIndex].substr(TailOffset);
  447. StringRef Prefix = Decoration;
  448. // We need this to account for the case when we have a decoration "* " for all
  449. // the lines except for the last one, where the star in "*/" acts as a
  450. // decoration.
  451. unsigned LocalIndentAtLineBreak = IndentAtLineBreak;
  452. if (LineIndex + 1 == Lines.size() &&
  453. Text.size() == Split.first + Split.second) {
  454. // For the last line we need to break before "*/", but not to add "* ".
  455. Prefix = "";
  456. if (LocalIndentAtLineBreak >= 2)
  457. LocalIndentAtLineBreak -= 2;
  458. }
  459. // The split offset is from the beginning of the line. Convert it to an offset
  460. // from the beginning of the token text.
  461. unsigned BreakOffsetInToken =
  462. Text.data() - tokenAt(LineIndex).TokenText.data() + Split.first;
  463. unsigned CharsToRemove = Split.second;
  464. assert(LocalIndentAtLineBreak >= Prefix.size());
  465. Whitespaces.replaceWhitespaceInToken(
  466. tokenAt(LineIndex), BreakOffsetInToken, CharsToRemove, "", Prefix,
  467. InPPDirective, /*Newlines=*/1,
  468. /*Spaces=*/LocalIndentAtLineBreak - Prefix.size());
  469. }
  470. BreakableToken::Split BreakableBlockComment::getSplitBefore(
  471. unsigned LineIndex,
  472. unsigned PreviousEndColumn,
  473. unsigned ColumnLimit,
  474. llvm::Regex &CommentPragmasRegex) const {
  475. if (!mayReflow(LineIndex, CommentPragmasRegex))
  476. return Split(StringRef::npos, 0);
  477. StringRef TrimmedContent = Content[LineIndex].ltrim(Blanks);
  478. return getReflowSplit(TrimmedContent, ReflowPrefix, PreviousEndColumn,
  479. ColumnLimit);
  480. }
  481. unsigned BreakableBlockComment::getReflownColumn(
  482. StringRef Content,
  483. unsigned LineIndex,
  484. unsigned PreviousEndColumn) const {
  485. unsigned StartColumn = PreviousEndColumn + ReflowPrefix.size();
  486. // If this is the last line, it will carry around its '*/' postfix.
  487. unsigned PostfixLength = (LineIndex + 1 == Lines.size() ? 2 : 0);
  488. // The line is composed of previous text, reflow prefix, reflown text and
  489. // postfix.
  490. unsigned ReflownColumn =
  491. StartColumn + encoding::columnWidthWithTabs(Content, StartColumn,
  492. Style.TabWidth, Encoding) +
  493. PostfixLength;
  494. return ReflownColumn;
  495. }
  496. unsigned BreakableBlockComment::getLineLengthAfterSplitBefore(
  497. unsigned LineIndex, unsigned TailOffset,
  498. unsigned PreviousEndColumn,
  499. unsigned ColumnLimit,
  500. Split SplitBefore) const {
  501. if (SplitBefore.first == StringRef::npos ||
  502. // Block comment line contents contain the trailing whitespace after the
  503. // decoration, so the need of left trim. Note that this behavior is
  504. // consistent with the breaking of block comments where the indentation of
  505. // a broken line is uniform across all the lines of the block comment.
  506. SplitBefore.first + SplitBefore.second <
  507. Content[LineIndex].ltrim().size()) {
  508. // A piece of line, not the whole, gets reflown.
  509. return getLineLengthAfterSplit(LineIndex, TailOffset, StringRef::npos);
  510. } else {
  511. // The whole line gets reflown, need to check if we need to insert a break
  512. // for the postfix or not.
  513. StringRef TrimmedContent = Content[LineIndex].ltrim(Blanks);
  514. unsigned ReflownColumn =
  515. getReflownColumn(TrimmedContent, LineIndex, PreviousEndColumn);
  516. if (ReflownColumn <= ColumnLimit) {
  517. return ReflownColumn;
  518. }
  519. return getLineLengthAfterSplit(LineIndex, TailOffset, StringRef::npos);
  520. }
  521. }
  522. void BreakableBlockComment::replaceWhitespaceBefore(
  523. unsigned LineIndex, unsigned PreviousEndColumn, unsigned ColumnLimit,
  524. Split SplitBefore, WhitespaceManager &Whitespaces) {
  525. if (LineIndex == 0) return;
  526. StringRef TrimmedContent = Content[LineIndex].ltrim(Blanks);
  527. if (SplitBefore.first != StringRef::npos) {
  528. // Here we need to reflow.
  529. assert(Tokens[LineIndex - 1] == Tokens[LineIndex] &&
  530. "Reflowing whitespace within a token");
  531. // This is the offset of the end of the last line relative to the start of
  532. // the token text in the token.
  533. unsigned WhitespaceOffsetInToken = Content[LineIndex - 1].data() +
  534. Content[LineIndex - 1].size() -
  535. tokenAt(LineIndex).TokenText.data();
  536. unsigned WhitespaceLength = TrimmedContent.data() -
  537. tokenAt(LineIndex).TokenText.data() -
  538. WhitespaceOffsetInToken;
  539. Whitespaces.replaceWhitespaceInToken(
  540. tokenAt(LineIndex), WhitespaceOffsetInToken,
  541. /*ReplaceChars=*/WhitespaceLength, /*PreviousPostfix=*/"",
  542. /*CurrentPrefix=*/ReflowPrefix, InPPDirective, /*Newlines=*/0,
  543. /*Spaces=*/0);
  544. // Check if we need to also insert a break at the whitespace range.
  545. // For this we first adapt the reflow split relative to the beginning of the
  546. // content.
  547. // Note that we don't need a penalty for this break, since it doesn't change
  548. // the total number of lines.
  549. Split BreakSplit = SplitBefore;
  550. BreakSplit.first += TrimmedContent.data() - Content[LineIndex].data();
  551. unsigned ReflownColumn =
  552. getReflownColumn(TrimmedContent, LineIndex, PreviousEndColumn);
  553. if (ReflownColumn > ColumnLimit) {
  554. insertBreak(LineIndex, 0, BreakSplit, Whitespaces);
  555. }
  556. return;
  557. }
  558. // Here no reflow with the previous line will happen.
  559. // Fix the decoration of the line at LineIndex.
  560. StringRef Prefix = Decoration;
  561. if (Content[LineIndex].empty()) {
  562. if (LineIndex + 1 == Lines.size()) {
  563. if (!LastLineNeedsDecoration) {
  564. // If the last line was empty, we don't need a prefix, as the */ will
  565. // line up with the decoration (if it exists).
  566. Prefix = "";
  567. }
  568. } else if (!Decoration.empty()) {
  569. // For other empty lines, if we do have a decoration, adapt it to not
  570. // contain a trailing whitespace.
  571. Prefix = Prefix.substr(0, 1);
  572. }
  573. } else {
  574. if (ContentColumn[LineIndex] == 1) {
  575. // This line starts immediately after the decorating *.
  576. Prefix = Prefix.substr(0, 1);
  577. }
  578. }
  579. // This is the offset of the end of the last line relative to the start of the
  580. // token text in the token.
  581. unsigned WhitespaceOffsetInToken = Content[LineIndex - 1].data() +
  582. Content[LineIndex - 1].size() -
  583. tokenAt(LineIndex).TokenText.data();
  584. unsigned WhitespaceLength = Content[LineIndex].data() -
  585. tokenAt(LineIndex).TokenText.data() -
  586. WhitespaceOffsetInToken;
  587. Whitespaces.replaceWhitespaceInToken(
  588. tokenAt(LineIndex), WhitespaceOffsetInToken, WhitespaceLength, "", Prefix,
  589. InPPDirective, /*Newlines=*/1, ContentColumn[LineIndex] - Prefix.size());
  590. }
  591. bool BreakableBlockComment::mayReflow(unsigned LineIndex,
  592. llvm::Regex &CommentPragmasRegex) const {
  593. // Content[LineIndex] may exclude the indent after the '*' decoration. In that
  594. // case, we compute the start of the comment pragma manually.
  595. StringRef IndentContent = Content[LineIndex];
  596. if (Lines[LineIndex].ltrim(Blanks).startswith("*")) {
  597. IndentContent = Lines[LineIndex].ltrim(Blanks).substr(1);
  598. }
  599. return LineIndex > 0 && !CommentPragmasRegex.match(IndentContent) &&
  600. mayReflowContent(Content[LineIndex]) && !Tok.Finalized &&
  601. !switchesFormatting(tokenAt(LineIndex));
  602. }
  603. unsigned
  604. BreakableBlockComment::getContentStartColumn(unsigned LineIndex,
  605. unsigned TailOffset) const {
  606. // If we break, we always break at the predefined indent.
  607. if (TailOffset != 0)
  608. return IndentAtLineBreak;
  609. return std::max(0, ContentColumn[LineIndex]);
  610. }
  611. BreakableLineCommentSection::BreakableLineCommentSection(
  612. const FormatToken &Token, unsigned StartColumn,
  613. unsigned OriginalStartColumn, bool FirstInLine, bool InPPDirective,
  614. encoding::Encoding Encoding, const FormatStyle &Style)
  615. : BreakableComment(Token, StartColumn, OriginalStartColumn, FirstInLine,
  616. InPPDirective, Encoding, Style) {
  617. assert(Tok.is(TT_LineComment) &&
  618. "line comment section must start with a line comment");
  619. FormatToken *LineTok = nullptr;
  620. for (const FormatToken *CurrentTok = &Tok;
  621. CurrentTok && CurrentTok->is(TT_LineComment);
  622. CurrentTok = CurrentTok->Next) {
  623. LastLineTok = LineTok;
  624. StringRef TokenText(CurrentTok->TokenText);
  625. assert(TokenText.startswith("//"));
  626. size_t FirstLineIndex = Lines.size();
  627. TokenText.split(Lines, "\n");
  628. Content.resize(Lines.size());
  629. ContentColumn.resize(Lines.size());
  630. OriginalContentColumn.resize(Lines.size());
  631. Tokens.resize(Lines.size());
  632. Prefix.resize(Lines.size());
  633. OriginalPrefix.resize(Lines.size());
  634. for (size_t i = FirstLineIndex, e = Lines.size(); i < e; ++i) {
  635. // We need to trim the blanks in case this is not the first line in a
  636. // multiline comment. Then the indent is included in Lines[i].
  637. StringRef IndentPrefix =
  638. getLineCommentIndentPrefix(Lines[i].ltrim(Blanks));
  639. assert(IndentPrefix.startswith("//"));
  640. OriginalPrefix[i] = Prefix[i] = IndentPrefix;
  641. if (Lines[i].size() > Prefix[i].size() &&
  642. isAlphanumeric(Lines[i][Prefix[i].size()])) {
  643. if (Prefix[i] == "//")
  644. Prefix[i] = "// ";
  645. else if (Prefix[i] == "///")
  646. Prefix[i] = "/// ";
  647. else if (Prefix[i] == "//!")
  648. Prefix[i] = "//! ";
  649. }
  650. Tokens[i] = LineTok;
  651. Content[i] = Lines[i].substr(IndentPrefix.size());
  652. OriginalContentColumn[i] =
  653. StartColumn +
  654. encoding::columnWidthWithTabs(OriginalPrefix[i],
  655. StartColumn,
  656. Style.TabWidth,
  657. Encoding);
  658. ContentColumn[i] =
  659. StartColumn +
  660. encoding::columnWidthWithTabs(Prefix[i],
  661. StartColumn,
  662. Style.TabWidth,
  663. Encoding);
  664. // Calculate the end of the non-whitespace text in this line.
  665. size_t EndOfLine = Content[i].find_last_not_of(Blanks);
  666. if (EndOfLine == StringRef::npos)
  667. EndOfLine = Content[i].size();
  668. else
  669. ++EndOfLine;
  670. Content[i] = Content[i].substr(0, EndOfLine);
  671. }
  672. LineTok = CurrentTok->Next;
  673. if (CurrentTok->Next && !CurrentTok->Next->ContinuesLineCommentSection) {
  674. // A line comment section needs to broken by a line comment that is
  675. // preceded by at least two newlines. Note that we put this break here
  676. // instead of breaking at a previous stage during parsing, since that
  677. // would split the contents of the enum into two unwrapped lines in this
  678. // example, which is undesirable:
  679. // enum A {
  680. // a, // comment about a
  681. //
  682. // // comment about b
  683. // b
  684. // };
  685. //
  686. // FIXME: Consider putting separate line comment sections as children to
  687. // the unwrapped line instead.
  688. break;
  689. }
  690. }
  691. }
  692. unsigned BreakableLineCommentSection::getLineLengthAfterSplit(
  693. unsigned LineIndex, unsigned TailOffset,
  694. StringRef::size_type Length) const {
  695. unsigned ContentStartColumn =
  696. (TailOffset == 0 ? ContentColumn[LineIndex]
  697. : OriginalContentColumn[LineIndex]);
  698. return ContentStartColumn + encoding::columnWidthWithTabs(
  699. Content[LineIndex].substr(TailOffset, Length),
  700. ContentStartColumn, Style.TabWidth, Encoding);
  701. }
  702. void BreakableLineCommentSection::insertBreak(unsigned LineIndex,
  703. unsigned TailOffset, Split Split,
  704. WhitespaceManager &Whitespaces) {
  705. StringRef Text = Content[LineIndex].substr(TailOffset);
  706. // Compute the offset of the split relative to the beginning of the token
  707. // text.
  708. unsigned BreakOffsetInToken =
  709. Text.data() - tokenAt(LineIndex).TokenText.data() + Split.first;
  710. unsigned CharsToRemove = Split.second;
  711. // Compute the size of the new indent, including the size of the new prefix of
  712. // the newly broken line.
  713. unsigned IndentAtLineBreak = OriginalContentColumn[LineIndex] +
  714. Prefix[LineIndex].size() -
  715. OriginalPrefix[LineIndex].size();
  716. assert(IndentAtLineBreak >= Prefix[LineIndex].size());
  717. Whitespaces.replaceWhitespaceInToken(
  718. tokenAt(LineIndex), BreakOffsetInToken, CharsToRemove, "",
  719. Prefix[LineIndex], InPPDirective, /*Newlines=*/1,
  720. /*Spaces=*/IndentAtLineBreak - Prefix[LineIndex].size());
  721. }
  722. BreakableComment::Split BreakableLineCommentSection::getSplitBefore(
  723. unsigned LineIndex, unsigned PreviousEndColumn, unsigned ColumnLimit,
  724. llvm::Regex &CommentPragmasRegex) const {
  725. if (!mayReflow(LineIndex, CommentPragmasRegex))
  726. return Split(StringRef::npos, 0);
  727. return getReflowSplit(Content[LineIndex], ReflowPrefix, PreviousEndColumn,
  728. ColumnLimit);
  729. }
  730. unsigned BreakableLineCommentSection::getLineLengthAfterSplitBefore(
  731. unsigned LineIndex, unsigned TailOffset,
  732. unsigned PreviousEndColumn,
  733. unsigned ColumnLimit,
  734. Split SplitBefore) const {
  735. if (SplitBefore.first == StringRef::npos ||
  736. SplitBefore.first + SplitBefore.second < Content[LineIndex].size()) {
  737. // A piece of line, not the whole line, gets reflown.
  738. return getLineLengthAfterSplit(LineIndex, TailOffset, StringRef::npos);
  739. } else {
  740. // The whole line gets reflown.
  741. unsigned StartColumn = PreviousEndColumn + ReflowPrefix.size();
  742. return StartColumn + encoding::columnWidthWithTabs(Content[LineIndex],
  743. StartColumn,
  744. Style.TabWidth,
  745. Encoding);
  746. }
  747. }
  748. void BreakableLineCommentSection::replaceWhitespaceBefore(
  749. unsigned LineIndex, unsigned PreviousEndColumn, unsigned ColumnLimit,
  750. Split SplitBefore, WhitespaceManager &Whitespaces) {
  751. // If this is the first line of a token, we need to inform Whitespace Manager
  752. // about it: either adapt the whitespace range preceding it, or mark it as an
  753. // untouchable token.
  754. // This happens for instance here:
  755. // // line 1 \
  756. // // line 2
  757. if (LineIndex > 0 && Tokens[LineIndex] != Tokens[LineIndex - 1]) {
  758. if (SplitBefore.first != StringRef::npos) {
  759. // Reflow happens between tokens. Replace the whitespace between the
  760. // tokens by the empty string.
  761. Whitespaces.replaceWhitespace(
  762. *Tokens[LineIndex], /*Newlines=*/0, /*Spaces=*/0,
  763. /*StartOfTokenColumn=*/StartColumn, /*InPPDirective=*/false);
  764. // Replace the indent and prefix of the token with the reflow prefix.
  765. unsigned WhitespaceLength =
  766. Content[LineIndex].data() - tokenAt(LineIndex).TokenText.data();
  767. Whitespaces.replaceWhitespaceInToken(*Tokens[LineIndex],
  768. /*Offset=*/0,
  769. /*ReplaceChars=*/WhitespaceLength,
  770. /*PreviousPostfix=*/"",
  771. /*CurrentPrefix=*/ReflowPrefix,
  772. /*InPPDirective=*/false,
  773. /*Newlines=*/0,
  774. /*Spaces=*/0);
  775. } else {
  776. // This is the first line for the current token, but no reflow with the
  777. // previous token is necessary. However, we still may need to adjust the
  778. // start column. Note that ContentColumn[LineIndex] is the expected
  779. // content column after a possible update to the prefix, hence the prefix
  780. // length change is included.
  781. unsigned LineColumn =
  782. ContentColumn[LineIndex] -
  783. (Content[LineIndex].data() - Lines[LineIndex].data()) +
  784. (OriginalPrefix[LineIndex].size() - Prefix[LineIndex].size());
  785. // We always want to create a replacement instead of adding an untouchable
  786. // token, even if LineColumn is the same as the original column of the
  787. // token. This is because WhitespaceManager doesn't align trailing
  788. // comments if they are untouchable.
  789. Whitespaces.replaceWhitespace(*Tokens[LineIndex],
  790. /*Newlines=*/1,
  791. /*Spaces=*/LineColumn,
  792. /*StartOfTokenColumn=*/LineColumn,
  793. /*InPPDirective=*/false);
  794. }
  795. }
  796. if (OriginalPrefix[LineIndex] != Prefix[LineIndex]) {
  797. // Adjust the prefix if necessary.
  798. // Take care of the space possibly introduced after a decoration.
  799. assert(Prefix[LineIndex] == (OriginalPrefix[LineIndex] + " ").str() &&
  800. "Expecting a line comment prefix to differ from original by at most "
  801. "a space");
  802. Whitespaces.replaceWhitespaceInToken(
  803. tokenAt(LineIndex), OriginalPrefix[LineIndex].size(), 0, "", "",
  804. /*InPPDirective=*/false, /*Newlines=*/0, /*Spaces=*/1);
  805. }
  806. // Add a break after a reflow split has been introduced, if necessary.
  807. // Note that this break doesn't need to be penalized, since it doesn't change
  808. // the number of lines.
  809. if (SplitBefore.first != StringRef::npos &&
  810. SplitBefore.first + SplitBefore.second < Content[LineIndex].size()) {
  811. insertBreak(LineIndex, 0, SplitBefore, Whitespaces);
  812. }
  813. }
  814. void BreakableLineCommentSection::updateNextToken(LineState& State) const {
  815. if (LastLineTok) {
  816. State.NextToken = LastLineTok->Next;
  817. }
  818. }
  819. bool BreakableLineCommentSection::mayReflow(
  820. unsigned LineIndex, llvm::Regex &CommentPragmasRegex) const {
  821. // Line comments have the indent as part of the prefix, so we need to
  822. // recompute the start of the line.
  823. StringRef IndentContent = Content[LineIndex];
  824. if (Lines[LineIndex].startswith("//")) {
  825. IndentContent = Lines[LineIndex].substr(2);
  826. }
  827. return LineIndex > 0 && !CommentPragmasRegex.match(IndentContent) &&
  828. mayReflowContent(Content[LineIndex]) && !Tok.Finalized &&
  829. !switchesFormatting(tokenAt(LineIndex)) &&
  830. OriginalPrefix[LineIndex] == OriginalPrefix[LineIndex - 1];
  831. }
  832. unsigned
  833. BreakableLineCommentSection::getContentStartColumn(unsigned LineIndex,
  834. unsigned TailOffset) const {
  835. if (TailOffset != 0) {
  836. return OriginalContentColumn[LineIndex];
  837. }
  838. return ContentColumn[LineIndex];
  839. }
  840. } // namespace format
  841. } // namespace clang