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