BreakableToken.cpp 45 KB

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