FormatToken.cpp 11 KB

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