BreakableToken.cpp 42 KB

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