FormatToken.cpp 10 KB

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