FormatToken.cpp 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195
  1. //===--- FormatToken.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 specific functions of \c FormatTokens and their
  12. /// roles.
  13. ///
  14. //===----------------------------------------------------------------------===//
  15. #include "FormatToken.h"
  16. #include "ContinuationIndenter.h"
  17. #include "clang/Format/Format.h"
  18. #include "llvm/ADT/SmallVector.h"
  19. #include "llvm/Support/Debug.h"
  20. namespace clang {
  21. namespace format {
  22. TokenRole::~TokenRole() {}
  23. void TokenRole::precomputeFormattingInfos(const FormatToken *Token) {}
  24. unsigned CommaSeparatedList::format(LineState &State,
  25. ContinuationIndenter *Indenter,
  26. bool DryRun) {
  27. if (!State.NextToken->Previous || !State.NextToken->Previous->Previous ||
  28. Commas.size() <= 2)
  29. return 0;
  30. // Ensure that we start on the opening brace.
  31. const FormatToken *LBrace = State.NextToken->Previous->Previous;
  32. if (LBrace->isNot(tok::l_brace) ||
  33. LBrace->BlockKind == BK_Block ||
  34. LBrace->Next->Type == TT_DesignatedInitializerPeriod)
  35. return 0;
  36. // Calculate the number of code points we have to format this list. As the
  37. // first token is already placed, we have to subtract it.
  38. unsigned RemainingCodePoints = Style.ColumnLimit - State.Column +
  39. State.NextToken->Previous->ColumnWidth;
  40. // Find the best ColumnFormat, i.e. the best number of columns to use.
  41. const ColumnFormat *Format = getColumnFormat(RemainingCodePoints);
  42. if (!Format)
  43. return 0;
  44. // Format the entire list.
  45. unsigned Penalty = 0;
  46. unsigned Column = 0;
  47. unsigned Item = 0;
  48. while (State.NextToken != LBrace->MatchingParen) {
  49. bool NewLine = false;
  50. unsigned ExtraSpaces = 0;
  51. // If the previous token was one of our commas, we are now on the next item.
  52. if (Item < Commas.size() && State.NextToken->Previous == Commas[Item]) {
  53. if (!State.NextToken->isTrailingComment()) {
  54. ExtraSpaces += Format->ColumnSizes[Column] - ItemLengths[Item];
  55. ++Column;
  56. }
  57. ++Item;
  58. }
  59. if (Column == Format->Columns || State.NextToken->MustBreakBefore) {
  60. Column = 0;
  61. NewLine = true;
  62. }
  63. // Place token using the continuation indenter and store the penalty.
  64. Penalty += Indenter->addTokenToState(State, NewLine, DryRun, ExtraSpaces);
  65. }
  66. return Penalty;
  67. }
  68. // Returns the lengths in code points between Begin and End (both included),
  69. // assuming that the entire sequence is put on a single line.
  70. static unsigned CodePointsBetween(const FormatToken *Begin,
  71. const FormatToken *End) {
  72. assert(End->TotalLength >= Begin->TotalLength);
  73. return End->TotalLength - Begin->TotalLength + Begin->ColumnWidth;
  74. }
  75. void CommaSeparatedList::precomputeFormattingInfos(const FormatToken *Token) {
  76. // FIXME: At some point we might want to do this for other lists, too.
  77. if (!Token->MatchingParen || Token->isNot(tok::l_brace))
  78. return;
  79. FormatToken *ItemBegin = Token->Next;
  80. SmallVector<bool, 8> MustBreakBeforeItem;
  81. // The lengths of an item if it is put at the end of the line. This includes
  82. // trailing comments which are otherwise ignored for column alignment.
  83. SmallVector<unsigned, 8> EndOfLineItemLength;
  84. for (unsigned i = 0, e = Commas.size() + 1; i != e; ++i) {
  85. // Skip comments on their own line.
  86. while (ItemBegin->HasUnescapedNewline && ItemBegin->isTrailingComment())
  87. ItemBegin = ItemBegin->Next;
  88. MustBreakBeforeItem.push_back(ItemBegin->MustBreakBefore);
  89. const FormatToken *ItemEnd = NULL;
  90. if (i == Commas.size()) {
  91. ItemEnd = Token->MatchingParen;
  92. const FormatToken *NonCommentEnd = ItemEnd->getPreviousNonComment();
  93. ItemLengths.push_back(CodePointsBetween(ItemBegin, NonCommentEnd));
  94. if (Style.Cpp11BracedListStyle) {
  95. // In Cpp11 braced list style, the } and possibly other subsequent
  96. // tokens will need to stay on a line with the last element.
  97. while (ItemEnd->Next && !ItemEnd->Next->CanBreakBefore)
  98. ItemEnd = ItemEnd->Next;
  99. } else {
  100. // In other braced lists styles, the "}" can be wrapped to the new line.
  101. ItemEnd = Token->MatchingParen->Previous;
  102. }
  103. } else {
  104. ItemEnd = Commas[i];
  105. // The comma is counted as part of the item when calculating the length.
  106. ItemLengths.push_back(CodePointsBetween(ItemBegin, ItemEnd));
  107. // Consume trailing comments so the are included in EndOfLineItemLength.
  108. if (ItemEnd->Next && !ItemEnd->Next->HasUnescapedNewline &&
  109. ItemEnd->Next->isTrailingComment())
  110. ItemEnd = ItemEnd->Next;
  111. }
  112. EndOfLineItemLength.push_back(CodePointsBetween(ItemBegin, ItemEnd));
  113. // If there is a trailing comma in the list, the next item will start at the
  114. // closing brace. Don't create an extra item for this.
  115. if (ItemEnd->getNextNonComment() == Token->MatchingParen)
  116. break;
  117. ItemBegin = ItemEnd->Next;
  118. }
  119. // We can never place more than ColumnLimit / 3 items in a row (because of the
  120. // spaces and the comma).
  121. for (unsigned Columns = 1; Columns <= Style.ColumnLimit / 3; ++Columns) {
  122. ColumnFormat Format;
  123. Format.Columns = Columns;
  124. Format.ColumnSizes.resize(Columns);
  125. Format.LineCount = 0;
  126. bool HasRowWithSufficientColumns = false;
  127. unsigned Column = 0;
  128. for (unsigned i = 0, e = ItemLengths.size(); i != e; ++i) {
  129. assert(i < MustBreakBeforeItem.size());
  130. if (MustBreakBeforeItem[i] || Column == Columns) {
  131. ++Format.LineCount;
  132. Column = 0;
  133. }
  134. if (Column == Columns - 1)
  135. HasRowWithSufficientColumns = true;
  136. unsigned length =
  137. (Column == Columns - 1) ? EndOfLineItemLength[i] : ItemLengths[i];
  138. Format.ColumnSizes[Column] =
  139. std::max(Format.ColumnSizes[Column], length);
  140. ++Column;
  141. }
  142. // If all rows are terminated early (e.g. by trailing comments), we don't
  143. // need to look further.
  144. if (!HasRowWithSufficientColumns)
  145. break;
  146. Format.TotalWidth = Columns - 1; // Width of the N-1 spaces.
  147. for (unsigned i = 0; i < Columns; ++i) {
  148. Format.TotalWidth += Format.ColumnSizes[i];
  149. }
  150. // Ignore layouts that are bound to violate the column limit.
  151. if (Format.TotalWidth > Style.ColumnLimit)
  152. continue;
  153. Formats.push_back(Format);
  154. }
  155. }
  156. const CommaSeparatedList::ColumnFormat *
  157. CommaSeparatedList::getColumnFormat(unsigned RemainingCharacters) const {
  158. const ColumnFormat *BestFormat = NULL;
  159. for (SmallVector<ColumnFormat, 4>::const_reverse_iterator
  160. I = Formats.rbegin(),
  161. E = Formats.rend();
  162. I != E; ++I) {
  163. if (I->TotalWidth <= RemainingCharacters) {
  164. if (BestFormat && I->LineCount > BestFormat->LineCount)
  165. break;
  166. BestFormat = &*I;
  167. }
  168. }
  169. return BestFormat;
  170. }
  171. } // namespace format
  172. } // namespace clang