FormatToken.cpp 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  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 "ContinuationIndenter.h"
  16. #include "FormatToken.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. const char *getTokenTypeName(TokenType Type) {
  24. static const char *const TokNames[] = {
  25. #define TYPE(X) #X,
  26. LIST_TOKEN_TYPES
  27. #undef TYPE
  28. nullptr
  29. };
  30. if (Type < NUM_TOKEN_TYPES)
  31. return TokNames[Type];
  32. llvm_unreachable("unknown TokenType");
  33. return nullptr;
  34. }
  35. // FIXME: This is copy&pasted from Sema. Put it in a common place and remove
  36. // duplication.
  37. bool FormatToken::isSimpleTypeSpecifier() const {
  38. switch (Tok.getKind()) {
  39. case tok::kw_short:
  40. case tok::kw_long:
  41. case tok::kw___int64:
  42. case tok::kw___int128:
  43. case tok::kw_signed:
  44. case tok::kw_unsigned:
  45. case tok::kw_void:
  46. case tok::kw_char:
  47. case tok::kw_int:
  48. case tok::kw_half:
  49. case tok::kw_float:
  50. case tok::kw_double:
  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->isNot(tok::l_brace) || LBrace->BlockKind == BK_Block ||
  75. 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 || Token->isNot(tok::l_brace))
  130. return;
  131. // In C++11 braced list style, we should not format in columns unless they
  132. // have many items (20 or more) or we allow bin-packing of function call
  133. // arguments.
  134. if (Style.Cpp11BracedListStyle && !Style.BinPackArguments &&
  135. Commas.size() < 19)
  136. return;
  137. // Column format doesn't really make sense if we don't align after brackets.
  138. if (!Style.AlignAfterOpenBracket)
  139. return;
  140. FormatToken *ItemBegin = Token->Next;
  141. while (ItemBegin->isTrailingComment())
  142. ItemBegin = ItemBegin->Next;
  143. SmallVector<bool, 8> MustBreakBeforeItem;
  144. // The lengths of an item if it is put at the end of the line. This includes
  145. // trailing comments which are otherwise ignored for column alignment.
  146. SmallVector<unsigned, 8> EndOfLineItemLength;
  147. bool HasSeparatingComment = false;
  148. for (unsigned i = 0, e = Commas.size() + 1; i != e; ++i) {
  149. // Skip comments on their own line.
  150. while (ItemBegin->HasUnescapedNewline && ItemBegin->isTrailingComment()) {
  151. ItemBegin = ItemBegin->Next;
  152. HasSeparatingComment = i > 0;
  153. }
  154. MustBreakBeforeItem.push_back(ItemBegin->MustBreakBefore);
  155. if (ItemBegin->is(tok::l_brace))
  156. HasNestedBracedList = true;
  157. const FormatToken *ItemEnd = nullptr;
  158. if (i == Commas.size()) {
  159. ItemEnd = Token->MatchingParen;
  160. const FormatToken *NonCommentEnd = ItemEnd->getPreviousNonComment();
  161. ItemLengths.push_back(CodePointsBetween(ItemBegin, NonCommentEnd));
  162. if (Style.Cpp11BracedListStyle &&
  163. !ItemEnd->Previous->isTrailingComment()) {
  164. // In Cpp11 braced list style, the } and possibly other subsequent
  165. // tokens will need to stay on a line with the last element.
  166. while (ItemEnd->Next && !ItemEnd->Next->CanBreakBefore)
  167. ItemEnd = ItemEnd->Next;
  168. } else {
  169. // In other braced lists styles, the "}" can be wrapped to the new line.
  170. ItemEnd = Token->MatchingParen->Previous;
  171. }
  172. } else {
  173. ItemEnd = Commas[i];
  174. // The comma is counted as part of the item when calculating the length.
  175. ItemLengths.push_back(CodePointsBetween(ItemBegin, ItemEnd));
  176. // Consume trailing comments so the are included in EndOfLineItemLength.
  177. if (ItemEnd->Next && !ItemEnd->Next->HasUnescapedNewline &&
  178. ItemEnd->Next->isTrailingComment())
  179. ItemEnd = ItemEnd->Next;
  180. }
  181. EndOfLineItemLength.push_back(CodePointsBetween(ItemBegin, ItemEnd));
  182. // If there is a trailing comma in the list, the next item will start at the
  183. // closing brace. Don't create an extra item for this.
  184. if (ItemEnd->getNextNonComment() == Token->MatchingParen)
  185. break;
  186. ItemBegin = ItemEnd->Next;
  187. }
  188. // Don't use column layout for nested lists, lists with few elements and in
  189. // presence of separating comments.
  190. if (Token->NestingLevel != 0 || Commas.size() < 5 || HasSeparatingComment)
  191. return;
  192. // We can never place more than ColumnLimit / 3 items in a row (because of the
  193. // spaces and the comma).
  194. unsigned MaxItems = Style.ColumnLimit / 3;
  195. std::vector<unsigned> MinSizeInColumn;
  196. MinSizeInColumn.reserve(MaxItems);
  197. for (unsigned Columns = 1; Columns <= MaxItems; ++Columns) {
  198. ColumnFormat Format;
  199. Format.Columns = Columns;
  200. Format.ColumnSizes.resize(Columns);
  201. MinSizeInColumn.assign(Columns, UINT_MAX);
  202. Format.LineCount = 1;
  203. bool HasRowWithSufficientColumns = false;
  204. unsigned Column = 0;
  205. for (unsigned i = 0, e = ItemLengths.size(); i != e; ++i) {
  206. assert(i < MustBreakBeforeItem.size());
  207. if (MustBreakBeforeItem[i] || Column == Columns) {
  208. ++Format.LineCount;
  209. Column = 0;
  210. }
  211. if (Column == Columns - 1)
  212. HasRowWithSufficientColumns = true;
  213. unsigned Length =
  214. (Column == Columns - 1) ? EndOfLineItemLength[i] : ItemLengths[i];
  215. Format.ColumnSizes[Column] = std::max(Format.ColumnSizes[Column], Length);
  216. MinSizeInColumn[Column] = std::min(MinSizeInColumn[Column], Length);
  217. ++Column;
  218. }
  219. // If all rows are terminated early (e.g. by trailing comments), we don't
  220. // need to look further.
  221. if (!HasRowWithSufficientColumns)
  222. break;
  223. Format.TotalWidth = Columns - 1; // Width of the N-1 spaces.
  224. for (unsigned i = 0; i < Columns; ++i)
  225. Format.TotalWidth += Format.ColumnSizes[i];
  226. // Don't use this Format, if the difference between the longest and shortest
  227. // element in a column exceeds a threshold to avoid excessive spaces.
  228. if ([&] {
  229. for (unsigned i = 0; i < Columns - 1; ++i)
  230. if (Format.ColumnSizes[i] - MinSizeInColumn[i] > 10)
  231. return true;
  232. return false;
  233. }())
  234. continue;
  235. // Ignore layouts that are bound to violate the column limit.
  236. if (Format.TotalWidth > Style.ColumnLimit)
  237. continue;
  238. Formats.push_back(Format);
  239. }
  240. }
  241. const CommaSeparatedList::ColumnFormat *
  242. CommaSeparatedList::getColumnFormat(unsigned RemainingCharacters) const {
  243. const ColumnFormat *BestFormat = nullptr;
  244. for (SmallVector<ColumnFormat, 4>::const_reverse_iterator
  245. I = Formats.rbegin(),
  246. E = Formats.rend();
  247. I != E; ++I) {
  248. if (I->TotalWidth <= RemainingCharacters) {
  249. if (BestFormat && I->LineCount > BestFormat->LineCount)
  250. break;
  251. BestFormat = &*I;
  252. }
  253. }
  254. return BestFormat;
  255. }
  256. } // namespace format
  257. } // namespace clang