blob: d1f16eb1c3c1656a8ec86299ad2679943f4f92a2 [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 Jasperd89ae9d2015-09-23 08:30:47 +000016#include "FormatToken.h"
Mehdi Amini9670f842016-07-18 19:02:11 +000017#include "ContinuationIndenter.h"
Daniel Jasper8de9ed02013-08-22 15:00:41 +000018#include "llvm/ADT/SmallVector.h"
19#include "llvm/Support/Debug.h"
Daniel Jasperd9ff0352015-05-11 13:52:13 +000020#include <climits>
Daniel Jasper8de9ed02013-08-22 15:00:41 +000021
22namespace clang {
23namespace format {
24
Birunthan Mohanathas67d81c82015-07-13 16:19:34 +000025const char *getTokenTypeName(TokenType Type) {
26 static const char *const TokNames[] = {
27#define TYPE(X) #X,
28LIST_TOKEN_TYPES
29#undef TYPE
30 nullptr
31 };
32
33 if (Type < NUM_TOKEN_TYPES)
34 return TokNames[Type];
35 llvm_unreachable("unknown TokenType");
36 return nullptr;
37}
38
Daniel Jaspercb51cf42014-01-16 09:11:55 +000039// FIXME: This is copy&pasted from Sema. Put it in a common place and remove
40// duplication.
41bool FormatToken::isSimpleTypeSpecifier() const {
42 switch (Tok.getKind()) {
43 case tok::kw_short:
44 case tok::kw_long:
45 case tok::kw___int64:
46 case tok::kw___int128:
47 case tok::kw_signed:
48 case tok::kw_unsigned:
49 case tok::kw_void:
50 case tok::kw_char:
51 case tok::kw_int:
52 case tok::kw_half:
53 case tok::kw_float:
54 case tok::kw_double:
Sjoerd Meijercc623ad2017-09-08 15:15:00 +000055 case tok::kw__Float16:
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +000056 case tok::kw___float128:
Daniel Jaspercb51cf42014-01-16 09:11:55 +000057 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_char16_t:
62 case tok::kw_char32_t:
63 case tok::kw_typeof:
64 case tok::kw_decltype:
65 return true;
66 default:
67 return false;
68 }
69}
70
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +000071TokenRole::~TokenRole() {}
Daniel Jasper8de9ed02013-08-22 15:00:41 +000072
73void TokenRole::precomputeFormattingInfos(const FormatToken *Token) {}
74
Daniel Jasper01603472014-01-09 13:42:56 +000075unsigned CommaSeparatedList::formatAfterToken(LineState &State,
76 ContinuationIndenter *Indenter,
77 bool DryRun) {
Daniel Jasper60c27072015-05-13 08:16:00 +000078 if (State.NextToken == nullptr || !State.NextToken->Previous)
Daniel Jasper8de9ed02013-08-22 15:00:41 +000079 return 0;
80
Daniel Jasper083d1702016-12-21 17:02:06 +000081 if (Formats.size() == 1)
82 return 0; // Handled by formatFromToken
83
Daniel Jasper8de9ed02013-08-22 15:00:41 +000084 // Ensure that we start on the opening brace.
Daniel Jasper60c27072015-05-13 08:16:00 +000085 const FormatToken *LBrace =
86 State.NextToken->Previous->getPreviousNonComment();
Daniel Jaspere2deb592015-12-22 15:48:15 +000087 if (!LBrace || !LBrace->isOneOf(tok::l_brace, TT_ArrayInitializerLSquare) ||
88 LBrace->BlockKind == BK_Block || LBrace->Type == TT_DictLiteral ||
Daniel Jasper8de9ed02013-08-22 15:00:41 +000089 LBrace->Next->Type == TT_DesignatedInitializerPeriod)
90 return 0;
91
Daniel Jaspercb3f0ed2013-08-27 08:43:47 +000092 // 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.
Daniel Jasperb05a81d2014-05-09 13:11:16 +000094 unsigned RemainingCodePoints =
95 Style.ColumnLimit - State.Column + State.NextToken->Previous->ColumnWidth;
Daniel Jaspercb3f0ed2013-08-27 08:43:47 +000096
Daniel Jasper8de9ed02013-08-22 15:00:41 +000097 // Find the best ColumnFormat, i.e. the best number of columns to use.
Daniel Jaspercb3f0ed2013-08-27 08:43:47 +000098 const ColumnFormat *Format = getColumnFormat(RemainingCodePoints);
Daniel Jasperff8d61362016-12-19 08:40:56 +000099
Daniel Jasper1a1a2ab2013-11-23 10:22:59 +0000100 // 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
Alp Tokerf6a24ce2013-12-05 16:25:25 +0000102 // preferred if possible.
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000103 if (!Format)
Daniel Jasper1a1a2ab2013-11-23 10:22:59 +0000104 return 10000;
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000105
106 // Format the entire list.
107 unsigned Penalty = 0;
108 unsigned Column = 0;
109 unsigned Item = 0;
110 while (State.NextToken != LBrace->MatchingParen) {
111 bool NewLine = false;
112 unsigned ExtraSpaces = 0;
113
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];
118 ++Column;
119 }
120 ++Item;
121 }
122
123 if (Column == Format->Columns || State.NextToken->MustBreakBefore) {
124 Column = 0;
125 NewLine = true;
126 }
127
128 // Place token using the continuation indenter and store the penalty.
129 Penalty += Indenter->addTokenToState(State, NewLine, DryRun, ExtraSpaces);
130 }
131 return Penalty;
132}
133
Daniel Jasper01603472014-01-09 13:42:56 +0000134unsigned CommaSeparatedList::formatFromToken(LineState &State,
135 ContinuationIndenter *Indenter,
136 bool DryRun) {
Daniel Jasper083d1702016-12-21 17:02:06 +0000137 // 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)
Daniel Jasper01603472014-01-09 13:42:56 +0000140 State.Stack.back().AvoidBinPacking = true;
141 return 0;
142}
143
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000144// Returns the lengths in code points between Begin and End (both included),
145// assuming that the entire sequence is put on a single line.
146static unsigned CodePointsBetween(const FormatToken *Begin,
147 const FormatToken *End) {
Daniel Jasper8863ada2013-08-26 08:10:17 +0000148 assert(End->TotalLength >= Begin->TotalLength);
Alexander Kornienko39856b72013-09-10 09:38:25 +0000149 return End->TotalLength - Begin->TotalLength + Begin->ColumnWidth;
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000150}
151
152void CommaSeparatedList::precomputeFormattingInfos(const FormatToken *Token) {
Daniel Jasper8863ada2013-08-26 08:10:17 +0000153 // FIXME: At some point we might want to do this for other lists, too.
Daniel Jaspere2deb592015-12-22 15:48:15 +0000154 if (!Token->MatchingParen ||
155 !Token->isOneOf(tok::l_brace, TT_ArrayInitializerLSquare))
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000156 return;
157
Daniel Jasper839922e2014-08-13 08:46:21 +0000158 // In C++11 braced list style, we should not format in columns unless they
Daniel Jasper08434342015-05-26 07:26:26 +0000159 // have many items (20 or more) or we allow bin-packing of function call
160 // arguments.
161 if (Style.Cpp11BracedListStyle && !Style.BinPackArguments &&
Daniel Jasper839922e2014-08-13 08:46:21 +0000162 Commas.size() < 19)
Daniel Jasperae8e0d82014-04-17 11:32:02 +0000163 return;
164
Daniel Jaspere2deb592015-12-22 15:48:15 +0000165 // 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
167 // necessary.
168 if (Token->is(TT_ArrayInitializerLSquare) && Commas.size() < 19)
169 return;
170
Daniel Jasper13404da2014-11-27 14:40:48 +0000171 // Column format doesn't really make sense if we don't align after brackets.
Daniel Jasper6501f7e2015-10-27 12:38:37 +0000172 if (Style.AlignAfterOpenBracket == FormatStyle::BAS_DontAlign)
Daniel Jasper13404da2014-11-27 14:40:48 +0000173 return;
174
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000175 FormatToken *ItemBegin = Token->Next;
Daniel Jasper60c27072015-05-13 08:16:00 +0000176 while (ItemBegin->isTrailingComment())
177 ItemBegin = ItemBegin->Next;
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000178 SmallVector<bool, 8> MustBreakBeforeItem;
179
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;
183
Daniel Jasper731dde92015-05-15 09:41:59 +0000184 bool HasSeparatingComment = false;
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000185 for (unsigned i = 0, e = Commas.size() + 1; i != e; ++i) {
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000186 // Skip comments on their own line.
Daniel Jasper731dde92015-05-15 09:41:59 +0000187 while (ItemBegin->HasUnescapedNewline && ItemBegin->isTrailingComment()) {
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000188 ItemBegin = ItemBegin->Next;
Daniel Jasper731dde92015-05-15 09:41:59 +0000189 HasSeparatingComment = i > 0;
190 }
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000191
192 MustBreakBeforeItem.push_back(ItemBegin->MustBreakBefore);
Daniel Jasper7c72d9f2013-10-24 14:14:49 +0000193 if (ItemBegin->is(tok::l_brace))
194 HasNestedBracedList = true;
Craig Topper2145bc02014-05-09 08:15:10 +0000195 const FormatToken *ItemEnd = nullptr;
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000196 if (i == Commas.size()) {
197 ItemEnd = Token->MatchingParen;
198 const FormatToken *NonCommentEnd = ItemEnd->getPreviousNonComment();
199 ItemLengths.push_back(CodePointsBetween(ItemBegin, NonCommentEnd));
Daniel Jasper00fb2a12015-07-15 16:26:47 +0000200 if (Style.Cpp11BracedListStyle &&
201 !ItemEnd->Previous->isTrailingComment()) {
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000202 // 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;
206 } else {
207 // In other braced lists styles, the "}" can be wrapped to the new line.
208 ItemEnd = Token->MatchingParen->Previous;
209 }
210 } else {
211 ItemEnd = Commas[i];
212 // The comma is counted as part of the item when calculating the length.
Daniel Jasper8863ada2013-08-26 08:10:17 +0000213 ItemLengths.push_back(CodePointsBetween(ItemBegin, ItemEnd));
Daniel Jasper540dbe22014-09-19 08:28:43 +0000214
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000215 // Consume trailing comments so the are included in EndOfLineItemLength.
216 if (ItemEnd->Next && !ItemEnd->Next->HasUnescapedNewline &&
217 ItemEnd->Next->isTrailingComment())
218 ItemEnd = ItemEnd->Next;
219 }
220 EndOfLineItemLength.push_back(CodePointsBetween(ItemBegin, ItemEnd));
Daniel Jasper8863ada2013-08-26 08:10:17 +0000221 // 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)
224 break;
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000225 ItemBegin = ItemEnd->Next;
226 }
227
Daniel Jasper55582072016-01-04 07:30:44 +0000228 // Don't use column layout for lists with few elements and in presence of
229 // separating comments.
230 if (Commas.size() < 5 || HasSeparatingComment)
231 return;
232
233 if (Token->NestingLevel != 0 && Token->is(tok::l_brace) && Commas.size() < 19)
Daniel Jasper01603472014-01-09 13:42:56 +0000234 return;
235
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000236 // We can never place more than ColumnLimit / 3 items in a row (because of the
237 // spaces and the comma).
Benjamin Kramer3aa55db2015-06-12 13:06:57 +0000238 unsigned MaxItems = Style.ColumnLimit / 3;
239 std::vector<unsigned> MinSizeInColumn;
240 MinSizeInColumn.reserve(MaxItems);
241 for (unsigned Columns = 1; Columns <= MaxItems; ++Columns) {
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000242 ColumnFormat Format;
243 Format.Columns = Columns;
244 Format.ColumnSizes.resize(Columns);
Benjamin Kramer3aa55db2015-06-12 13:06:57 +0000245 MinSizeInColumn.assign(Columns, UINT_MAX);
Daniel Jasper7c72d9f2013-10-24 14:14:49 +0000246 Format.LineCount = 1;
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000247 bool HasRowWithSufficientColumns = false;
248 unsigned Column = 0;
249 for (unsigned i = 0, e = ItemLengths.size(); i != e; ++i) {
Manuel Klimek71814b42013-10-11 21:25:45 +0000250 assert(i < MustBreakBeforeItem.size());
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000251 if (MustBreakBeforeItem[i] || Column == Columns) {
252 ++Format.LineCount;
253 Column = 0;
254 }
255 if (Column == Columns - 1)
256 HasRowWithSufficientColumns = true;
Daniel Jasperd57843d2015-05-11 13:35:40 +0000257 unsigned Length =
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000258 (Column == Columns - 1) ? EndOfLineItemLength[i] : ItemLengths[i];
Daniel Jasperd57843d2015-05-11 13:35:40 +0000259 Format.ColumnSizes[Column] = std::max(Format.ColumnSizes[Column], Length);
260 MinSizeInColumn[Column] = std::min(MinSizeInColumn[Column], Length);
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000261 ++Column;
262 }
263 // If all rows are terminated early (e.g. by trailing comments), we don't
264 // need to look further.
265 if (!HasRowWithSufficientColumns)
266 break;
267 Format.TotalWidth = Columns - 1; // Width of the N-1 spaces.
Daniel Jasperd57843d2015-05-11 13:35:40 +0000268
269 for (unsigned i = 0; i < Columns; ++i)
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000270 Format.TotalWidth += Format.ColumnSizes[i];
Daniel Jasperd57843d2015-05-11 13:35:40 +0000271
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.
274 if ([&] {
275 for (unsigned i = 0; i < Columns - 1; ++i)
276 if (Format.ColumnSizes[i] - MinSizeInColumn[i] > 10)
277 return true;
278 return false;
279 }())
280 continue;
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000281
282 // Ignore layouts that are bound to violate the column limit.
Daniel Jaspere6169662016-12-19 07:26:11 +0000283 if (Format.TotalWidth > Style.ColumnLimit && Columns > 1)
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000284 continue;
285
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000286 Formats.push_back(Format);
287 }
288}
289
290const CommaSeparatedList::ColumnFormat *
291CommaSeparatedList::getColumnFormat(unsigned RemainingCharacters) const {
Craig Topper2145bc02014-05-09 08:15:10 +0000292 const ColumnFormat *BestFormat = nullptr;
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000293 for (SmallVector<ColumnFormat, 4>::const_reverse_iterator
294 I = Formats.rbegin(),
295 E = Formats.rend();
296 I != E; ++I) {
Daniel Jaspere6169662016-12-19 07:26:11 +0000297 if (I->TotalWidth <= RemainingCharacters || I->Columns == 1) {
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000298 if (BestFormat && I->LineCount > BestFormat->LineCount)
299 break;
300 BestFormat = &*I;
301 }
302 }
303 return BestFormat;
304}
305
306} // namespace format
307} // namespace clang