FormatToken.cpp 12 KB

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