FormatToken.cpp 11 KB

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