WhitespaceManager.cpp 28 KB

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