FormatToken.cpp 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  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. #include <climits>
  21. namespace clang {
  22. namespace format {
  23. // FIXME: This is copy&pasted from Sema. Put it in a common place and remove
  24. // duplication.
  25. bool FormatToken::isSimpleTypeSpecifier() const {
  26. switch (Tok.getKind()) {
  27. case tok::kw_short:
  28. case tok::kw_long:
  29. case tok::kw___int64:
  30. case tok::kw___int128:
  31. case tok::kw_signed:
  32. case tok::kw_unsigned:
  33. case tok::kw_void:
  34. case tok::kw_char:
  35. case tok::kw_int:
  36. case tok::kw_half:
  37. case tok::kw_float:
  38. case tok::kw_double:
  39. case tok::kw_wchar_t:
  40. case tok::kw_bool:
  41. case tok::kw___underlying_type:
  42. case tok::annot_typename:
  43. case tok::kw_char16_t:
  44. case tok::kw_char32_t:
  45. case tok::kw_typeof:
  46. case tok::kw_decltype:
  47. return true;
  48. default:
  49. return false;
  50. }
  51. }
  52. TokenRole::~TokenRole() {}
  53. void TokenRole::precomputeFormattingInfos(const FormatToken *Token) {}
  54. unsigned CommaSeparatedList::formatAfterToken(LineState &State,
  55. ContinuationIndenter *Indenter,
  56. bool DryRun) {
  57. if (State.NextToken == nullptr || !State.NextToken->Previous ||
  58. !State.NextToken->Previous->Previous)
  59. return 0;
  60. // Ensure that we start on the opening brace.
  61. const FormatToken *LBrace = State.NextToken->Previous->Previous;
  62. if (LBrace->isNot(tok::l_brace) || LBrace->BlockKind == BK_Block ||
  63. LBrace->Type == TT_DictLiteral ||
  64. LBrace->Next->Type == TT_DesignatedInitializerPeriod)
  65. return 0;
  66. // Calculate the number of code points we have to format this list. As the
  67. // first token is already placed, we have to subtract it.
  68. unsigned RemainingCodePoints =
  69. Style.ColumnLimit - State.Column + State.NextToken->Previous->ColumnWidth;
  70. // Find the best ColumnFormat, i.e. the best number of columns to use.
  71. const ColumnFormat *Format = getColumnFormat(RemainingCodePoints);
  72. // If no ColumnFormat can be used, the braced list would generally be
  73. // bin-packed. Add a severe penalty to this so that column layouts are
  74. // preferred if possible.
  75. if (!Format)
  76. return 10000;
  77. // Format the entire list.
  78. unsigned Penalty = 0;
  79. unsigned Column = 0;
  80. unsigned Item = 0;
  81. while (State.NextToken != LBrace->MatchingParen) {
  82. bool NewLine = false;
  83. unsigned ExtraSpaces = 0;
  84. // If the previous token was one of our commas, we are now on the next item.
  85. if (Item < Commas.size() && State.NextToken->Previous == Commas[Item]) {
  86. if (!State.NextToken->isTrailingComment()) {
  87. ExtraSpaces += Format->ColumnSizes[Column] - ItemLengths[Item];
  88. ++Column;
  89. }
  90. ++Item;
  91. }
  92. if (Column == Format->Columns || State.NextToken->MustBreakBefore) {
  93. Column = 0;
  94. NewLine = true;
  95. }
  96. // Place token using the continuation indenter and store the penalty.
  97. Penalty += Indenter->addTokenToState(State, NewLine, DryRun, ExtraSpaces);
  98. }
  99. return Penalty;
  100. }
  101. unsigned CommaSeparatedList::formatFromToken(LineState &State,
  102. ContinuationIndenter *Indenter,
  103. bool DryRun) {
  104. if (HasNestedBracedList)
  105. State.Stack.back().AvoidBinPacking = true;
  106. return 0;
  107. }
  108. // Returns the lengths in code points between Begin and End (both included),
  109. // assuming that the entire sequence is put on a single line.
  110. static unsigned CodePointsBetween(const FormatToken *Begin,
  111. const FormatToken *End) {
  112. assert(End->TotalLength >= Begin->TotalLength);
  113. return End->TotalLength - Begin->TotalLength + Begin->ColumnWidth;
  114. }
  115. void CommaSeparatedList::precomputeFormattingInfos(const FormatToken *Token) {
  116. // FIXME: At some point we might want to do this for other lists, too.
  117. if (!Token->MatchingParen || Token->isNot(tok::l_brace))
  118. return;
  119. // In C++11 braced list style, we should not format in columns unless they
  120. // have many items (20 or more) or we allow bin-packing of function
  121. // parameters.
  122. if (Style.Cpp11BracedListStyle && !Style.BinPackParameters &&
  123. Commas.size() < 19)
  124. return;
  125. // Column format doesn't really make sense if we don't align after brackets.
  126. if (!Style.AlignAfterOpenBracket)
  127. return;
  128. FormatToken *ItemBegin = Token->Next;
  129. SmallVector<bool, 8> MustBreakBeforeItem;
  130. // The lengths of an item if it is put at the end of the line. This includes
  131. // trailing comments which are otherwise ignored for column alignment.
  132. SmallVector<unsigned, 8> EndOfLineItemLength;
  133. for (unsigned i = 0, e = Commas.size() + 1; i != e; ++i) {
  134. // Skip comments on their own line.
  135. while (ItemBegin->HasUnescapedNewline && ItemBegin->isTrailingComment())
  136. ItemBegin = ItemBegin->Next;
  137. MustBreakBeforeItem.push_back(ItemBegin->MustBreakBefore);
  138. if (ItemBegin->is(tok::l_brace))
  139. HasNestedBracedList = true;
  140. const FormatToken *ItemEnd = nullptr;
  141. if (i == Commas.size()) {
  142. ItemEnd = Token->MatchingParen;
  143. const FormatToken *NonCommentEnd = ItemEnd->getPreviousNonComment();
  144. ItemLengths.push_back(CodePointsBetween(ItemBegin, NonCommentEnd));
  145. if (Style.Cpp11BracedListStyle) {
  146. // In Cpp11 braced list style, the } and possibly other subsequent
  147. // tokens will need to stay on a line with the last element.
  148. while (ItemEnd->Next && !ItemEnd->Next->CanBreakBefore)
  149. ItemEnd = ItemEnd->Next;
  150. } else {
  151. // In other braced lists styles, the "}" can be wrapped to the new line.
  152. ItemEnd = Token->MatchingParen->Previous;
  153. }
  154. } else {
  155. ItemEnd = Commas[i];
  156. // The comma is counted as part of the item when calculating the length.
  157. ItemLengths.push_back(CodePointsBetween(ItemBegin, ItemEnd));
  158. // Consume trailing comments so the are included in EndOfLineItemLength.
  159. if (ItemEnd->Next && !ItemEnd->Next->HasUnescapedNewline &&
  160. ItemEnd->Next->isTrailingComment())
  161. ItemEnd = ItemEnd->Next;
  162. }
  163. EndOfLineItemLength.push_back(CodePointsBetween(ItemBegin, ItemEnd));
  164. // If there is a trailing comma in the list, the next item will start at the
  165. // closing brace. Don't create an extra item for this.
  166. if (ItemEnd->getNextNonComment() == Token->MatchingParen)
  167. break;
  168. ItemBegin = ItemEnd->Next;
  169. }
  170. // If this doesn't have a nested list, we require at least 6 elements in order
  171. // create a column layout. If it has a nested list, column layout ensures one
  172. // list element per line.
  173. if (Commas.size() < 5 || Token->NestingLevel != 0)
  174. return;
  175. // We can never place more than ColumnLimit / 3 items in a row (because of the
  176. // spaces and the comma).
  177. for (unsigned Columns = 1; Columns <= Style.ColumnLimit / 3; ++Columns) {
  178. ColumnFormat Format;
  179. Format.Columns = Columns;
  180. Format.ColumnSizes.resize(Columns);
  181. std::vector<unsigned> MinSizeInColumn(Columns, UINT_MAX);
  182. Format.LineCount = 1;
  183. bool HasRowWithSufficientColumns = false;
  184. unsigned Column = 0;
  185. for (unsigned i = 0, e = ItemLengths.size(); i != e; ++i) {
  186. assert(i < MustBreakBeforeItem.size());
  187. if (MustBreakBeforeItem[i] || Column == Columns) {
  188. ++Format.LineCount;
  189. Column = 0;
  190. }
  191. if (Column == Columns - 1)
  192. HasRowWithSufficientColumns = true;
  193. unsigned Length =
  194. (Column == Columns - 1) ? EndOfLineItemLength[i] : ItemLengths[i];
  195. Format.ColumnSizes[Column] = std::max(Format.ColumnSizes[Column], Length);
  196. MinSizeInColumn[Column] = std::min(MinSizeInColumn[Column], Length);
  197. ++Column;
  198. }
  199. // If all rows are terminated early (e.g. by trailing comments), we don't
  200. // need to look further.
  201. if (!HasRowWithSufficientColumns)
  202. break;
  203. Format.TotalWidth = Columns - 1; // Width of the N-1 spaces.
  204. for (unsigned i = 0; i < Columns; ++i)
  205. Format.TotalWidth += Format.ColumnSizes[i];
  206. // Don't use this Format, if the difference between the longest and shortest
  207. // element in a column exceeds a threshold to avoid excessive spaces.
  208. if ([&] {
  209. for (unsigned i = 0; i < Columns - 1; ++i)
  210. if (Format.ColumnSizes[i] - MinSizeInColumn[i] > 10)
  211. return true;
  212. return false;
  213. }())
  214. continue;
  215. // Ignore layouts that are bound to violate the column limit.
  216. if (Format.TotalWidth > Style.ColumnLimit)
  217. continue;
  218. Formats.push_back(Format);
  219. }
  220. }
  221. const CommaSeparatedList::ColumnFormat *
  222. CommaSeparatedList::getColumnFormat(unsigned RemainingCharacters) const {
  223. const ColumnFormat *BestFormat = nullptr;
  224. for (SmallVector<ColumnFormat, 4>::const_reverse_iterator
  225. I = Formats.rbegin(),
  226. E = Formats.rend();
  227. I != E; ++I) {
  228. if (I->TotalWidth <= RemainingCharacters) {
  229. if (BestFormat && I->LineCount > BestFormat->LineCount)
  230. break;
  231. BestFormat = &*I;
  232. }
  233. }
  234. return BestFormat;
  235. }
  236. } // namespace format
  237. } // namespace clang