BreakableToken.cpp 38 KB

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