blob: 2ae4ddcfd08a067e11b354036181dc1f107aa4ba [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:
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
81 // Ensure that we start on the opening brace.
Daniel Jasper60c27072015-05-13 08:16:00 +000082 const FormatToken *LBrace =
83 State.NextToken->Previous->getPreviousNonComment();
Daniel Jaspere2deb592015-12-22 15:48:15 +000084 if (!LBrace || !LBrace->isOneOf(tok::l_brace, TT_ArrayInitializerLSquare) ||
85 LBrace->BlockKind == BK_Block || LBrace->Type == TT_DictLiteral ||
Daniel Jasper8de9ed02013-08-22 15:00:41 +000086 LBrace->Next->Type == TT_DesignatedInitializerPeriod)
87 return 0;
88
Daniel Jaspercb3f0ed2013-08-27 08:43:47 +000089 // Calculate the number of code points we have to format this list. As the
90 // first token is already placed, we have to subtract it.
Daniel Jasperb05a81d2014-05-09 13:11:16 +000091 unsigned RemainingCodePoints =
92 Style.ColumnLimit - State.Column + State.NextToken->Previous->ColumnWidth;
Daniel Jaspercb3f0ed2013-08-27 08:43:47 +000093
Daniel Jasper8de9ed02013-08-22 15:00:41 +000094 // Find the best ColumnFormat, i.e. the best number of columns to use.
Daniel Jaspercb3f0ed2013-08-27 08:43:47 +000095 const ColumnFormat *Format = getColumnFormat(RemainingCodePoints);
Daniel Jasper1a1a2ab2013-11-23 10:22:59 +000096 // If no ColumnFormat can be used, the braced list would generally be
97 // bin-packed. Add a severe penalty to this so that column layouts are
Alp Tokerf6a24ce2013-12-05 16:25:25 +000098 // preferred if possible.
Daniel Jasper8de9ed02013-08-22 15:00:41 +000099 if (!Format)
Daniel Jasper1a1a2ab2013-11-23 10:22:59 +0000100 return 10000;
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000101
102 // Format the entire list.
103 unsigned Penalty = 0;
104 unsigned Column = 0;
105 unsigned Item = 0;
106 while (State.NextToken != LBrace->MatchingParen) {
107 bool NewLine = false;
108 unsigned ExtraSpaces = 0;
109
110 // If the previous token was one of our commas, we are now on the next item.
111 if (Item < Commas.size() && State.NextToken->Previous == Commas[Item]) {
112 if (!State.NextToken->isTrailingComment()) {
113 ExtraSpaces += Format->ColumnSizes[Column] - ItemLengths[Item];
114 ++Column;
115 }
116 ++Item;
117 }
118
119 if (Column == Format->Columns || State.NextToken->MustBreakBefore) {
120 Column = 0;
121 NewLine = true;
122 }
123
124 // Place token using the continuation indenter and store the penalty.
125 Penalty += Indenter->addTokenToState(State, NewLine, DryRun, ExtraSpaces);
126 }
127 return Penalty;
128}
129
Daniel Jasper01603472014-01-09 13:42:56 +0000130unsigned CommaSeparatedList::formatFromToken(LineState &State,
131 ContinuationIndenter *Indenter,
132 bool DryRun) {
133 if (HasNestedBracedList)
134 State.Stack.back().AvoidBinPacking = true;
135 return 0;
136}
137
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000138// Returns the lengths in code points between Begin and End (both included),
139// assuming that the entire sequence is put on a single line.
140static unsigned CodePointsBetween(const FormatToken *Begin,
141 const FormatToken *End) {
Daniel Jasper8863ada2013-08-26 08:10:17 +0000142 assert(End->TotalLength >= Begin->TotalLength);
Alexander Kornienko39856b72013-09-10 09:38:25 +0000143 return End->TotalLength - Begin->TotalLength + Begin->ColumnWidth;
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000144}
145
146void CommaSeparatedList::precomputeFormattingInfos(const FormatToken *Token) {
Daniel Jasper8863ada2013-08-26 08:10:17 +0000147 // FIXME: At some point we might want to do this for other lists, too.
Daniel Jaspere2deb592015-12-22 15:48:15 +0000148 if (!Token->MatchingParen ||
149 !Token->isOneOf(tok::l_brace, TT_ArrayInitializerLSquare))
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000150 return;
151
Daniel Jasper839922e2014-08-13 08:46:21 +0000152 // In C++11 braced list style, we should not format in columns unless they
Daniel Jasper08434342015-05-26 07:26:26 +0000153 // have many items (20 or more) or we allow bin-packing of function call
154 // arguments.
155 if (Style.Cpp11BracedListStyle && !Style.BinPackArguments &&
Daniel Jasper839922e2014-08-13 08:46:21 +0000156 Commas.size() < 19)
Daniel Jasperae8e0d82014-04-17 11:32:02 +0000157 return;
158
Daniel Jaspere2deb592015-12-22 15:48:15 +0000159 // Limit column layout for JavaScript array initializers to 20 or more items
160 // for now to introduce it carefully. We can become more aggressive if this
161 // necessary.
162 if (Token->is(TT_ArrayInitializerLSquare) && Commas.size() < 19)
163 return;
164
Daniel Jasper13404da2014-11-27 14:40:48 +0000165 // Column format doesn't really make sense if we don't align after brackets.
Daniel Jasper6501f7e2015-10-27 12:38:37 +0000166 if (Style.AlignAfterOpenBracket == FormatStyle::BAS_DontAlign)
Daniel Jasper13404da2014-11-27 14:40:48 +0000167 return;
168
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000169 FormatToken *ItemBegin = Token->Next;
Daniel Jasper60c27072015-05-13 08:16:00 +0000170 while (ItemBegin->isTrailingComment())
171 ItemBegin = ItemBegin->Next;
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000172 SmallVector<bool, 8> MustBreakBeforeItem;
173
174 // The lengths of an item if it is put at the end of the line. This includes
175 // trailing comments which are otherwise ignored for column alignment.
176 SmallVector<unsigned, 8> EndOfLineItemLength;
177
Daniel Jasper731dde92015-05-15 09:41:59 +0000178 bool HasSeparatingComment = false;
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000179 for (unsigned i = 0, e = Commas.size() + 1; i != e; ++i) {
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000180 // Skip comments on their own line.
Daniel Jasper731dde92015-05-15 09:41:59 +0000181 while (ItemBegin->HasUnescapedNewline && ItemBegin->isTrailingComment()) {
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000182 ItemBegin = ItemBegin->Next;
Daniel Jasper731dde92015-05-15 09:41:59 +0000183 HasSeparatingComment = i > 0;
184 }
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000185
186 MustBreakBeforeItem.push_back(ItemBegin->MustBreakBefore);
Daniel Jasper7c72d9f2013-10-24 14:14:49 +0000187 if (ItemBegin->is(tok::l_brace))
188 HasNestedBracedList = true;
Craig Topper2145bc02014-05-09 08:15:10 +0000189 const FormatToken *ItemEnd = nullptr;
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000190 if (i == Commas.size()) {
191 ItemEnd = Token->MatchingParen;
192 const FormatToken *NonCommentEnd = ItemEnd->getPreviousNonComment();
193 ItemLengths.push_back(CodePointsBetween(ItemBegin, NonCommentEnd));
Daniel Jasper00fb2a12015-07-15 16:26:47 +0000194 if (Style.Cpp11BracedListStyle &&
195 !ItemEnd->Previous->isTrailingComment()) {
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000196 // In Cpp11 braced list style, the } and possibly other subsequent
197 // tokens will need to stay on a line with the last element.
198 while (ItemEnd->Next && !ItemEnd->Next->CanBreakBefore)
199 ItemEnd = ItemEnd->Next;
200 } else {
201 // In other braced lists styles, the "}" can be wrapped to the new line.
202 ItemEnd = Token->MatchingParen->Previous;
203 }
204 } else {
205 ItemEnd = Commas[i];
206 // The comma is counted as part of the item when calculating the length.
Daniel Jasper8863ada2013-08-26 08:10:17 +0000207 ItemLengths.push_back(CodePointsBetween(ItemBegin, ItemEnd));
Daniel Jasper540dbe22014-09-19 08:28:43 +0000208
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000209 // Consume trailing comments so the are included in EndOfLineItemLength.
210 if (ItemEnd->Next && !ItemEnd->Next->HasUnescapedNewline &&
211 ItemEnd->Next->isTrailingComment())
212 ItemEnd = ItemEnd->Next;
213 }
214 EndOfLineItemLength.push_back(CodePointsBetween(ItemBegin, ItemEnd));
Daniel Jasper8863ada2013-08-26 08:10:17 +0000215 // If there is a trailing comma in the list, the next item will start at the
216 // closing brace. Don't create an extra item for this.
217 if (ItemEnd->getNextNonComment() == Token->MatchingParen)
218 break;
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000219 ItemBegin = ItemEnd->Next;
220 }
221
Daniel Jasper55582072016-01-04 07:30:44 +0000222 // Don't use column layout for lists with few elements and in presence of
223 // separating comments.
224 if (Commas.size() < 5 || HasSeparatingComment)
225 return;
226
227 if (Token->NestingLevel != 0 && Token->is(tok::l_brace) && Commas.size() < 19)
Daniel Jasper01603472014-01-09 13:42:56 +0000228 return;
229
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000230 // We can never place more than ColumnLimit / 3 items in a row (because of the
231 // spaces and the comma).
Benjamin Kramer3aa55db2015-06-12 13:06:57 +0000232 unsigned MaxItems = Style.ColumnLimit / 3;
233 std::vector<unsigned> MinSizeInColumn;
234 MinSizeInColumn.reserve(MaxItems);
235 for (unsigned Columns = 1; Columns <= MaxItems; ++Columns) {
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000236 ColumnFormat Format;
237 Format.Columns = Columns;
238 Format.ColumnSizes.resize(Columns);
Benjamin Kramer3aa55db2015-06-12 13:06:57 +0000239 MinSizeInColumn.assign(Columns, UINT_MAX);
Daniel Jasper7c72d9f2013-10-24 14:14:49 +0000240 Format.LineCount = 1;
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000241 bool HasRowWithSufficientColumns = false;
242 unsigned Column = 0;
243 for (unsigned i = 0, e = ItemLengths.size(); i != e; ++i) {
Manuel Klimek71814b42013-10-11 21:25:45 +0000244 assert(i < MustBreakBeforeItem.size());
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000245 if (MustBreakBeforeItem[i] || Column == Columns) {
246 ++Format.LineCount;
247 Column = 0;
248 }
249 if (Column == Columns - 1)
250 HasRowWithSufficientColumns = true;
Daniel Jasperd57843d2015-05-11 13:35:40 +0000251 unsigned Length =
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000252 (Column == Columns - 1) ? EndOfLineItemLength[i] : ItemLengths[i];
Daniel Jasperd57843d2015-05-11 13:35:40 +0000253 Format.ColumnSizes[Column] = std::max(Format.ColumnSizes[Column], Length);
254 MinSizeInColumn[Column] = std::min(MinSizeInColumn[Column], Length);
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000255 ++Column;
256 }
257 // If all rows are terminated early (e.g. by trailing comments), we don't
258 // need to look further.
259 if (!HasRowWithSufficientColumns)
260 break;
261 Format.TotalWidth = Columns - 1; // Width of the N-1 spaces.
Daniel Jasperd57843d2015-05-11 13:35:40 +0000262
263 for (unsigned i = 0; i < Columns; ++i)
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000264 Format.TotalWidth += Format.ColumnSizes[i];
Daniel Jasperd57843d2015-05-11 13:35:40 +0000265
266 // Don't use this Format, if the difference between the longest and shortest
267 // element in a column exceeds a threshold to avoid excessive spaces.
268 if ([&] {
269 for (unsigned i = 0; i < Columns - 1; ++i)
270 if (Format.ColumnSizes[i] - MinSizeInColumn[i] > 10)
271 return true;
272 return false;
273 }())
274 continue;
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000275
276 // Ignore layouts that are bound to violate the column limit.
277 if (Format.TotalWidth > Style.ColumnLimit)
278 continue;
279
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000280 Formats.push_back(Format);
281 }
282}
283
284const CommaSeparatedList::ColumnFormat *
285CommaSeparatedList::getColumnFormat(unsigned RemainingCharacters) const {
Craig Topper2145bc02014-05-09 08:15:10 +0000286 const ColumnFormat *BestFormat = nullptr;
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000287 for (SmallVector<ColumnFormat, 4>::const_reverse_iterator
288 I = Formats.rbegin(),
289 E = Formats.rend();
290 I != E; ++I) {
291 if (I->TotalWidth <= RemainingCharacters) {
292 if (BestFormat && I->LineCount > BestFormat->LineCount)
293 break;
294 BestFormat = &*I;
295 }
296 }
297 return BestFormat;
298}
299
300} // namespace format
301} // namespace clang