blob: 63af0d6088d17fb175affa6c9de03f24b4234d4b [file] [log] [blame]
Daniel Jasper8de9ed02013-08-22 15:00:41 +00001//===--- 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
Daniel Jasper8de9ed02013-08-22 15:00:41 +000016#include "ContinuationIndenter.h"
Daniel Jasperd89ae9d2015-09-23 08:30:47 +000017#include "FormatToken.h"
Daniel Jasper8de9ed02013-08-22 15:00:41 +000018#include "clang/Format/Format.h"
19#include "llvm/ADT/SmallVector.h"
20#include "llvm/Support/Debug.h"
Daniel Jasperd9ff0352015-05-11 13:52:13 +000021#include <climits>
Daniel Jasper8de9ed02013-08-22 15:00:41 +000022
23namespace clang {
24namespace format {
25
Birunthan Mohanathas67d81c82015-07-13 16:19:34 +000026const char *getTokenTypeName(TokenType Type) {
27 static const char *const TokNames[] = {
28#define TYPE(X) #X,
29LIST_TOKEN_TYPES
30#undef TYPE
31 nullptr
32 };
33
34 if (Type < NUM_TOKEN_TYPES)
35 return TokNames[Type];
36 llvm_unreachable("unknown TokenType");
37 return nullptr;
38}
39
Daniel Jaspercb51cf42014-01-16 09:11:55 +000040// FIXME: This is copy&pasted from Sema. Put it in a common place and remove
41// duplication.
42bool FormatToken::isSimpleTypeSpecifier() const {
43 switch (Tok.getKind()) {
44 case tok::kw_short:
45 case tok::kw_long:
46 case tok::kw___int64:
47 case tok::kw___int128:
48 case tok::kw_signed:
49 case tok::kw_unsigned:
50 case tok::kw_void:
51 case tok::kw_char:
52 case tok::kw_int:
53 case tok::kw_half:
54 case tok::kw_float:
55 case tok::kw_double:
56 case tok::kw_wchar_t:
57 case tok::kw_bool:
58 case tok::kw___underlying_type:
59 case tok::annot_typename:
60 case tok::kw_char16_t:
61 case tok::kw_char32_t:
62 case tok::kw_typeof:
63 case tok::kw_decltype:
64 return true;
65 default:
66 return false;
67 }
68}
69
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +000070TokenRole::~TokenRole() {}
Daniel Jasper8de9ed02013-08-22 15:00:41 +000071
72void TokenRole::precomputeFormattingInfos(const FormatToken *Token) {}
73
Daniel Jasper01603472014-01-09 13:42:56 +000074unsigned CommaSeparatedList::formatAfterToken(LineState &State,
75 ContinuationIndenter *Indenter,
76 bool DryRun) {
Daniel Jasper60c27072015-05-13 08:16:00 +000077 if (State.NextToken == nullptr || !State.NextToken->Previous)
Daniel Jasper8de9ed02013-08-22 15:00:41 +000078 return 0;
79
80 // Ensure that we start on the opening brace.
Daniel Jasper60c27072015-05-13 08:16:00 +000081 const FormatToken *LBrace =
82 State.NextToken->Previous->getPreviousNonComment();
Daniel Jaspere2deb592015-12-22 15:48:15 +000083 if (!LBrace || !LBrace->isOneOf(tok::l_brace, TT_ArrayInitializerLSquare) ||
84 LBrace->BlockKind == BK_Block || LBrace->Type == TT_DictLiteral ||
Daniel Jasper8de9ed02013-08-22 15:00:41 +000085 LBrace->Next->Type == TT_DesignatedInitializerPeriod)
86 return 0;
87
Daniel Jaspercb3f0ed2013-08-27 08:43:47 +000088 // Calculate the number of code points we have to format this list. As the
89 // first token is already placed, we have to subtract it.
Daniel Jasperb05a81d2014-05-09 13:11:16 +000090 unsigned RemainingCodePoints =
91 Style.ColumnLimit - State.Column + State.NextToken->Previous->ColumnWidth;
Daniel Jaspercb3f0ed2013-08-27 08:43:47 +000092
Daniel Jasper8de9ed02013-08-22 15:00:41 +000093 // Find the best ColumnFormat, i.e. the best number of columns to use.
Daniel Jaspercb3f0ed2013-08-27 08:43:47 +000094 const ColumnFormat *Format = getColumnFormat(RemainingCodePoints);
Daniel Jasper1a1a2ab2013-11-23 10:22:59 +000095 // If no ColumnFormat can be used, the braced list would generally be
96 // bin-packed. Add a severe penalty to this so that column layouts are
Alp Tokerf6a24ce2013-12-05 16:25:25 +000097 // preferred if possible.
Daniel Jasper8de9ed02013-08-22 15:00:41 +000098 if (!Format)
Daniel Jasper1a1a2ab2013-11-23 10:22:59 +000099 return 10000;
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000100
101 // Format the entire list.
102 unsigned Penalty = 0;
103 unsigned Column = 0;
104 unsigned Item = 0;
105 while (State.NextToken != LBrace->MatchingParen) {
106 bool NewLine = false;
107 unsigned ExtraSpaces = 0;
108
109 // If the previous token was one of our commas, we are now on the next item.
110 if (Item < Commas.size() && State.NextToken->Previous == Commas[Item]) {
111 if (!State.NextToken->isTrailingComment()) {
112 ExtraSpaces += Format->ColumnSizes[Column] - ItemLengths[Item];
113 ++Column;
114 }
115 ++Item;
116 }
117
118 if (Column == Format->Columns || State.NextToken->MustBreakBefore) {
119 Column = 0;
120 NewLine = true;
121 }
122
123 // Place token using the continuation indenter and store the penalty.
124 Penalty += Indenter->addTokenToState(State, NewLine, DryRun, ExtraSpaces);
125 }
126 return Penalty;
127}
128
Daniel Jasper01603472014-01-09 13:42:56 +0000129unsigned CommaSeparatedList::formatFromToken(LineState &State,
130 ContinuationIndenter *Indenter,
131 bool DryRun) {
132 if (HasNestedBracedList)
133 State.Stack.back().AvoidBinPacking = true;
134 return 0;
135}
136
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000137// Returns the lengths in code points between Begin and End (both included),
138// assuming that the entire sequence is put on a single line.
139static unsigned CodePointsBetween(const FormatToken *Begin,
140 const FormatToken *End) {
Daniel Jasper8863ada2013-08-26 08:10:17 +0000141 assert(End->TotalLength >= Begin->TotalLength);
Alexander Kornienko39856b72013-09-10 09:38:25 +0000142 return End->TotalLength - Begin->TotalLength + Begin->ColumnWidth;
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000143}
144
145void CommaSeparatedList::precomputeFormattingInfos(const FormatToken *Token) {
Daniel Jasper8863ada2013-08-26 08:10:17 +0000146 // FIXME: At some point we might want to do this for other lists, too.
Daniel Jaspere2deb592015-12-22 15:48:15 +0000147 if (!Token->MatchingParen ||
148 !Token->isOneOf(tok::l_brace, TT_ArrayInitializerLSquare))
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000149 return;
150
Daniel Jasper839922e2014-08-13 08:46:21 +0000151 // In C++11 braced list style, we should not format in columns unless they
Daniel Jasper08434342015-05-26 07:26:26 +0000152 // have many items (20 or more) or we allow bin-packing of function call
153 // arguments.
154 if (Style.Cpp11BracedListStyle && !Style.BinPackArguments &&
Daniel Jasper839922e2014-08-13 08:46:21 +0000155 Commas.size() < 19)
Daniel Jasperae8e0d82014-04-17 11:32:02 +0000156 return;
157
Daniel Jaspere2deb592015-12-22 15:48:15 +0000158 // Limit column layout for JavaScript array initializers to 20 or more items
159 // for now to introduce it carefully. We can become more aggressive if this
160 // necessary.
161 if (Token->is(TT_ArrayInitializerLSquare) && Commas.size() < 19)
162 return;
163
Daniel Jasper13404da2014-11-27 14:40:48 +0000164 // Column format doesn't really make sense if we don't align after brackets.
Daniel Jasper6501f7e2015-10-27 12:38:37 +0000165 if (Style.AlignAfterOpenBracket == FormatStyle::BAS_DontAlign)
Daniel Jasper13404da2014-11-27 14:40:48 +0000166 return;
167
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000168 FormatToken *ItemBegin = Token->Next;
Daniel Jasper60c27072015-05-13 08:16:00 +0000169 while (ItemBegin->isTrailingComment())
170 ItemBegin = ItemBegin->Next;
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000171 SmallVector<bool, 8> MustBreakBeforeItem;
172
173 // The lengths of an item if it is put at the end of the line. This includes
174 // trailing comments which are otherwise ignored for column alignment.
175 SmallVector<unsigned, 8> EndOfLineItemLength;
176
Daniel Jasper731dde92015-05-15 09:41:59 +0000177 bool HasSeparatingComment = false;
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000178 for (unsigned i = 0, e = Commas.size() + 1; i != e; ++i) {
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000179 // Skip comments on their own line.
Daniel Jasper731dde92015-05-15 09:41:59 +0000180 while (ItemBegin->HasUnescapedNewline && ItemBegin->isTrailingComment()) {
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000181 ItemBegin = ItemBegin->Next;
Daniel Jasper731dde92015-05-15 09:41:59 +0000182 HasSeparatingComment = i > 0;
183 }
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000184
185 MustBreakBeforeItem.push_back(ItemBegin->MustBreakBefore);
Daniel Jasper7c72d9f2013-10-24 14:14:49 +0000186 if (ItemBegin->is(tok::l_brace))
187 HasNestedBracedList = true;
Craig Topper2145bc02014-05-09 08:15:10 +0000188 const FormatToken *ItemEnd = nullptr;
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000189 if (i == Commas.size()) {
190 ItemEnd = Token->MatchingParen;
191 const FormatToken *NonCommentEnd = ItemEnd->getPreviousNonComment();
192 ItemLengths.push_back(CodePointsBetween(ItemBegin, NonCommentEnd));
Daniel Jasper00fb2a12015-07-15 16:26:47 +0000193 if (Style.Cpp11BracedListStyle &&
194 !ItemEnd->Previous->isTrailingComment()) {
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000195 // In Cpp11 braced list style, the } and possibly other subsequent
196 // tokens will need to stay on a line with the last element.
197 while (ItemEnd->Next && !ItemEnd->Next->CanBreakBefore)
198 ItemEnd = ItemEnd->Next;
199 } else {
200 // In other braced lists styles, the "}" can be wrapped to the new line.
201 ItemEnd = Token->MatchingParen->Previous;
202 }
203 } else {
204 ItemEnd = Commas[i];
205 // The comma is counted as part of the item when calculating the length.
Daniel Jasper8863ada2013-08-26 08:10:17 +0000206 ItemLengths.push_back(CodePointsBetween(ItemBegin, ItemEnd));
Daniel Jasper540dbe22014-09-19 08:28:43 +0000207
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000208 // Consume trailing comments so the are included in EndOfLineItemLength.
209 if (ItemEnd->Next && !ItemEnd->Next->HasUnescapedNewline &&
210 ItemEnd->Next->isTrailingComment())
211 ItemEnd = ItemEnd->Next;
212 }
213 EndOfLineItemLength.push_back(CodePointsBetween(ItemBegin, ItemEnd));
Daniel Jasper8863ada2013-08-26 08:10:17 +0000214 // If there is a trailing comma in the list, the next item will start at the
215 // closing brace. Don't create an extra item for this.
216 if (ItemEnd->getNextNonComment() == Token->MatchingParen)
217 break;
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000218 ItemBegin = ItemEnd->Next;
219 }
220
Daniel Jasper731dde92015-05-15 09:41:59 +0000221 // Don't use column layout for nested lists, lists with few elements and in
222 // presence of separating comments.
Daniel Jaspere2deb592015-12-22 15:48:15 +0000223 if ((Token->NestingLevel != 0 && Token->is(tok::l_brace)) ||
224 Commas.size() < 5 || HasSeparatingComment)
Daniel Jasper01603472014-01-09 13:42:56 +0000225 return;
226
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000227 // We can never place more than ColumnLimit / 3 items in a row (because of the
228 // spaces and the comma).
Benjamin Kramer3aa55db2015-06-12 13:06:57 +0000229 unsigned MaxItems = Style.ColumnLimit / 3;
230 std::vector<unsigned> MinSizeInColumn;
231 MinSizeInColumn.reserve(MaxItems);
232 for (unsigned Columns = 1; Columns <= MaxItems; ++Columns) {
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000233 ColumnFormat Format;
234 Format.Columns = Columns;
235 Format.ColumnSizes.resize(Columns);
Benjamin Kramer3aa55db2015-06-12 13:06:57 +0000236 MinSizeInColumn.assign(Columns, UINT_MAX);
Daniel Jasper7c72d9f2013-10-24 14:14:49 +0000237 Format.LineCount = 1;
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000238 bool HasRowWithSufficientColumns = false;
239 unsigned Column = 0;
240 for (unsigned i = 0, e = ItemLengths.size(); i != e; ++i) {
Manuel Klimek71814b42013-10-11 21:25:45 +0000241 assert(i < MustBreakBeforeItem.size());
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000242 if (MustBreakBeforeItem[i] || Column == Columns) {
243 ++Format.LineCount;
244 Column = 0;
245 }
246 if (Column == Columns - 1)
247 HasRowWithSufficientColumns = true;
Daniel Jasperd57843d2015-05-11 13:35:40 +0000248 unsigned Length =
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000249 (Column == Columns - 1) ? EndOfLineItemLength[i] : ItemLengths[i];
Daniel Jasperd57843d2015-05-11 13:35:40 +0000250 Format.ColumnSizes[Column] = std::max(Format.ColumnSizes[Column], Length);
251 MinSizeInColumn[Column] = std::min(MinSizeInColumn[Column], Length);
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000252 ++Column;
253 }
254 // If all rows are terminated early (e.g. by trailing comments), we don't
255 // need to look further.
256 if (!HasRowWithSufficientColumns)
257 break;
258 Format.TotalWidth = Columns - 1; // Width of the N-1 spaces.
Daniel Jasperd57843d2015-05-11 13:35:40 +0000259
260 for (unsigned i = 0; i < Columns; ++i)
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000261 Format.TotalWidth += Format.ColumnSizes[i];
Daniel Jasperd57843d2015-05-11 13:35:40 +0000262
263 // Don't use this Format, if the difference between the longest and shortest
264 // element in a column exceeds a threshold to avoid excessive spaces.
265 if ([&] {
266 for (unsigned i = 0; i < Columns - 1; ++i)
267 if (Format.ColumnSizes[i] - MinSizeInColumn[i] > 10)
268 return true;
269 return false;
270 }())
271 continue;
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000272
273 // Ignore layouts that are bound to violate the column limit.
274 if (Format.TotalWidth > Style.ColumnLimit)
275 continue;
276
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000277 Formats.push_back(Format);
278 }
279}
280
281const CommaSeparatedList::ColumnFormat *
282CommaSeparatedList::getColumnFormat(unsigned RemainingCharacters) const {
Craig Topper2145bc02014-05-09 08:15:10 +0000283 const ColumnFormat *BestFormat = nullptr;
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000284 for (SmallVector<ColumnFormat, 4>::const_reverse_iterator
285 I = Formats.rbegin(),
286 E = Formats.rend();
287 I != E; ++I) {
288 if (I->TotalWidth <= RemainingCharacters) {
289 if (BestFormat && I->LineCount > BestFormat->LineCount)
290 break;
291 BestFormat = &*I;
292 }
293 }
294 return BestFormat;
295}
296
297} // namespace format
298} // namespace clang