BreakableToken.cpp 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028
  1. //===--- BreakableToken.cpp - Format C++ code -----------------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. ///
  9. /// \file
  10. /// Contains implementation of BreakableToken class and classes derived
  11. /// from it.
  12. ///
  13. //===----------------------------------------------------------------------===//
  14. #include "BreakableToken.h"
  15. #include "ContinuationIndenter.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 constexpr StringRef 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 StringRef getLineCommentIndentPrefix(StringRef Comment,
  38. const FormatStyle &Style) {
  39. static constexpr StringRef KnownCStylePrefixes[] = {"///<", "//!<", "///",
  40. "//!", "//:", "//"};
  41. static constexpr StringRef KnownTextProtoPrefixes[] = {"####", "###", "##",
  42. "//", "#"};
  43. ArrayRef<StringRef> KnownPrefixes(KnownCStylePrefixes);
  44. if (Style.Language == FormatStyle::LK_TextProto)
  45. KnownPrefixes = KnownTextProtoPrefixes;
  46. assert(std::is_sorted(KnownPrefixes.begin(), KnownPrefixes.end(),
  47. [](StringRef Lhs, StringRef Rhs) noexcept {
  48. return Lhs.size() > Rhs.size();
  49. }));
  50. for (StringRef KnownPrefix : KnownPrefixes) {
  51. if (Comment.startswith(KnownPrefix)) {
  52. const auto PrefixLength =
  53. Comment.find_first_not_of(' ', KnownPrefix.size());
  54. return Comment.substr(0, PrefixLength);
  55. }
  56. }
  57. return {};
  58. }
  59. static BreakableToken::Split
  60. getCommentSplit(StringRef Text, unsigned ContentStartColumn,
  61. unsigned ColumnLimit, unsigned TabWidth,
  62. encoding::Encoding Encoding, const FormatStyle &Style,
  63. bool DecorationEndsWithStar = false) {
  64. LLVM_DEBUG(llvm::dbgs() << "Comment split: \"" << Text
  65. << "\", Column limit: " << ColumnLimit
  66. << ", Content start: " << ContentStartColumn << "\n");
  67. if (ColumnLimit <= ContentStartColumn + 1)
  68. return BreakableToken::Split(StringRef::npos, 0);
  69. unsigned MaxSplit = ColumnLimit - ContentStartColumn + 1;
  70. unsigned MaxSplitBytes = 0;
  71. for (unsigned NumChars = 0;
  72. NumChars < MaxSplit && MaxSplitBytes < Text.size();) {
  73. unsigned BytesInChar =
  74. encoding::getCodePointNumBytes(Text[MaxSplitBytes], Encoding);
  75. NumChars +=
  76. encoding::columnWidthWithTabs(Text.substr(MaxSplitBytes, BytesInChar),
  77. ContentStartColumn, TabWidth, Encoding);
  78. MaxSplitBytes += BytesInChar;
  79. }
  80. // In JavaScript, some @tags can be followed by {, and machinery that parses
  81. // these comments will fail to understand the comment if followed by a line
  82. // break. So avoid ever breaking before a {.
  83. if (Style.isJavaScript()) {
  84. StringRef::size_type SpaceOffset =
  85. Text.find_first_of(Blanks, MaxSplitBytes);
  86. if (SpaceOffset != StringRef::npos && SpaceOffset + 1 < Text.size() &&
  87. Text[SpaceOffset + 1] == '{') {
  88. MaxSplitBytes = SpaceOffset + 1;
  89. }
  90. }
  91. StringRef::size_type SpaceOffset = Text.find_last_of(Blanks, MaxSplitBytes);
  92. static const auto kNumberedListRegexp = llvm::Regex("^[1-9][0-9]?\\.");
  93. // Some spaces are unacceptable to break on, rewind past them.
  94. while (SpaceOffset != StringRef::npos) {
  95. // If a line-comment ends with `\`, the next line continues the comment,
  96. // whether or not it starts with `//`. This is confusing and triggers
  97. // -Wcomment.
  98. // Avoid introducing multiline comments by not allowing a break right
  99. // after '\'.
  100. if (Style.isCpp()) {
  101. StringRef::size_type LastNonBlank =
  102. Text.find_last_not_of(Blanks, SpaceOffset);
  103. if (LastNonBlank != StringRef::npos && Text[LastNonBlank] == '\\') {
  104. SpaceOffset = Text.find_last_of(Blanks, LastNonBlank);
  105. continue;
  106. }
  107. }
  108. // Do not split before a number followed by a dot: this would be interpreted
  109. // as a numbered list, which would prevent re-flowing in subsequent passes.
  110. if (kNumberedListRegexp.match(Text.substr(SpaceOffset).ltrim(Blanks))) {
  111. SpaceOffset = Text.find_last_of(Blanks, SpaceOffset);
  112. continue;
  113. }
  114. // Avoid ever breaking before a @tag or a { in JavaScript.
  115. if (Style.isJavaScript() && SpaceOffset + 1 < Text.size() &&
  116. (Text[SpaceOffset + 1] == '{' || Text[SpaceOffset + 1] == '@')) {
  117. SpaceOffset = Text.find_last_of(Blanks, SpaceOffset);
  118. continue;
  119. }
  120. break;
  121. }
  122. if (SpaceOffset == StringRef::npos ||
  123. // Don't break at leading whitespace.
  124. Text.find_last_not_of(Blanks, SpaceOffset) == StringRef::npos) {
  125. // Make sure that we don't break at leading whitespace that
  126. // reaches past MaxSplit.
  127. StringRef::size_type FirstNonWhitespace = Text.find_first_not_of(Blanks);
  128. if (FirstNonWhitespace == StringRef::npos)
  129. // If the comment is only whitespace, we cannot split.
  130. return BreakableToken::Split(StringRef::npos, 0);
  131. SpaceOffset = Text.find_first_of(
  132. Blanks, std::max<unsigned>(MaxSplitBytes, FirstNonWhitespace));
  133. }
  134. if (SpaceOffset != StringRef::npos && SpaceOffset != 0) {
  135. // adaptStartOfLine will break after lines starting with /** if the comment
  136. // is broken anywhere. Avoid emitting this break twice here.
  137. // Example: in /** longtextcomesherethatbreaks */ (with ColumnLimit 20) will
  138. // insert a break after /**, so this code must not insert the same break.
  139. if (SpaceOffset == 1 && Text[SpaceOffset - 1] == '*')
  140. return BreakableToken::Split(StringRef::npos, 0);
  141. StringRef BeforeCut = Text.substr(0, SpaceOffset).rtrim(Blanks);
  142. StringRef AfterCut = Text.substr(SpaceOffset);
  143. // Don't trim the leading blanks if it would create a */ after the break.
  144. if (!DecorationEndsWithStar || AfterCut.size() <= 1 || AfterCut[1] != '/')
  145. AfterCut = AfterCut.ltrim(Blanks);
  146. return BreakableToken::Split(BeforeCut.size(),
  147. AfterCut.begin() - BeforeCut.end());
  148. }
  149. return BreakableToken::Split(StringRef::npos, 0);
  150. }
  151. static BreakableToken::Split
  152. getStringSplit(StringRef Text, unsigned UsedColumns, unsigned ColumnLimit,
  153. unsigned TabWidth, encoding::Encoding Encoding) {
  154. // FIXME: Reduce unit test case.
  155. if (Text.empty())
  156. return BreakableToken::Split(StringRef::npos, 0);
  157. if (ColumnLimit <= UsedColumns)
  158. return BreakableToken::Split(StringRef::npos, 0);
  159. unsigned MaxSplit = ColumnLimit - UsedColumns;
  160. StringRef::size_type SpaceOffset = 0;
  161. StringRef::size_type SlashOffset = 0;
  162. StringRef::size_type WordStartOffset = 0;
  163. StringRef::size_type SplitPoint = 0;
  164. for (unsigned Chars = 0;;) {
  165. unsigned Advance;
  166. if (Text[0] == '\\') {
  167. Advance = encoding::getEscapeSequenceLength(Text);
  168. Chars += Advance;
  169. } else {
  170. Advance = encoding::getCodePointNumBytes(Text[0], Encoding);
  171. Chars += encoding::columnWidthWithTabs(
  172. Text.substr(0, Advance), UsedColumns + Chars, TabWidth, Encoding);
  173. }
  174. if (Chars > MaxSplit || Text.size() <= Advance)
  175. break;
  176. if (IsBlank(Text[0]))
  177. SpaceOffset = SplitPoint;
  178. if (Text[0] == '/')
  179. SlashOffset = SplitPoint;
  180. if (Advance == 1 && !isAlphanumeric(Text[0]))
  181. WordStartOffset = SplitPoint;
  182. SplitPoint += Advance;
  183. Text = Text.substr(Advance);
  184. }
  185. if (SpaceOffset != 0)
  186. return BreakableToken::Split(SpaceOffset + 1, 0);
  187. if (SlashOffset != 0)
  188. return BreakableToken::Split(SlashOffset + 1, 0);
  189. if (WordStartOffset != 0)
  190. return BreakableToken::Split(WordStartOffset + 1, 0);
  191. if (SplitPoint != 0)
  192. return BreakableToken::Split(SplitPoint, 0);
  193. return BreakableToken::Split(StringRef::npos, 0);
  194. }
  195. bool switchesFormatting(const FormatToken &Token) {
  196. assert((Token.is(TT_BlockComment) || Token.is(TT_LineComment)) &&
  197. "formatting regions are switched by comment tokens");
  198. StringRef Content = Token.TokenText.substr(2).ltrim();
  199. return Content.startswith("clang-format on") ||
  200. Content.startswith("clang-format off");
  201. }
  202. unsigned
  203. BreakableToken::getLengthAfterCompression(unsigned RemainingTokenColumns,
  204. Split Split) const {
  205. // Example: consider the content
  206. // lala lala
  207. // - RemainingTokenColumns is the original number of columns, 10;
  208. // - Split is (4, 2), denoting the two spaces between the two words;
  209. //
  210. // We compute the number of columns when the split is compressed into a single
  211. // space, like:
  212. // lala lala
  213. //
  214. // FIXME: Correctly measure the length of whitespace in Split.second so it
  215. // works with tabs.
  216. return RemainingTokenColumns + 1 - Split.second;
  217. }
  218. unsigned BreakableStringLiteral::getLineCount() const { return 1; }
  219. unsigned BreakableStringLiteral::getRangeLength(unsigned LineIndex,
  220. unsigned Offset,
  221. StringRef::size_type Length,
  222. unsigned StartColumn) const {
  223. llvm_unreachable("Getting the length of a part of the string literal "
  224. "indicates that the code tries to reflow it.");
  225. }
  226. unsigned
  227. BreakableStringLiteral::getRemainingLength(unsigned LineIndex, unsigned Offset,
  228. unsigned StartColumn) const {
  229. return UnbreakableTailLength + Postfix.size() +
  230. encoding::columnWidthWithTabs(Line.substr(Offset), StartColumn,
  231. Style.TabWidth, Encoding);
  232. }
  233. unsigned BreakableStringLiteral::getContentStartColumn(unsigned LineIndex,
  234. bool Break) const {
  235. return StartColumn + Prefix.size();
  236. }
  237. BreakableStringLiteral::BreakableStringLiteral(
  238. const FormatToken &Tok, unsigned StartColumn, StringRef Prefix,
  239. StringRef Postfix, unsigned UnbreakableTailLength, bool InPPDirective,
  240. encoding::Encoding Encoding, const FormatStyle &Style)
  241. : BreakableToken(Tok, InPPDirective, Encoding, Style),
  242. StartColumn(StartColumn), Prefix(Prefix), Postfix(Postfix),
  243. UnbreakableTailLength(UnbreakableTailLength) {
  244. assert(Tok.TokenText.startswith(Prefix) && Tok.TokenText.endswith(Postfix));
  245. Line = Tok.TokenText.substr(
  246. Prefix.size(), Tok.TokenText.size() - Prefix.size() - Postfix.size());
  247. }
  248. BreakableToken::Split BreakableStringLiteral::getSplit(
  249. unsigned LineIndex, unsigned TailOffset, unsigned ColumnLimit,
  250. unsigned ContentStartColumn, const llvm::Regex &CommentPragmasRegex) const {
  251. return getStringSplit(Line.substr(TailOffset), ContentStartColumn,
  252. ColumnLimit - Postfix.size(), Style.TabWidth, Encoding);
  253. }
  254. void BreakableStringLiteral::insertBreak(unsigned LineIndex,
  255. unsigned TailOffset, Split Split,
  256. unsigned ContentIndent,
  257. WhitespaceManager &Whitespaces) const {
  258. Whitespaces.replaceWhitespaceInToken(
  259. Tok, Prefix.size() + TailOffset + Split.first, Split.second, Postfix,
  260. Prefix, InPPDirective, 1, StartColumn);
  261. }
  262. BreakableComment::BreakableComment(const FormatToken &Token,
  263. unsigned StartColumn, bool InPPDirective,
  264. encoding::Encoding Encoding,
  265. const FormatStyle &Style)
  266. : BreakableToken(Token, InPPDirective, Encoding, Style),
  267. StartColumn(StartColumn) {}
  268. unsigned BreakableComment::getLineCount() const { return Lines.size(); }
  269. BreakableToken::Split
  270. BreakableComment::getSplit(unsigned LineIndex, unsigned TailOffset,
  271. unsigned ColumnLimit, unsigned ContentStartColumn,
  272. const llvm::Regex &CommentPragmasRegex) const {
  273. // Don't break lines matching the comment pragmas regex.
  274. if (CommentPragmasRegex.match(Content[LineIndex]))
  275. return Split(StringRef::npos, 0);
  276. return getCommentSplit(Content[LineIndex].substr(TailOffset),
  277. ContentStartColumn, ColumnLimit, Style.TabWidth,
  278. Encoding, Style);
  279. }
  280. void BreakableComment::compressWhitespace(
  281. unsigned LineIndex, unsigned TailOffset, Split Split,
  282. WhitespaceManager &Whitespaces) const {
  283. StringRef Text = Content[LineIndex].substr(TailOffset);
  284. // Text is relative to the content line, but Whitespaces operates relative to
  285. // the start of the corresponding token, so compute the start of the Split
  286. // that needs to be compressed into a single space relative to the start of
  287. // its token.
  288. unsigned BreakOffsetInToken =
  289. Text.data() - tokenAt(LineIndex).TokenText.data() + Split.first;
  290. unsigned CharsToRemove = Split.second;
  291. Whitespaces.replaceWhitespaceInToken(
  292. tokenAt(LineIndex), BreakOffsetInToken, CharsToRemove, "", "",
  293. /*InPPDirective=*/false, /*Newlines=*/0, /*Spaces=*/1);
  294. }
  295. const FormatToken &BreakableComment::tokenAt(unsigned LineIndex) const {
  296. return Tokens[LineIndex] ? *Tokens[LineIndex] : Tok;
  297. }
  298. static bool mayReflowContent(StringRef Content) {
  299. Content = Content.trim(Blanks);
  300. // Lines starting with '@' commonly have special meaning.
  301. // Lines starting with '-', '-#', '+' or '*' are bulleted/numbered lists.
  302. bool hasSpecialMeaningPrefix = false;
  303. for (StringRef Prefix :
  304. {"@", "TODO", "FIXME", "XXX", "-# ", "- ", "+ ", "* "}) {
  305. if (Content.startswith(Prefix)) {
  306. hasSpecialMeaningPrefix = true;
  307. break;
  308. }
  309. }
  310. // Numbered lists may also start with a number followed by '.'
  311. // To avoid issues if a line starts with a number which is actually the end
  312. // of a previous line, we only consider numbers with up to 2 digits.
  313. static const auto kNumberedListRegexp = llvm::Regex("^[1-9][0-9]?\\. ");
  314. hasSpecialMeaningPrefix =
  315. hasSpecialMeaningPrefix || kNumberedListRegexp.match(Content);
  316. // Simple heuristic for what to reflow: content should contain at least two
  317. // characters and either the first or second character must be
  318. // non-punctuation.
  319. return Content.size() >= 2 && !hasSpecialMeaningPrefix &&
  320. !Content.endswith("\\") &&
  321. // Note that this is UTF-8 safe, since if isPunctuation(Content[0]) is
  322. // true, then the first code point must be 1 byte long.
  323. (!isPunctuation(Content[0]) || !isPunctuation(Content[1]));
  324. }
  325. BreakableBlockComment::BreakableBlockComment(
  326. const FormatToken &Token, unsigned StartColumn,
  327. unsigned OriginalStartColumn, bool FirstInLine, bool InPPDirective,
  328. encoding::Encoding Encoding, const FormatStyle &Style, bool UseCRLF)
  329. : BreakableComment(Token, StartColumn, InPPDirective, Encoding, Style),
  330. DelimitersOnNewline(false),
  331. UnbreakableTailLength(Token.UnbreakableTailLength) {
  332. assert(Tok.is(TT_BlockComment) &&
  333. "block comment section must start with a block comment");
  334. StringRef TokenText(Tok.TokenText);
  335. assert(TokenText.startswith("/*") && TokenText.endswith("*/"));
  336. TokenText.substr(2, TokenText.size() - 4)
  337. .split(Lines, UseCRLF ? "\r\n" : "\n");
  338. int IndentDelta = StartColumn - OriginalStartColumn;
  339. Content.resize(Lines.size());
  340. Content[0] = Lines[0];
  341. ContentColumn.resize(Lines.size());
  342. // Account for the initial '/*'.
  343. ContentColumn[0] = StartColumn + 2;
  344. Tokens.resize(Lines.size());
  345. for (size_t i = 1; i < Lines.size(); ++i)
  346. adjustWhitespace(i, IndentDelta);
  347. // Align decorations with the column of the star on the first line,
  348. // that is one column after the start "/*".
  349. DecorationColumn = StartColumn + 1;
  350. // Account for comment decoration patterns like this:
  351. //
  352. // /*
  353. // ** blah blah blah
  354. // */
  355. if (Lines.size() >= 2 && Content[1].startswith("**") &&
  356. static_cast<unsigned>(ContentColumn[1]) == StartColumn) {
  357. DecorationColumn = StartColumn;
  358. }
  359. Decoration = "* ";
  360. if (Lines.size() == 1 && !FirstInLine) {
  361. // Comments for which FirstInLine is false can start on arbitrary column,
  362. // and available horizontal space can be too small to align consecutive
  363. // lines with the first one.
  364. // FIXME: We could, probably, align them to current indentation level, but
  365. // now we just wrap them without stars.
  366. Decoration = "";
  367. }
  368. for (size_t i = 1, e = Lines.size(); i < e && !Decoration.empty(); ++i) {
  369. // If the last line is empty, the closing "*/" will have a star.
  370. if (i + 1 == e && Content[i].empty())
  371. break;
  372. if (!Content[i].empty() && i + 1 != e && Decoration.startswith(Content[i]))
  373. continue;
  374. while (!Content[i].startswith(Decoration))
  375. Decoration = Decoration.substr(0, Decoration.size() - 1);
  376. }
  377. LastLineNeedsDecoration = true;
  378. IndentAtLineBreak = ContentColumn[0] + 1;
  379. for (size_t i = 1, e = Lines.size(); i < e; ++i) {
  380. if (Content[i].empty()) {
  381. if (i + 1 == e) {
  382. // Empty last line means that we already have a star as a part of the
  383. // trailing */. We also need to preserve whitespace, so that */ is
  384. // correctly indented.
  385. LastLineNeedsDecoration = false;
  386. // Align the star in the last '*/' with the stars on the previous lines.
  387. if (e >= 2 && !Decoration.empty()) {
  388. ContentColumn[i] = DecorationColumn;
  389. }
  390. } else if (Decoration.empty()) {
  391. // For all other lines, set the start column to 0 if they're empty, so
  392. // we do not insert trailing whitespace anywhere.
  393. ContentColumn[i] = 0;
  394. }
  395. continue;
  396. }
  397. // The first line already excludes the star.
  398. // The last line excludes the star if LastLineNeedsDecoration is false.
  399. // For all other lines, adjust the line to exclude the star and
  400. // (optionally) the first whitespace.
  401. unsigned DecorationSize = Decoration.startswith(Content[i])
  402. ? Content[i].size()
  403. : Decoration.size();
  404. if (DecorationSize) {
  405. ContentColumn[i] = DecorationColumn + DecorationSize;
  406. }
  407. Content[i] = Content[i].substr(DecorationSize);
  408. if (!Decoration.startswith(Content[i]))
  409. IndentAtLineBreak =
  410. std::min<int>(IndentAtLineBreak, std::max(0, ContentColumn[i]));
  411. }
  412. IndentAtLineBreak = std::max<unsigned>(IndentAtLineBreak, Decoration.size());
  413. // Detect a multiline jsdoc comment and set DelimitersOnNewline in that case.
  414. if (Style.isJavaScript() || Style.Language == FormatStyle::LK_Java) {
  415. if ((Lines[0] == "*" || Lines[0].startswith("* ")) && Lines.size() > 1) {
  416. // This is a multiline jsdoc comment.
  417. DelimitersOnNewline = true;
  418. } else if (Lines[0].startswith("* ") && Lines.size() == 1) {
  419. // Detect a long single-line comment, like:
  420. // /** long long long */
  421. // Below, '2' is the width of '*/'.
  422. unsigned EndColumn =
  423. ContentColumn[0] +
  424. encoding::columnWidthWithTabs(Lines[0], ContentColumn[0],
  425. Style.TabWidth, Encoding) +
  426. 2;
  427. DelimitersOnNewline = EndColumn > Style.ColumnLimit;
  428. }
  429. }
  430. LLVM_DEBUG({
  431. llvm::dbgs() << "IndentAtLineBreak " << IndentAtLineBreak << "\n";
  432. llvm::dbgs() << "DelimitersOnNewline " << DelimitersOnNewline << "\n";
  433. for (size_t i = 0; i < Lines.size(); ++i) {
  434. llvm::dbgs() << i << " |" << Content[i] << "| "
  435. << "CC=" << ContentColumn[i] << "| "
  436. << "IN=" << (Content[i].data() - Lines[i].data()) << "\n";
  437. }
  438. });
  439. }
  440. BreakableToken::Split BreakableBlockComment::getSplit(
  441. unsigned LineIndex, unsigned TailOffset, unsigned ColumnLimit,
  442. unsigned ContentStartColumn, const llvm::Regex &CommentPragmasRegex) const {
  443. // Don't break lines matching the comment pragmas regex.
  444. if (CommentPragmasRegex.match(Content[LineIndex]))
  445. return Split(StringRef::npos, 0);
  446. return getCommentSplit(Content[LineIndex].substr(TailOffset),
  447. ContentStartColumn, ColumnLimit, Style.TabWidth,
  448. Encoding, Style, Decoration.endswith("*"));
  449. }
  450. void BreakableBlockComment::adjustWhitespace(unsigned LineIndex,
  451. int IndentDelta) {
  452. // When in a preprocessor directive, the trailing backslash in a block comment
  453. // is not needed, but can serve a purpose of uniformity with necessary escaped
  454. // newlines outside the comment. In this case we remove it here before
  455. // trimming the trailing whitespace. The backslash will be re-added later when
  456. // inserting a line break.
  457. size_t EndOfPreviousLine = Lines[LineIndex - 1].size();
  458. if (InPPDirective && Lines[LineIndex - 1].endswith("\\"))
  459. --EndOfPreviousLine;
  460. // Calculate the end of the non-whitespace text in the previous line.
  461. EndOfPreviousLine =
  462. Lines[LineIndex - 1].find_last_not_of(Blanks, EndOfPreviousLine);
  463. if (EndOfPreviousLine == StringRef::npos)
  464. EndOfPreviousLine = 0;
  465. else
  466. ++EndOfPreviousLine;
  467. // Calculate the start of the non-whitespace text in the current line.
  468. size_t StartOfLine = Lines[LineIndex].find_first_not_of(Blanks);
  469. if (StartOfLine == StringRef::npos)
  470. StartOfLine = Lines[LineIndex].size();
  471. StringRef Whitespace = Lines[LineIndex].substr(0, StartOfLine);
  472. // Adjust Lines to only contain relevant text.
  473. size_t PreviousContentOffset =
  474. Content[LineIndex - 1].data() - Lines[LineIndex - 1].data();
  475. Content[LineIndex - 1] = Lines[LineIndex - 1].substr(
  476. PreviousContentOffset, EndOfPreviousLine - PreviousContentOffset);
  477. Content[LineIndex] = Lines[LineIndex].substr(StartOfLine);
  478. // Adjust the start column uniformly across all lines.
  479. ContentColumn[LineIndex] =
  480. encoding::columnWidthWithTabs(Whitespace, 0, Style.TabWidth, Encoding) +
  481. IndentDelta;
  482. }
  483. unsigned BreakableBlockComment::getRangeLength(unsigned LineIndex,
  484. unsigned Offset,
  485. StringRef::size_type Length,
  486. unsigned StartColumn) const {
  487. return encoding::columnWidthWithTabs(
  488. Content[LineIndex].substr(Offset, Length), StartColumn, Style.TabWidth,
  489. Encoding);
  490. }
  491. unsigned BreakableBlockComment::getRemainingLength(unsigned LineIndex,
  492. unsigned Offset,
  493. unsigned StartColumn) const {
  494. unsigned LineLength =
  495. UnbreakableTailLength +
  496. getRangeLength(LineIndex, Offset, StringRef::npos, StartColumn);
  497. if (LineIndex + 1 == Lines.size()) {
  498. LineLength += 2;
  499. // We never need a decoration when breaking just the trailing "*/" postfix.
  500. bool HasRemainingText = Offset < Content[LineIndex].size();
  501. if (!HasRemainingText) {
  502. bool HasDecoration = Lines[LineIndex].ltrim().startswith(Decoration);
  503. if (HasDecoration)
  504. LineLength -= Decoration.size();
  505. }
  506. }
  507. return LineLength;
  508. }
  509. unsigned BreakableBlockComment::getContentStartColumn(unsigned LineIndex,
  510. bool Break) const {
  511. if (Break)
  512. return IndentAtLineBreak;
  513. return std::max(0, ContentColumn[LineIndex]);
  514. }
  515. const llvm::StringSet<>
  516. BreakableBlockComment::ContentIndentingJavadocAnnotations = {
  517. "@param", "@return", "@returns", "@throws", "@type", "@template",
  518. "@see", "@deprecated", "@define", "@exports", "@mods", "@private",
  519. };
  520. unsigned BreakableBlockComment::getContentIndent(unsigned LineIndex) const {
  521. if (Style.Language != FormatStyle::LK_Java && !Style.isJavaScript())
  522. return 0;
  523. // The content at LineIndex 0 of a comment like:
  524. // /** line 0 */
  525. // is "* line 0", so we need to skip over the decoration in that case.
  526. StringRef ContentWithNoDecoration = Content[LineIndex];
  527. if (LineIndex == 0 && ContentWithNoDecoration.startswith("*")) {
  528. ContentWithNoDecoration = ContentWithNoDecoration.substr(1).ltrim(Blanks);
  529. }
  530. StringRef FirstWord = ContentWithNoDecoration.substr(
  531. 0, ContentWithNoDecoration.find_first_of(Blanks));
  532. if (ContentIndentingJavadocAnnotations.find(FirstWord) !=
  533. ContentIndentingJavadocAnnotations.end())
  534. return Style.ContinuationIndentWidth;
  535. return 0;
  536. }
  537. void BreakableBlockComment::insertBreak(unsigned LineIndex, unsigned TailOffset,
  538. Split Split, unsigned ContentIndent,
  539. WhitespaceManager &Whitespaces) const {
  540. StringRef Text = Content[LineIndex].substr(TailOffset);
  541. StringRef Prefix = Decoration;
  542. // We need this to account for the case when we have a decoration "* " for all
  543. // the lines except for the last one, where the star in "*/" acts as a
  544. // decoration.
  545. unsigned LocalIndentAtLineBreak = IndentAtLineBreak;
  546. if (LineIndex + 1 == Lines.size() &&
  547. Text.size() == Split.first + Split.second) {
  548. // For the last line we need to break before "*/", but not to add "* ".
  549. Prefix = "";
  550. if (LocalIndentAtLineBreak >= 2)
  551. LocalIndentAtLineBreak -= 2;
  552. }
  553. // The split offset is from the beginning of the line. Convert it to an offset
  554. // from the beginning of the token text.
  555. unsigned BreakOffsetInToken =
  556. Text.data() - tokenAt(LineIndex).TokenText.data() + Split.first;
  557. unsigned CharsToRemove = Split.second;
  558. assert(LocalIndentAtLineBreak >= Prefix.size());
  559. std::string PrefixWithTrailingIndent = std::string(Prefix);
  560. PrefixWithTrailingIndent.append(ContentIndent, ' ');
  561. Whitespaces.replaceWhitespaceInToken(
  562. tokenAt(LineIndex), BreakOffsetInToken, CharsToRemove, "",
  563. PrefixWithTrailingIndent, InPPDirective, /*Newlines=*/1,
  564. /*Spaces=*/LocalIndentAtLineBreak + ContentIndent -
  565. PrefixWithTrailingIndent.size());
  566. }
  567. BreakableToken::Split BreakableBlockComment::getReflowSplit(
  568. unsigned LineIndex, const llvm::Regex &CommentPragmasRegex) const {
  569. if (!mayReflow(LineIndex, CommentPragmasRegex))
  570. return Split(StringRef::npos, 0);
  571. // If we're reflowing into a line with content indent, only reflow the next
  572. // line if its starting whitespace matches the content indent.
  573. size_t Trimmed = Content[LineIndex].find_first_not_of(Blanks);
  574. if (LineIndex) {
  575. unsigned PreviousContentIndent = getContentIndent(LineIndex - 1);
  576. if (PreviousContentIndent && Trimmed != StringRef::npos &&
  577. Trimmed != PreviousContentIndent)
  578. return Split(StringRef::npos, 0);
  579. }
  580. return Split(0, Trimmed != StringRef::npos ? Trimmed : 0);
  581. }
  582. bool BreakableBlockComment::introducesBreakBeforeToken() const {
  583. // A break is introduced when we want delimiters on newline.
  584. return DelimitersOnNewline &&
  585. Lines[0].substr(1).find_first_not_of(Blanks) != StringRef::npos;
  586. }
  587. void BreakableBlockComment::reflow(unsigned LineIndex,
  588. WhitespaceManager &Whitespaces) const {
  589. StringRef TrimmedContent = Content[LineIndex].ltrim(Blanks);
  590. // Here we need to reflow.
  591. assert(Tokens[LineIndex - 1] == Tokens[LineIndex] &&
  592. "Reflowing whitespace within a token");
  593. // This is the offset of the end of the last line relative to the start of
  594. // the token text in the token.
  595. unsigned WhitespaceOffsetInToken = Content[LineIndex - 1].data() +
  596. Content[LineIndex - 1].size() -
  597. tokenAt(LineIndex).TokenText.data();
  598. unsigned WhitespaceLength = TrimmedContent.data() -
  599. tokenAt(LineIndex).TokenText.data() -
  600. WhitespaceOffsetInToken;
  601. Whitespaces.replaceWhitespaceInToken(
  602. tokenAt(LineIndex), WhitespaceOffsetInToken,
  603. /*ReplaceChars=*/WhitespaceLength, /*PreviousPostfix=*/"",
  604. /*CurrentPrefix=*/ReflowPrefix, InPPDirective, /*Newlines=*/0,
  605. /*Spaces=*/0);
  606. }
  607. void BreakableBlockComment::adaptStartOfLine(
  608. unsigned LineIndex, WhitespaceManager &Whitespaces) const {
  609. if (LineIndex == 0) {
  610. if (DelimitersOnNewline) {
  611. // Since we're breaking at index 1 below, the break position and the
  612. // break length are the same.
  613. // Note: this works because getCommentSplit is careful never to split at
  614. // the beginning of a line.
  615. size_t BreakLength = Lines[0].substr(1).find_first_not_of(Blanks);
  616. if (BreakLength != StringRef::npos)
  617. insertBreak(LineIndex, 0, Split(1, BreakLength), /*ContentIndent=*/0,
  618. Whitespaces);
  619. }
  620. return;
  621. }
  622. // Here no reflow with the previous line will happen.
  623. // Fix the decoration of the line at LineIndex.
  624. StringRef Prefix = Decoration;
  625. if (Content[LineIndex].empty()) {
  626. if (LineIndex + 1 == Lines.size()) {
  627. if (!LastLineNeedsDecoration) {
  628. // If the last line was empty, we don't need a prefix, as the */ will
  629. // line up with the decoration (if it exists).
  630. Prefix = "";
  631. }
  632. } else if (!Decoration.empty()) {
  633. // For other empty lines, if we do have a decoration, adapt it to not
  634. // contain a trailing whitespace.
  635. Prefix = Prefix.substr(0, 1);
  636. }
  637. } else {
  638. if (ContentColumn[LineIndex] == 1) {
  639. // This line starts immediately after the decorating *.
  640. Prefix = Prefix.substr(0, 1);
  641. }
  642. }
  643. // This is the offset of the end of the last line relative to the start of the
  644. // token text in the token.
  645. unsigned WhitespaceOffsetInToken = Content[LineIndex - 1].data() +
  646. Content[LineIndex - 1].size() -
  647. tokenAt(LineIndex).TokenText.data();
  648. unsigned WhitespaceLength = Content[LineIndex].data() -
  649. tokenAt(LineIndex).TokenText.data() -
  650. WhitespaceOffsetInToken;
  651. Whitespaces.replaceWhitespaceInToken(
  652. tokenAt(LineIndex), WhitespaceOffsetInToken, WhitespaceLength, "", Prefix,
  653. InPPDirective, /*Newlines=*/1, ContentColumn[LineIndex] - Prefix.size());
  654. }
  655. BreakableToken::Split
  656. BreakableBlockComment::getSplitAfterLastLine(unsigned TailOffset) const {
  657. if (DelimitersOnNewline) {
  658. // Replace the trailing whitespace of the last line with a newline.
  659. // In case the last line is empty, the ending '*/' is already on its own
  660. // line.
  661. StringRef Line = Content.back().substr(TailOffset);
  662. StringRef TrimmedLine = Line.rtrim(Blanks);
  663. if (!TrimmedLine.empty())
  664. return Split(TrimmedLine.size(), Line.size() - TrimmedLine.size());
  665. }
  666. return Split(StringRef::npos, 0);
  667. }
  668. bool BreakableBlockComment::mayReflow(
  669. unsigned LineIndex, const llvm::Regex &CommentPragmasRegex) const {
  670. // Content[LineIndex] may exclude the indent after the '*' decoration. In that
  671. // case, we compute the start of the comment pragma manually.
  672. StringRef IndentContent = Content[LineIndex];
  673. if (Lines[LineIndex].ltrim(Blanks).startswith("*")) {
  674. IndentContent = Lines[LineIndex].ltrim(Blanks).substr(1);
  675. }
  676. return LineIndex > 0 && !CommentPragmasRegex.match(IndentContent) &&
  677. mayReflowContent(Content[LineIndex]) && !Tok.Finalized &&
  678. !switchesFormatting(tokenAt(LineIndex));
  679. }
  680. BreakableLineCommentSection::BreakableLineCommentSection(
  681. const FormatToken &Token, unsigned StartColumn, bool InPPDirective,
  682. encoding::Encoding Encoding, const FormatStyle &Style)
  683. : BreakableComment(Token, StartColumn, InPPDirective, Encoding, Style) {
  684. assert(Tok.is(TT_LineComment) &&
  685. "line comment section must start with a line comment");
  686. FormatToken *LineTok = nullptr;
  687. const int Minimum = Style.SpacesInLineCommentPrefix.Minimum;
  688. // How many spaces we changed in the first line of the section, this will be
  689. // applied in all following lines
  690. int FirstLineSpaceChange = 0;
  691. for (const FormatToken *CurrentTok = &Tok;
  692. CurrentTok && CurrentTok->is(TT_LineComment);
  693. CurrentTok = CurrentTok->Next) {
  694. LastLineTok = LineTok;
  695. StringRef TokenText(CurrentTok->TokenText);
  696. assert((TokenText.startswith("//") || TokenText.startswith("#")) &&
  697. "unsupported line comment prefix, '//' and '#' are supported");
  698. size_t FirstLineIndex = Lines.size();
  699. TokenText.split(Lines, "\n");
  700. Content.resize(Lines.size());
  701. ContentColumn.resize(Lines.size());
  702. PrefixSpaceChange.resize(Lines.size());
  703. Tokens.resize(Lines.size());
  704. Prefix.resize(Lines.size());
  705. OriginalPrefix.resize(Lines.size());
  706. for (size_t i = FirstLineIndex, e = Lines.size(); i < e; ++i) {
  707. Lines[i] = Lines[i].ltrim(Blanks);
  708. StringRef IndentPrefix = getLineCommentIndentPrefix(Lines[i], Style);
  709. OriginalPrefix[i] = IndentPrefix;
  710. const int SpacesInPrefix = llvm::count(IndentPrefix, ' ');
  711. // On the first line of the comment section we calculate how many spaces
  712. // are to be added or removed, all lines after that just get only the
  713. // change and we will not look at the maximum anymore. Additionally to the
  714. // actual first line, we calculate that when the non space Prefix changes,
  715. // e.g. from "///" to "//".
  716. if (i == 0 || OriginalPrefix[i].rtrim(Blanks) !=
  717. OriginalPrefix[i - 1].rtrim(Blanks)) {
  718. if (SpacesInPrefix < Minimum && Lines[i].size() > IndentPrefix.size() &&
  719. isAlphanumeric(Lines[i][IndentPrefix.size()])) {
  720. FirstLineSpaceChange = Minimum - SpacesInPrefix;
  721. } else if (static_cast<unsigned>(SpacesInPrefix) >
  722. Style.SpacesInLineCommentPrefix.Maximum) {
  723. FirstLineSpaceChange =
  724. Style.SpacesInLineCommentPrefix.Maximum - SpacesInPrefix;
  725. } else {
  726. FirstLineSpaceChange = 0;
  727. }
  728. }
  729. if (Lines[i].size() != IndentPrefix.size()) {
  730. PrefixSpaceChange[i] = FirstLineSpaceChange;
  731. if (SpacesInPrefix + PrefixSpaceChange[i] < Minimum) {
  732. PrefixSpaceChange[i] +=
  733. Minimum - (SpacesInPrefix + PrefixSpaceChange[i]);
  734. }
  735. assert(Lines[i].size() > IndentPrefix.size());
  736. const auto FirstNonSpace = Lines[i][IndentPrefix.size()];
  737. const auto AllowsSpaceChange =
  738. SpacesInPrefix != 0 ||
  739. (isAlphanumeric(FirstNonSpace) ||
  740. (FirstNonSpace == '}' && FirstLineSpaceChange != 0));
  741. if (PrefixSpaceChange[i] > 0 && AllowsSpaceChange) {
  742. Prefix[i] = IndentPrefix.str();
  743. Prefix[i].append(PrefixSpaceChange[i], ' ');
  744. } else if (PrefixSpaceChange[i] < 0 && AllowsSpaceChange) {
  745. Prefix[i] = IndentPrefix
  746. .drop_back(std::min<std::size_t>(
  747. -PrefixSpaceChange[i], SpacesInPrefix))
  748. .str();
  749. } else {
  750. Prefix[i] = IndentPrefix.str();
  751. }
  752. } else {
  753. // If the IndentPrefix is the whole line, there is no content and we
  754. // drop just all space
  755. Prefix[i] = IndentPrefix.drop_back(SpacesInPrefix).str();
  756. }
  757. Tokens[i] = LineTok;
  758. Content[i] = Lines[i].substr(IndentPrefix.size());
  759. ContentColumn[i] =
  760. StartColumn + encoding::columnWidthWithTabs(Prefix[i], StartColumn,
  761. Style.TabWidth, Encoding);
  762. // Calculate the end of the non-whitespace text in this line.
  763. size_t EndOfLine = Content[i].find_last_not_of(Blanks);
  764. if (EndOfLine == StringRef::npos)
  765. EndOfLine = Content[i].size();
  766. else
  767. ++EndOfLine;
  768. Content[i] = Content[i].substr(0, EndOfLine);
  769. }
  770. LineTok = CurrentTok->Next;
  771. if (CurrentTok->Next && !CurrentTok->Next->ContinuesLineCommentSection) {
  772. // A line comment section needs to broken by a line comment that is
  773. // preceded by at least two newlines. Note that we put this break here
  774. // instead of breaking at a previous stage during parsing, since that
  775. // would split the contents of the enum into two unwrapped lines in this
  776. // example, which is undesirable:
  777. // enum A {
  778. // a, // comment about a
  779. //
  780. // // comment about b
  781. // b
  782. // };
  783. //
  784. // FIXME: Consider putting separate line comment sections as children to
  785. // the unwrapped line instead.
  786. break;
  787. }
  788. }
  789. }
  790. unsigned
  791. BreakableLineCommentSection::getRangeLength(unsigned LineIndex, unsigned Offset,
  792. StringRef::size_type Length,
  793. unsigned StartColumn) const {
  794. return encoding::columnWidthWithTabs(
  795. Content[LineIndex].substr(Offset, Length), StartColumn, Style.TabWidth,
  796. Encoding);
  797. }
  798. unsigned
  799. BreakableLineCommentSection::getContentStartColumn(unsigned LineIndex,
  800. bool /*Break*/) const {
  801. return ContentColumn[LineIndex];
  802. }
  803. void BreakableLineCommentSection::insertBreak(
  804. unsigned LineIndex, unsigned TailOffset, Split Split,
  805. unsigned ContentIndent, WhitespaceManager &Whitespaces) const {
  806. StringRef Text = Content[LineIndex].substr(TailOffset);
  807. // Compute the offset of the split relative to the beginning of the token
  808. // text.
  809. unsigned BreakOffsetInToken =
  810. Text.data() - tokenAt(LineIndex).TokenText.data() + Split.first;
  811. unsigned CharsToRemove = Split.second;
  812. Whitespaces.replaceWhitespaceInToken(
  813. tokenAt(LineIndex), BreakOffsetInToken, CharsToRemove, "",
  814. Prefix[LineIndex], InPPDirective, /*Newlines=*/1,
  815. /*Spaces=*/ContentColumn[LineIndex] - Prefix[LineIndex].size());
  816. }
  817. BreakableComment::Split BreakableLineCommentSection::getReflowSplit(
  818. unsigned LineIndex, const llvm::Regex &CommentPragmasRegex) const {
  819. if (!mayReflow(LineIndex, CommentPragmasRegex))
  820. return Split(StringRef::npos, 0);
  821. size_t Trimmed = Content[LineIndex].find_first_not_of(Blanks);
  822. // In a line comment section each line is a separate token; thus, after a
  823. // split we replace all whitespace before the current line comment token
  824. // (which does not need to be included in the split), plus the start of the
  825. // line up to where the content starts.
  826. return Split(0, Trimmed != StringRef::npos ? Trimmed : 0);
  827. }
  828. void BreakableLineCommentSection::reflow(unsigned LineIndex,
  829. WhitespaceManager &Whitespaces) const {
  830. if (LineIndex > 0 && Tokens[LineIndex] != Tokens[LineIndex - 1]) {
  831. // Reflow happens between tokens. Replace the whitespace between the
  832. // tokens by the empty string.
  833. Whitespaces.replaceWhitespace(
  834. *Tokens[LineIndex], /*Newlines=*/0, /*Spaces=*/0,
  835. /*StartOfTokenColumn=*/StartColumn, /*IsAligned=*/true,
  836. /*InPPDirective=*/false);
  837. } else if (LineIndex > 0) {
  838. // In case we're reflowing after the '\' in:
  839. //
  840. // // line comment \
  841. // // line 2
  842. //
  843. // the reflow happens inside the single comment token (it is a single line
  844. // comment with an unescaped newline).
  845. // Replace the whitespace between the '\' and '//' with the empty string.
  846. //
  847. // Offset points to after the '\' relative to start of the token.
  848. unsigned Offset = Lines[LineIndex - 1].data() +
  849. Lines[LineIndex - 1].size() -
  850. tokenAt(LineIndex - 1).TokenText.data();
  851. // WhitespaceLength is the number of chars between the '\' and the '//' on
  852. // the next line.
  853. unsigned WhitespaceLength =
  854. Lines[LineIndex].data() - tokenAt(LineIndex).TokenText.data() - Offset;
  855. Whitespaces.replaceWhitespaceInToken(*Tokens[LineIndex], Offset,
  856. /*ReplaceChars=*/WhitespaceLength,
  857. /*PreviousPostfix=*/"",
  858. /*CurrentPrefix=*/"",
  859. /*InPPDirective=*/false,
  860. /*Newlines=*/0,
  861. /*Spaces=*/0);
  862. }
  863. // Replace the indent and prefix of the token with the reflow prefix.
  864. unsigned Offset =
  865. Lines[LineIndex].data() - tokenAt(LineIndex).TokenText.data();
  866. unsigned WhitespaceLength =
  867. Content[LineIndex].data() - Lines[LineIndex].data();
  868. Whitespaces.replaceWhitespaceInToken(*Tokens[LineIndex], Offset,
  869. /*ReplaceChars=*/WhitespaceLength,
  870. /*PreviousPostfix=*/"",
  871. /*CurrentPrefix=*/ReflowPrefix,
  872. /*InPPDirective=*/false,
  873. /*Newlines=*/0,
  874. /*Spaces=*/0);
  875. }
  876. void BreakableLineCommentSection::adaptStartOfLine(
  877. unsigned LineIndex, WhitespaceManager &Whitespaces) const {
  878. // If this is the first line of a token, we need to inform Whitespace Manager
  879. // about it: either adapt the whitespace range preceding it, or mark it as an
  880. // untouchable token.
  881. // This happens for instance here:
  882. // // line 1 \
  883. // // line 2
  884. if (LineIndex > 0 && Tokens[LineIndex] != Tokens[LineIndex - 1]) {
  885. // This is the first line for the current token, but no reflow with the
  886. // previous token is necessary. However, we still may need to adjust the
  887. // start column. Note that ContentColumn[LineIndex] is the expected
  888. // content column after a possible update to the prefix, hence the prefix
  889. // length change is included.
  890. unsigned LineColumn =
  891. ContentColumn[LineIndex] -
  892. (Content[LineIndex].data() - Lines[LineIndex].data()) +
  893. (OriginalPrefix[LineIndex].size() - Prefix[LineIndex].size());
  894. // We always want to create a replacement instead of adding an untouchable
  895. // token, even if LineColumn is the same as the original column of the
  896. // token. This is because WhitespaceManager doesn't align trailing
  897. // comments if they are untouchable.
  898. Whitespaces.replaceWhitespace(*Tokens[LineIndex],
  899. /*Newlines=*/1,
  900. /*Spaces=*/LineColumn,
  901. /*StartOfTokenColumn=*/LineColumn,
  902. /*IsAligned=*/true,
  903. /*InPPDirective=*/false);
  904. }
  905. if (OriginalPrefix[LineIndex] != Prefix[LineIndex]) {
  906. // Adjust the prefix if necessary.
  907. const auto SpacesToRemove = -std::min(PrefixSpaceChange[LineIndex], 0);
  908. const auto SpacesToAdd = std::max(PrefixSpaceChange[LineIndex], 0);
  909. Whitespaces.replaceWhitespaceInToken(
  910. tokenAt(LineIndex), OriginalPrefix[LineIndex].size() - SpacesToRemove,
  911. /*ReplaceChars=*/SpacesToRemove, "", "", /*InPPDirective=*/false,
  912. /*Newlines=*/0, /*Spaces=*/SpacesToAdd);
  913. }
  914. }
  915. void BreakableLineCommentSection::updateNextToken(LineState &State) const {
  916. if (LastLineTok) {
  917. State.NextToken = LastLineTok->Next;
  918. }
  919. }
  920. bool BreakableLineCommentSection::mayReflow(
  921. unsigned LineIndex, const llvm::Regex &CommentPragmasRegex) const {
  922. // Line comments have the indent as part of the prefix, so we need to
  923. // recompute the start of the line.
  924. StringRef IndentContent = Content[LineIndex];
  925. if (Lines[LineIndex].startswith("//")) {
  926. IndentContent = Lines[LineIndex].substr(2);
  927. }
  928. // FIXME: Decide whether we want to reflow non-regular indents:
  929. // Currently, we only reflow when the OriginalPrefix[LineIndex] matches the
  930. // OriginalPrefix[LineIndex-1]. That means we don't reflow
  931. // // text that protrudes
  932. // // into text with different indent
  933. // We do reflow in that case in block comments.
  934. return LineIndex > 0 && !CommentPragmasRegex.match(IndentContent) &&
  935. mayReflowContent(Content[LineIndex]) && !Tok.Finalized &&
  936. !switchesFormatting(tokenAt(LineIndex)) &&
  937. OriginalPrefix[LineIndex] == OriginalPrefix[LineIndex - 1];
  938. }
  939. } // namespace format
  940. } // namespace clang