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