1 //===--- FormatToken.cpp - Format C++ code --------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
11 /// This file implements specific functions of \c FormatTokens and their
14 //===----------------------------------------------------------------------===//
16 #include "FormatToken.h"
17 #include "ContinuationIndenter.h"
18 #include "llvm/ADT/SmallVector.h"
19 #include "llvm/Support/Debug.h"
25 const char *getTokenTypeName(TokenType Type) {
26 static const char *const TokNames[] = {
32 if (Type < NUM_TOKEN_TYPES)
33 return TokNames[Type];
34 llvm_unreachable("unknown TokenType");
38 // FIXME: This is copy&pasted from Sema. Put it in a common place and remove
40 bool FormatToken::isSimpleTypeSpecifier() const {
41 switch (Tok.getKind()) {
45 case tok::kw___int128:
47 case tok::kw_unsigned:
54 case tok::kw__Float16:
55 case tok::kw___float128:
58 case tok::kw___underlying_type:
59 case tok::annot_typename:
61 case tok::kw_char16_t:
62 case tok::kw_char32_t:
64 case tok::kw_decltype:
71 TokenRole::~TokenRole() {}
73 void TokenRole::precomputeFormattingInfos(const FormatToken *Token) {}
75 unsigned CommaSeparatedList::formatAfterToken(LineState &State,
76 ContinuationIndenter *Indenter,
78 if (State.NextToken == nullptr || !State.NextToken->Previous)
81 if (Formats.size() == 1)
82 return 0; // Handled by formatFromToken
84 // Ensure that we start on the opening brace.
85 const FormatToken *LBrace =
86 State.NextToken->Previous->getPreviousNonComment();
87 if (!LBrace || !LBrace->isOneOf(tok::l_brace, TT_ArrayInitializerLSquare) ||
88 LBrace->BlockKind == BK_Block || LBrace->Type == TT_DictLiteral ||
89 LBrace->Next->Type == TT_DesignatedInitializerPeriod)
92 // Calculate the number of code points we have to format this list. As the
93 // first token is already placed, we have to subtract it.
94 unsigned RemainingCodePoints =
95 Style.ColumnLimit - State.Column + State.NextToken->Previous->ColumnWidth;
97 // Find the best ColumnFormat, i.e. the best number of columns to use.
98 const ColumnFormat *Format = getColumnFormat(RemainingCodePoints);
100 // If no ColumnFormat can be used, the braced list would generally be
101 // bin-packed. Add a severe penalty to this so that column layouts are
102 // preferred if possible.
106 // Format the entire list.
107 unsigned Penalty = 0;
110 while (State.NextToken != LBrace->MatchingParen) {
111 bool NewLine = false;
112 unsigned ExtraSpaces = 0;
114 // If the previous token was one of our commas, we are now on the next item.
115 if (Item < Commas.size() && State.NextToken->Previous == Commas[Item]) {
116 if (!State.NextToken->isTrailingComment()) {
117 ExtraSpaces += Format->ColumnSizes[Column] - ItemLengths[Item];
123 if (Column == Format->Columns || State.NextToken->MustBreakBefore) {
128 // Place token using the continuation indenter and store the penalty.
129 Penalty += Indenter->addTokenToState(State, NewLine, DryRun, ExtraSpaces);
134 unsigned CommaSeparatedList::formatFromToken(LineState &State,
135 ContinuationIndenter *Indenter,
137 // Formatting with 1 Column isn't really a column layout, so we don't need the
138 // special logic here. We can just avoid bin packing any of the parameters.
139 if (Formats.size() == 1 || HasNestedBracedList)
140 State.Stack.back().AvoidBinPacking = true;
144 // Returns the lengths in code points between Begin and End (both included),
145 // assuming that the entire sequence is put on a single line.
146 static unsigned CodePointsBetween(const FormatToken *Begin,
147 const FormatToken *End) {
148 assert(End->TotalLength >= Begin->TotalLength);
149 return End->TotalLength - Begin->TotalLength + Begin->ColumnWidth;
152 void CommaSeparatedList::precomputeFormattingInfos(const FormatToken *Token) {
153 // FIXME: At some point we might want to do this for other lists, too.
154 if (!Token->MatchingParen ||
155 !Token->isOneOf(tok::l_brace, TT_ArrayInitializerLSquare))
158 // In C++11 braced list style, we should not format in columns unless they
159 // have many items (20 or more) or we allow bin-packing of function call
161 if (Style.Cpp11BracedListStyle && !Style.BinPackArguments &&
165 // Limit column layout for JavaScript array initializers to 20 or more items
166 // for now to introduce it carefully. We can become more aggressive if this
168 if (Token->is(TT_ArrayInitializerLSquare) && Commas.size() < 19)
171 // Column format doesn't really make sense if we don't align after brackets.
172 if (Style.AlignAfterOpenBracket == FormatStyle::BAS_DontAlign)
175 FormatToken *ItemBegin = Token->Next;
176 while (ItemBegin->isTrailingComment())
177 ItemBegin = ItemBegin->Next;
178 SmallVector<bool, 8> MustBreakBeforeItem;
180 // The lengths of an item if it is put at the end of the line. This includes
181 // trailing comments which are otherwise ignored for column alignment.
182 SmallVector<unsigned, 8> EndOfLineItemLength;
184 bool HasSeparatingComment = false;
185 for (unsigned i = 0, e = Commas.size() + 1; i != e; ++i) {
186 // Skip comments on their own line.
187 while (ItemBegin->HasUnescapedNewline && ItemBegin->isTrailingComment()) {
188 ItemBegin = ItemBegin->Next;
189 HasSeparatingComment = i > 0;
192 MustBreakBeforeItem.push_back(ItemBegin->MustBreakBefore);
193 if (ItemBegin->is(tok::l_brace))
194 HasNestedBracedList = true;
195 const FormatToken *ItemEnd = nullptr;
196 if (i == Commas.size()) {
197 ItemEnd = Token->MatchingParen;
198 const FormatToken *NonCommentEnd = ItemEnd->getPreviousNonComment();
199 ItemLengths.push_back(CodePointsBetween(ItemBegin, NonCommentEnd));
200 if (Style.Cpp11BracedListStyle &&
201 !ItemEnd->Previous->isTrailingComment()) {
202 // In Cpp11 braced list style, the } and possibly other subsequent
203 // tokens will need to stay on a line with the last element.
204 while (ItemEnd->Next && !ItemEnd->Next->CanBreakBefore)
205 ItemEnd = ItemEnd->Next;
207 // In other braced lists styles, the "}" can be wrapped to the new line.
208 ItemEnd = Token->MatchingParen->Previous;
212 // The comma is counted as part of the item when calculating the length.
213 ItemLengths.push_back(CodePointsBetween(ItemBegin, ItemEnd));
215 // Consume trailing comments so the are included in EndOfLineItemLength.
216 if (ItemEnd->Next && !ItemEnd->Next->HasUnescapedNewline &&
217 ItemEnd->Next->isTrailingComment())
218 ItemEnd = ItemEnd->Next;
220 EndOfLineItemLength.push_back(CodePointsBetween(ItemBegin, ItemEnd));
221 // If there is a trailing comma in the list, the next item will start at the
222 // closing brace. Don't create an extra item for this.
223 if (ItemEnd->getNextNonComment() == Token->MatchingParen)
225 ItemBegin = ItemEnd->Next;
228 // Don't use column layout for lists with few elements and in presence of
229 // separating comments.
230 if (Commas.size() < 5 || HasSeparatingComment)
233 if (Token->NestingLevel != 0 && Token->is(tok::l_brace) && Commas.size() < 19)
236 // We can never place more than ColumnLimit / 3 items in a row (because of the
237 // spaces and the comma).
238 unsigned MaxItems = Style.ColumnLimit / 3;
239 std::vector<unsigned> MinSizeInColumn;
240 MinSizeInColumn.reserve(MaxItems);
241 for (unsigned Columns = 1; Columns <= MaxItems; ++Columns) {
243 Format.Columns = Columns;
244 Format.ColumnSizes.resize(Columns);
245 MinSizeInColumn.assign(Columns, UINT_MAX);
246 Format.LineCount = 1;
247 bool HasRowWithSufficientColumns = false;
249 for (unsigned i = 0, e = ItemLengths.size(); i != e; ++i) {
250 assert(i < MustBreakBeforeItem.size());
251 if (MustBreakBeforeItem[i] || Column == Columns) {
255 if (Column == Columns - 1)
256 HasRowWithSufficientColumns = true;
258 (Column == Columns - 1) ? EndOfLineItemLength[i] : ItemLengths[i];
259 Format.ColumnSizes[Column] = std::max(Format.ColumnSizes[Column], Length);
260 MinSizeInColumn[Column] = std::min(MinSizeInColumn[Column], Length);
263 // If all rows are terminated early (e.g. by trailing comments), we don't
264 // need to look further.
265 if (!HasRowWithSufficientColumns)
267 Format.TotalWidth = Columns - 1; // Width of the N-1 spaces.
269 for (unsigned i = 0; i < Columns; ++i)
270 Format.TotalWidth += Format.ColumnSizes[i];
272 // Don't use this Format, if the difference between the longest and shortest
273 // element in a column exceeds a threshold to avoid excessive spaces.
275 for (unsigned i = 0; i < Columns - 1; ++i)
276 if (Format.ColumnSizes[i] - MinSizeInColumn[i] > 10)
282 // Ignore layouts that are bound to violate the column limit.
283 if (Format.TotalWidth > Style.ColumnLimit && Columns > 1)
286 Formats.push_back(Format);
290 const CommaSeparatedList::ColumnFormat *
291 CommaSeparatedList::getColumnFormat(unsigned RemainingCharacters) const {
292 const ColumnFormat *BestFormat = nullptr;
293 for (SmallVector<ColumnFormat, 4>::const_reverse_iterator
294 I = Formats.rbegin(),
297 if (I->TotalWidth <= RemainingCharacters || I->Columns == 1) {
298 if (BestFormat && I->LineCount > BestFormat->LineCount)
306 } // namespace format