WhitespaceManager.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721
  1. //===--- WhitespaceManager.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. /// This file implements WhitespaceManager class.
  11. ///
  12. //===----------------------------------------------------------------------===//
  13. #include "WhitespaceManager.h"
  14. #include "llvm/ADT/STLExtras.h"
  15. namespace clang {
  16. namespace format {
  17. bool WhitespaceManager::Change::IsBeforeInFile::
  18. operator()(const Change &C1, const Change &C2) const {
  19. return SourceMgr.isBeforeInTranslationUnit(
  20. C1.OriginalWhitespaceRange.getBegin(),
  21. C2.OriginalWhitespaceRange.getBegin());
  22. }
  23. WhitespaceManager::Change::Change(const FormatToken &Tok,
  24. bool CreateReplacement,
  25. SourceRange OriginalWhitespaceRange,
  26. int Spaces, unsigned StartOfTokenColumn,
  27. unsigned NewlinesBefore,
  28. StringRef PreviousLinePostfix,
  29. StringRef CurrentLinePrefix,
  30. bool ContinuesPPDirective, bool IsInsideToken)
  31. : Tok(&Tok), CreateReplacement(CreateReplacement),
  32. OriginalWhitespaceRange(OriginalWhitespaceRange),
  33. StartOfTokenColumn(StartOfTokenColumn), NewlinesBefore(NewlinesBefore),
  34. PreviousLinePostfix(PreviousLinePostfix),
  35. CurrentLinePrefix(CurrentLinePrefix),
  36. ContinuesPPDirective(ContinuesPPDirective), Spaces(Spaces),
  37. IsInsideToken(IsInsideToken), IsTrailingComment(false), TokenLength(0),
  38. PreviousEndOfTokenColumn(0), EscapedNewlineColumn(0),
  39. StartOfBlockComment(nullptr), IndentationOffset(0) {}
  40. void WhitespaceManager::replaceWhitespace(FormatToken &Tok, unsigned Newlines,
  41. unsigned Spaces,
  42. unsigned StartOfTokenColumn,
  43. bool InPPDirective) {
  44. if (Tok.Finalized)
  45. return;
  46. Tok.Decision = (Newlines > 0) ? FD_Break : FD_Continue;
  47. Changes.push_back(Change(Tok, /*CreateReplacement=*/true, Tok.WhitespaceRange,
  48. Spaces, StartOfTokenColumn, Newlines, "", "",
  49. InPPDirective && !Tok.IsFirst,
  50. /*IsInsideToken=*/false));
  51. }
  52. void WhitespaceManager::addUntouchableToken(const FormatToken &Tok,
  53. bool InPPDirective) {
  54. if (Tok.Finalized)
  55. return;
  56. Changes.push_back(Change(Tok, /*CreateReplacement=*/false,
  57. Tok.WhitespaceRange, /*Spaces=*/0,
  58. Tok.OriginalColumn, Tok.NewlinesBefore, "", "",
  59. InPPDirective && !Tok.IsFirst,
  60. /*IsInsideToken=*/false));
  61. }
  62. llvm::Error
  63. WhitespaceManager::addReplacement(const tooling::Replacement &Replacement) {
  64. return Replaces.add(Replacement);
  65. }
  66. void WhitespaceManager::replaceWhitespaceInToken(
  67. const FormatToken &Tok, unsigned Offset, unsigned ReplaceChars,
  68. StringRef PreviousPostfix, StringRef CurrentPrefix, bool InPPDirective,
  69. unsigned Newlines, int Spaces) {
  70. if (Tok.Finalized)
  71. return;
  72. SourceLocation Start = Tok.getStartOfNonWhitespace().getLocWithOffset(Offset);
  73. Changes.push_back(
  74. Change(Tok, /*CreateReplacement=*/true,
  75. SourceRange(Start, Start.getLocWithOffset(ReplaceChars)), Spaces,
  76. std::max(0, Spaces), Newlines, PreviousPostfix, CurrentPrefix,
  77. InPPDirective && !Tok.IsFirst, /*IsInsideToken=*/true));
  78. }
  79. const tooling::Replacements &WhitespaceManager::generateReplacements() {
  80. if (Changes.empty())
  81. return Replaces;
  82. llvm::sort(Changes, Change::IsBeforeInFile(SourceMgr));
  83. calculateLineBreakInformation();
  84. alignConsecutiveDeclarations();
  85. alignConsecutiveAssignments();
  86. alignTrailingComments();
  87. alignEscapedNewlines();
  88. generateChanges();
  89. return Replaces;
  90. }
  91. void WhitespaceManager::calculateLineBreakInformation() {
  92. Changes[0].PreviousEndOfTokenColumn = 0;
  93. Change *LastOutsideTokenChange = &Changes[0];
  94. for (unsigned i = 1, e = Changes.size(); i != e; ++i) {
  95. SourceLocation OriginalWhitespaceStart =
  96. Changes[i].OriginalWhitespaceRange.getBegin();
  97. SourceLocation PreviousOriginalWhitespaceEnd =
  98. Changes[i - 1].OriginalWhitespaceRange.getEnd();
  99. unsigned OriginalWhitespaceStartOffset =
  100. SourceMgr.getFileOffset(OriginalWhitespaceStart);
  101. unsigned PreviousOriginalWhitespaceEndOffset =
  102. SourceMgr.getFileOffset(PreviousOriginalWhitespaceEnd);
  103. assert(PreviousOriginalWhitespaceEndOffset <=
  104. OriginalWhitespaceStartOffset);
  105. const char *const PreviousOriginalWhitespaceEndData =
  106. SourceMgr.getCharacterData(PreviousOriginalWhitespaceEnd);
  107. StringRef Text(PreviousOriginalWhitespaceEndData,
  108. SourceMgr.getCharacterData(OriginalWhitespaceStart) -
  109. PreviousOriginalWhitespaceEndData);
  110. // Usually consecutive changes would occur in consecutive tokens. This is
  111. // not the case however when analyzing some preprocessor runs of the
  112. // annotated lines. For example, in this code:
  113. //
  114. // #if A // line 1
  115. // int i = 1;
  116. // #else B // line 2
  117. // int i = 2;
  118. // #endif // line 3
  119. //
  120. // one of the runs will produce the sequence of lines marked with line 1, 2
  121. // and 3. So the two consecutive whitespace changes just before '// line 2'
  122. // and before '#endif // line 3' span multiple lines and tokens:
  123. //
  124. // #else B{change X}[// line 2
  125. // int i = 2;
  126. // ]{change Y}#endif // line 3
  127. //
  128. // For this reason, if the text between consecutive changes spans multiple
  129. // newlines, the token length must be adjusted to the end of the original
  130. // line of the token.
  131. auto NewlinePos = Text.find_first_of('\n');
  132. if (NewlinePos == StringRef::npos) {
  133. Changes[i - 1].TokenLength = OriginalWhitespaceStartOffset -
  134. PreviousOriginalWhitespaceEndOffset +
  135. Changes[i].PreviousLinePostfix.size() +
  136. Changes[i - 1].CurrentLinePrefix.size();
  137. } else {
  138. Changes[i - 1].TokenLength =
  139. NewlinePos + Changes[i - 1].CurrentLinePrefix.size();
  140. }
  141. // If there are multiple changes in this token, sum up all the changes until
  142. // the end of the line.
  143. if (Changes[i - 1].IsInsideToken && Changes[i - 1].NewlinesBefore == 0)
  144. LastOutsideTokenChange->TokenLength +=
  145. Changes[i - 1].TokenLength + Changes[i - 1].Spaces;
  146. else
  147. LastOutsideTokenChange = &Changes[i - 1];
  148. Changes[i].PreviousEndOfTokenColumn =
  149. Changes[i - 1].StartOfTokenColumn + Changes[i - 1].TokenLength;
  150. Changes[i - 1].IsTrailingComment =
  151. (Changes[i].NewlinesBefore > 0 || Changes[i].Tok->is(tok::eof) ||
  152. (Changes[i].IsInsideToken && Changes[i].Tok->is(tok::comment))) &&
  153. Changes[i - 1].Tok->is(tok::comment) &&
  154. // FIXME: This is a dirty hack. The problem is that
  155. // BreakableLineCommentSection does comment reflow changes and here is
  156. // the aligning of trailing comments. Consider the case where we reflow
  157. // the second line up in this example:
  158. //
  159. // // line 1
  160. // // line 2
  161. //
  162. // That amounts to 2 changes by BreakableLineCommentSection:
  163. // - the first, delimited by (), for the whitespace between the tokens,
  164. // - and second, delimited by [], for the whitespace at the beginning
  165. // of the second token:
  166. //
  167. // // line 1(
  168. // )[// ]line 2
  169. //
  170. // So in the end we have two changes like this:
  171. //
  172. // // line1()[ ]line 2
  173. //
  174. // Note that the OriginalWhitespaceStart of the second change is the
  175. // same as the PreviousOriginalWhitespaceEnd of the first change.
  176. // In this case, the below check ensures that the second change doesn't
  177. // get treated as a trailing comment change here, since this might
  178. // trigger additional whitespace to be wrongly inserted before "line 2"
  179. // by the comment aligner here.
  180. //
  181. // For a proper solution we need a mechanism to say to WhitespaceManager
  182. // that a particular change breaks the current sequence of trailing
  183. // comments.
  184. OriginalWhitespaceStart != PreviousOriginalWhitespaceEnd;
  185. }
  186. // FIXME: The last token is currently not always an eof token; in those
  187. // cases, setting TokenLength of the last token to 0 is wrong.
  188. Changes.back().TokenLength = 0;
  189. Changes.back().IsTrailingComment = Changes.back().Tok->is(tok::comment);
  190. const WhitespaceManager::Change *LastBlockComment = nullptr;
  191. for (auto &Change : Changes) {
  192. // Reset the IsTrailingComment flag for changes inside of trailing comments
  193. // so they don't get realigned later. Comment line breaks however still need
  194. // to be aligned.
  195. if (Change.IsInsideToken && Change.NewlinesBefore == 0)
  196. Change.IsTrailingComment = false;
  197. Change.StartOfBlockComment = nullptr;
  198. Change.IndentationOffset = 0;
  199. if (Change.Tok->is(tok::comment)) {
  200. if (Change.Tok->is(TT_LineComment) || !Change.IsInsideToken)
  201. LastBlockComment = &Change;
  202. else {
  203. if ((Change.StartOfBlockComment = LastBlockComment))
  204. Change.IndentationOffset =
  205. Change.StartOfTokenColumn -
  206. Change.StartOfBlockComment->StartOfTokenColumn;
  207. }
  208. } else {
  209. LastBlockComment = nullptr;
  210. }
  211. }
  212. }
  213. // Align a single sequence of tokens, see AlignTokens below.
  214. template <typename F>
  215. static void
  216. AlignTokenSequence(unsigned Start, unsigned End, unsigned Column, F &&Matches,
  217. SmallVector<WhitespaceManager::Change, 16> &Changes) {
  218. bool FoundMatchOnLine = false;
  219. int Shift = 0;
  220. // ScopeStack keeps track of the current scope depth. It contains indices of
  221. // the first token on each scope.
  222. // We only run the "Matches" function on tokens from the outer-most scope.
  223. // However, we do need to pay special attention to one class of tokens
  224. // that are not in the outer-most scope, and that is function parameters
  225. // which are split across multiple lines, as illustrated by this example:
  226. // double a(int x);
  227. // int b(int y,
  228. // double z);
  229. // In the above example, we need to take special care to ensure that
  230. // 'double z' is indented along with it's owning function 'b'.
  231. SmallVector<unsigned, 16> ScopeStack;
  232. for (unsigned i = Start; i != End; ++i) {
  233. if (ScopeStack.size() != 0 &&
  234. Changes[i].indentAndNestingLevel() <
  235. Changes[ScopeStack.back()].indentAndNestingLevel())
  236. ScopeStack.pop_back();
  237. // Compare current token to previous non-comment token to ensure whether
  238. // it is in a deeper scope or not.
  239. unsigned PreviousNonComment = i - 1;
  240. while (PreviousNonComment > Start &&
  241. Changes[PreviousNonComment].Tok->is(tok::comment))
  242. PreviousNonComment--;
  243. if (i != Start && Changes[i].indentAndNestingLevel() >
  244. Changes[PreviousNonComment].indentAndNestingLevel())
  245. ScopeStack.push_back(i);
  246. bool InsideNestedScope = ScopeStack.size() != 0;
  247. if (Changes[i].NewlinesBefore > 0 && !InsideNestedScope) {
  248. Shift = 0;
  249. FoundMatchOnLine = false;
  250. }
  251. // If this is the first matching token to be aligned, remember by how many
  252. // spaces it has to be shifted, so the rest of the changes on the line are
  253. // shifted by the same amount
  254. if (!FoundMatchOnLine && !InsideNestedScope && Matches(Changes[i])) {
  255. FoundMatchOnLine = true;
  256. Shift = Column - Changes[i].StartOfTokenColumn;
  257. Changes[i].Spaces += Shift;
  258. }
  259. // This is for function parameters that are split across multiple lines,
  260. // as mentioned in the ScopeStack comment.
  261. if (InsideNestedScope && Changes[i].NewlinesBefore > 0) {
  262. unsigned ScopeStart = ScopeStack.back();
  263. if (Changes[ScopeStart - 1].Tok->is(TT_FunctionDeclarationName) ||
  264. (ScopeStart > Start + 1 &&
  265. Changes[ScopeStart - 2].Tok->is(TT_FunctionDeclarationName)))
  266. Changes[i].Spaces += Shift;
  267. }
  268. assert(Shift >= 0);
  269. Changes[i].StartOfTokenColumn += Shift;
  270. if (i + 1 != Changes.size())
  271. Changes[i + 1].PreviousEndOfTokenColumn += Shift;
  272. }
  273. }
  274. // Walk through a subset of the changes, starting at StartAt, and find
  275. // sequences of matching tokens to align. To do so, keep track of the lines and
  276. // whether or not a matching token was found on a line. If a matching token is
  277. // found, extend the current sequence. If the current line cannot be part of a
  278. // sequence, e.g. because there is an empty line before it or it contains only
  279. // non-matching tokens, finalize the previous sequence.
  280. // The value returned is the token on which we stopped, either because we
  281. // exhausted all items inside Changes, or because we hit a scope level higher
  282. // than our initial scope.
  283. // This function is recursive. Each invocation processes only the scope level
  284. // equal to the initial level, which is the level of Changes[StartAt].
  285. // If we encounter a scope level greater than the initial level, then we call
  286. // ourselves recursively, thereby avoiding the pollution of the current state
  287. // with the alignment requirements of the nested sub-level. This recursive
  288. // behavior is necessary for aligning function prototypes that have one or more
  289. // arguments.
  290. // If this function encounters a scope level less than the initial level,
  291. // it returns the current position.
  292. // There is a non-obvious subtlety in the recursive behavior: Even though we
  293. // defer processing of nested levels to recursive invocations of this
  294. // function, when it comes time to align a sequence of tokens, we run the
  295. // alignment on the entire sequence, including the nested levels.
  296. // When doing so, most of the nested tokens are skipped, because their
  297. // alignment was already handled by the recursive invocations of this function.
  298. // However, the special exception is that we do NOT skip function parameters
  299. // that are split across multiple lines. See the test case in FormatTest.cpp
  300. // that mentions "split function parameter alignment" for an example of this.
  301. template <typename F>
  302. static unsigned AlignTokens(const FormatStyle &Style, F &&Matches,
  303. SmallVector<WhitespaceManager::Change, 16> &Changes,
  304. unsigned StartAt) {
  305. unsigned MinColumn = 0;
  306. unsigned MaxColumn = UINT_MAX;
  307. // Line number of the start and the end of the current token sequence.
  308. unsigned StartOfSequence = 0;
  309. unsigned EndOfSequence = 0;
  310. // Measure the scope level (i.e. depth of (), [], {}) of the first token, and
  311. // abort when we hit any token in a higher scope than the starting one.
  312. auto IndentAndNestingLevel = StartAt < Changes.size()
  313. ? Changes[StartAt].indentAndNestingLevel()
  314. : std::pair<unsigned, unsigned>(0, 0);
  315. // Keep track of the number of commas before the matching tokens, we will only
  316. // align a sequence of matching tokens if they are preceded by the same number
  317. // of commas.
  318. unsigned CommasBeforeLastMatch = 0;
  319. unsigned CommasBeforeMatch = 0;
  320. // Whether a matching token has been found on the current line.
  321. bool FoundMatchOnLine = false;
  322. // Aligns a sequence of matching tokens, on the MinColumn column.
  323. //
  324. // Sequences start from the first matching token to align, and end at the
  325. // first token of the first line that doesn't need to be aligned.
  326. //
  327. // We need to adjust the StartOfTokenColumn of each Change that is on a line
  328. // containing any matching token to be aligned and located after such token.
  329. auto AlignCurrentSequence = [&] {
  330. if (StartOfSequence > 0 && StartOfSequence < EndOfSequence)
  331. AlignTokenSequence(StartOfSequence, EndOfSequence, MinColumn, Matches,
  332. Changes);
  333. MinColumn = 0;
  334. MaxColumn = UINT_MAX;
  335. StartOfSequence = 0;
  336. EndOfSequence = 0;
  337. };
  338. unsigned i = StartAt;
  339. for (unsigned e = Changes.size(); i != e; ++i) {
  340. if (Changes[i].indentAndNestingLevel() < IndentAndNestingLevel)
  341. break;
  342. if (Changes[i].NewlinesBefore != 0) {
  343. CommasBeforeMatch = 0;
  344. EndOfSequence = i;
  345. // If there is a blank line, or if the last line didn't contain any
  346. // matching token, the sequence ends here.
  347. if (Changes[i].NewlinesBefore > 1 || !FoundMatchOnLine)
  348. AlignCurrentSequence();
  349. FoundMatchOnLine = false;
  350. }
  351. if (Changes[i].Tok->is(tok::comma)) {
  352. ++CommasBeforeMatch;
  353. } else if (Changes[i].indentAndNestingLevel() > IndentAndNestingLevel) {
  354. // Call AlignTokens recursively, skipping over this scope block.
  355. unsigned StoppedAt = AlignTokens(Style, Matches, Changes, i);
  356. i = StoppedAt - 1;
  357. continue;
  358. }
  359. if (!Matches(Changes[i]))
  360. continue;
  361. // If there is more than one matching token per line, or if the number of
  362. // preceding commas, do not match anymore, end the sequence.
  363. if (FoundMatchOnLine || CommasBeforeMatch != CommasBeforeLastMatch)
  364. AlignCurrentSequence();
  365. CommasBeforeLastMatch = CommasBeforeMatch;
  366. FoundMatchOnLine = true;
  367. if (StartOfSequence == 0)
  368. StartOfSequence = i;
  369. unsigned ChangeMinColumn = Changes[i].StartOfTokenColumn;
  370. int LineLengthAfter = -Changes[i].Spaces;
  371. for (unsigned j = i; j != e && Changes[j].NewlinesBefore == 0; ++j)
  372. LineLengthAfter += Changes[j].Spaces + Changes[j].TokenLength;
  373. unsigned ChangeMaxColumn = Style.ColumnLimit - LineLengthAfter;
  374. // If we are restricted by the maximum column width, end the sequence.
  375. if (ChangeMinColumn > MaxColumn || ChangeMaxColumn < MinColumn ||
  376. CommasBeforeLastMatch != CommasBeforeMatch) {
  377. AlignCurrentSequence();
  378. StartOfSequence = i;
  379. }
  380. MinColumn = std::max(MinColumn, ChangeMinColumn);
  381. MaxColumn = std::min(MaxColumn, ChangeMaxColumn);
  382. }
  383. EndOfSequence = i;
  384. AlignCurrentSequence();
  385. return i;
  386. }
  387. void WhitespaceManager::alignConsecutiveAssignments() {
  388. if (!Style.AlignConsecutiveAssignments)
  389. return;
  390. AlignTokens(
  391. Style,
  392. [&](const Change &C) {
  393. // Do not align on equal signs that are first on a line.
  394. if (C.NewlinesBefore > 0)
  395. return false;
  396. // Do not align on equal signs that are last on a line.
  397. if (&C != &Changes.back() && (&C + 1)->NewlinesBefore > 0)
  398. return false;
  399. return C.Tok->is(tok::equal);
  400. },
  401. Changes, /*StartAt=*/0);
  402. }
  403. void WhitespaceManager::alignConsecutiveDeclarations() {
  404. if (!Style.AlignConsecutiveDeclarations)
  405. return;
  406. // FIXME: Currently we don't handle properly the PointerAlignment: Right
  407. // The * and & are not aligned and are left dangling. Something has to be done
  408. // about it, but it raises the question of alignment of code like:
  409. // const char* const* v1;
  410. // float const* v2;
  411. // SomeVeryLongType const& v3;
  412. AlignTokens(
  413. Style,
  414. [](Change const &C) {
  415. // tok::kw_operator is necessary for aligning operator overload
  416. // definitions.
  417. return C.Tok->is(TT_StartOfName) ||
  418. C.Tok->is(TT_FunctionDeclarationName) ||
  419. C.Tok->is(tok::kw_operator);
  420. },
  421. Changes, /*StartAt=*/0);
  422. }
  423. void WhitespaceManager::alignTrailingComments() {
  424. unsigned MinColumn = 0;
  425. unsigned MaxColumn = UINT_MAX;
  426. unsigned StartOfSequence = 0;
  427. bool BreakBeforeNext = false;
  428. unsigned Newlines = 0;
  429. for (unsigned i = 0, e = Changes.size(); i != e; ++i) {
  430. if (Changes[i].StartOfBlockComment)
  431. continue;
  432. Newlines += Changes[i].NewlinesBefore;
  433. if (!Changes[i].IsTrailingComment)
  434. continue;
  435. unsigned ChangeMinColumn = Changes[i].StartOfTokenColumn;
  436. unsigned ChangeMaxColumn;
  437. if (Style.ColumnLimit == 0)
  438. ChangeMaxColumn = UINT_MAX;
  439. else if (Style.ColumnLimit >= Changes[i].TokenLength)
  440. ChangeMaxColumn = Style.ColumnLimit - Changes[i].TokenLength;
  441. else
  442. ChangeMaxColumn = ChangeMinColumn;
  443. // If we don't create a replacement for this change, we have to consider
  444. // it to be immovable.
  445. if (!Changes[i].CreateReplacement)
  446. ChangeMaxColumn = ChangeMinColumn;
  447. if (i + 1 != e && Changes[i + 1].ContinuesPPDirective)
  448. ChangeMaxColumn -= 2;
  449. // If this comment follows an } in column 0, it probably documents the
  450. // closing of a namespace and we don't want to align it.
  451. bool FollowsRBraceInColumn0 = i > 0 && Changes[i].NewlinesBefore == 0 &&
  452. Changes[i - 1].Tok->is(tok::r_brace) &&
  453. Changes[i - 1].StartOfTokenColumn == 0;
  454. bool WasAlignedWithStartOfNextLine = false;
  455. if (Changes[i].NewlinesBefore == 1) { // A comment on its own line.
  456. unsigned CommentColumn = SourceMgr.getSpellingColumnNumber(
  457. Changes[i].OriginalWhitespaceRange.getEnd());
  458. for (unsigned j = i + 1; j != e; ++j) {
  459. if (Changes[j].Tok->is(tok::comment))
  460. continue;
  461. unsigned NextColumn = SourceMgr.getSpellingColumnNumber(
  462. Changes[j].OriginalWhitespaceRange.getEnd());
  463. // The start of the next token was previously aligned with the
  464. // start of this comment.
  465. WasAlignedWithStartOfNextLine =
  466. CommentColumn == NextColumn ||
  467. CommentColumn == NextColumn + Style.IndentWidth;
  468. break;
  469. }
  470. }
  471. if (!Style.AlignTrailingComments || FollowsRBraceInColumn0) {
  472. alignTrailingComments(StartOfSequence, i, MinColumn);
  473. MinColumn = ChangeMinColumn;
  474. MaxColumn = ChangeMinColumn;
  475. StartOfSequence = i;
  476. } else if (BreakBeforeNext || Newlines > 1 ||
  477. (ChangeMinColumn > MaxColumn || ChangeMaxColumn < MinColumn) ||
  478. // Break the comment sequence if the previous line did not end
  479. // in a trailing comment.
  480. (Changes[i].NewlinesBefore == 1 && i > 0 &&
  481. !Changes[i - 1].IsTrailingComment) ||
  482. WasAlignedWithStartOfNextLine) {
  483. alignTrailingComments(StartOfSequence, i, MinColumn);
  484. MinColumn = ChangeMinColumn;
  485. MaxColumn = ChangeMaxColumn;
  486. StartOfSequence = i;
  487. } else {
  488. MinColumn = std::max(MinColumn, ChangeMinColumn);
  489. MaxColumn = std::min(MaxColumn, ChangeMaxColumn);
  490. }
  491. BreakBeforeNext = (i == 0) || (Changes[i].NewlinesBefore > 1) ||
  492. // Never start a sequence with a comment at the beginning
  493. // of the line.
  494. (Changes[i].NewlinesBefore == 1 && StartOfSequence == i);
  495. Newlines = 0;
  496. }
  497. alignTrailingComments(StartOfSequence, Changes.size(), MinColumn);
  498. }
  499. void WhitespaceManager::alignTrailingComments(unsigned Start, unsigned End,
  500. unsigned Column) {
  501. for (unsigned i = Start; i != End; ++i) {
  502. int Shift = 0;
  503. if (Changes[i].IsTrailingComment) {
  504. Shift = Column - Changes[i].StartOfTokenColumn;
  505. }
  506. if (Changes[i].StartOfBlockComment) {
  507. Shift = Changes[i].IndentationOffset +
  508. Changes[i].StartOfBlockComment->StartOfTokenColumn -
  509. Changes[i].StartOfTokenColumn;
  510. }
  511. assert(Shift >= 0);
  512. Changes[i].Spaces += Shift;
  513. if (i + 1 != Changes.size())
  514. Changes[i + 1].PreviousEndOfTokenColumn += Shift;
  515. Changes[i].StartOfTokenColumn += Shift;
  516. }
  517. }
  518. void WhitespaceManager::alignEscapedNewlines() {
  519. if (Style.AlignEscapedNewlines == FormatStyle::ENAS_DontAlign)
  520. return;
  521. bool AlignLeft = Style.AlignEscapedNewlines == FormatStyle::ENAS_Left;
  522. unsigned MaxEndOfLine = AlignLeft ? 0 : Style.ColumnLimit;
  523. unsigned StartOfMacro = 0;
  524. for (unsigned i = 1, e = Changes.size(); i < e; ++i) {
  525. Change &C = Changes[i];
  526. if (C.NewlinesBefore > 0) {
  527. if (C.ContinuesPPDirective) {
  528. MaxEndOfLine = std::max(C.PreviousEndOfTokenColumn + 2, MaxEndOfLine);
  529. } else {
  530. alignEscapedNewlines(StartOfMacro + 1, i, MaxEndOfLine);
  531. MaxEndOfLine = AlignLeft ? 0 : Style.ColumnLimit;
  532. StartOfMacro = i;
  533. }
  534. }
  535. }
  536. alignEscapedNewlines(StartOfMacro + 1, Changes.size(), MaxEndOfLine);
  537. }
  538. void WhitespaceManager::alignEscapedNewlines(unsigned Start, unsigned End,
  539. unsigned Column) {
  540. for (unsigned i = Start; i < End; ++i) {
  541. Change &C = Changes[i];
  542. if (C.NewlinesBefore > 0) {
  543. assert(C.ContinuesPPDirective);
  544. if (C.PreviousEndOfTokenColumn + 1 > Column)
  545. C.EscapedNewlineColumn = 0;
  546. else
  547. C.EscapedNewlineColumn = Column;
  548. }
  549. }
  550. }
  551. void WhitespaceManager::generateChanges() {
  552. for (unsigned i = 0, e = Changes.size(); i != e; ++i) {
  553. const Change &C = Changes[i];
  554. if (i > 0) {
  555. assert(Changes[i - 1].OriginalWhitespaceRange.getBegin() !=
  556. C.OriginalWhitespaceRange.getBegin() &&
  557. "Generating two replacements for the same location");
  558. }
  559. if (C.CreateReplacement) {
  560. std::string ReplacementText = C.PreviousLinePostfix;
  561. if (C.ContinuesPPDirective)
  562. appendEscapedNewlineText(ReplacementText, C.NewlinesBefore,
  563. C.PreviousEndOfTokenColumn,
  564. C.EscapedNewlineColumn);
  565. else
  566. appendNewlineText(ReplacementText, C.NewlinesBefore);
  567. appendIndentText(ReplacementText, C.Tok->IndentLevel,
  568. std::max(0, C.Spaces),
  569. C.StartOfTokenColumn - std::max(0, C.Spaces));
  570. ReplacementText.append(C.CurrentLinePrefix);
  571. storeReplacement(C.OriginalWhitespaceRange, ReplacementText);
  572. }
  573. }
  574. }
  575. void WhitespaceManager::storeReplacement(SourceRange Range, StringRef Text) {
  576. unsigned WhitespaceLength = SourceMgr.getFileOffset(Range.getEnd()) -
  577. SourceMgr.getFileOffset(Range.getBegin());
  578. // Don't create a replacement, if it does not change anything.
  579. if (StringRef(SourceMgr.getCharacterData(Range.getBegin()),
  580. WhitespaceLength) == Text)
  581. return;
  582. auto Err = Replaces.add(tooling::Replacement(
  583. SourceMgr, CharSourceRange::getCharRange(Range), Text));
  584. // FIXME: better error handling. For now, just print an error message in the
  585. // release version.
  586. if (Err) {
  587. llvm::errs() << llvm::toString(std::move(Err)) << "\n";
  588. assert(false);
  589. }
  590. }
  591. void WhitespaceManager::appendNewlineText(std::string &Text,
  592. unsigned Newlines) {
  593. for (unsigned i = 0; i < Newlines; ++i)
  594. Text.append(UseCRLF ? "\r\n" : "\n");
  595. }
  596. void WhitespaceManager::appendEscapedNewlineText(
  597. std::string &Text, unsigned Newlines, unsigned PreviousEndOfTokenColumn,
  598. unsigned EscapedNewlineColumn) {
  599. if (Newlines > 0) {
  600. unsigned Spaces =
  601. std::max<int>(1, EscapedNewlineColumn - PreviousEndOfTokenColumn - 1);
  602. for (unsigned i = 0; i < Newlines; ++i) {
  603. Text.append(Spaces, ' ');
  604. Text.append(UseCRLF ? "\\\r\n" : "\\\n");
  605. Spaces = std::max<int>(0, EscapedNewlineColumn - 1);
  606. }
  607. }
  608. }
  609. void WhitespaceManager::appendIndentText(std::string &Text,
  610. unsigned IndentLevel, unsigned Spaces,
  611. unsigned WhitespaceStartColumn) {
  612. switch (Style.UseTab) {
  613. case FormatStyle::UT_Never:
  614. Text.append(Spaces, ' ');
  615. break;
  616. case FormatStyle::UT_Always: {
  617. unsigned FirstTabWidth =
  618. Style.TabWidth - WhitespaceStartColumn % Style.TabWidth;
  619. // Insert only spaces when we want to end up before the next tab.
  620. if (Spaces < FirstTabWidth || Spaces == 1) {
  621. Text.append(Spaces, ' ');
  622. break;
  623. }
  624. // Align to the next tab.
  625. Spaces -= FirstTabWidth;
  626. Text.append("\t");
  627. Text.append(Spaces / Style.TabWidth, '\t');
  628. Text.append(Spaces % Style.TabWidth, ' ');
  629. break;
  630. }
  631. case FormatStyle::UT_ForIndentation:
  632. if (WhitespaceStartColumn == 0) {
  633. unsigned Indentation = IndentLevel * Style.IndentWidth;
  634. // This happens, e.g. when a line in a block comment is indented less than
  635. // the first one.
  636. if (Indentation > Spaces)
  637. Indentation = Spaces;
  638. unsigned Tabs = Indentation / Style.TabWidth;
  639. Text.append(Tabs, '\t');
  640. Spaces -= Tabs * Style.TabWidth;
  641. }
  642. Text.append(Spaces, ' ');
  643. break;
  644. case FormatStyle::UT_ForContinuationAndIndentation:
  645. if (WhitespaceStartColumn == 0) {
  646. unsigned Tabs = Spaces / Style.TabWidth;
  647. Text.append(Tabs, '\t');
  648. Spaces -= Tabs * Style.TabWidth;
  649. }
  650. Text.append(Spaces, ' ');
  651. break;
  652. }
  653. }
  654. } // namespace format
  655. } // namespace clang