blob: bbc0fa8b0b8c6f6ccedd7ca3b16e52e4478e3016 [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
16#include "FormatToken.h"
17#include "ContinuationIndenter.h"
18#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
Daniel Jaspercb51cf42014-01-16 09:11:55 +000026// FIXME: This is copy&pasted from Sema. Put it in a common place and remove
27// duplication.
28bool FormatToken::isSimpleTypeSpecifier() const {
29 switch (Tok.getKind()) {
30 case tok::kw_short:
31 case tok::kw_long:
32 case tok::kw___int64:
33 case tok::kw___int128:
34 case tok::kw_signed:
35 case tok::kw_unsigned:
36 case tok::kw_void:
37 case tok::kw_char:
38 case tok::kw_int:
39 case tok::kw_half:
40 case tok::kw_float:
41 case tok::kw_double:
42 case tok::kw_wchar_t:
43 case tok::kw_bool:
44 case tok::kw___underlying_type:
45 case tok::annot_typename:
46 case tok::kw_char16_t:
47 case tok::kw_char32_t:
48 case tok::kw_typeof:
49 case tok::kw_decltype:
50 return true;
51 default:
52 return false;
53 }
54}
55
Daniel Jasper8de9ed02013-08-22 15:00:41 +000056TokenRole::~TokenRole() {}
57
58void TokenRole::precomputeFormattingInfos(const FormatToken *Token) {}
59
Daniel Jasper01603472014-01-09 13:42:56 +000060unsigned CommaSeparatedList::formatAfterToken(LineState &State,
61 ContinuationIndenter *Indenter,
62 bool DryRun) {
Daniel Jasper20e8c3b2015-01-19 10:51:42 +000063 if (State.NextToken == nullptr || !State.NextToken->Previous ||
64 !State.NextToken->Previous->Previous)
Daniel Jasper8de9ed02013-08-22 15:00:41 +000065 return 0;
66
67 // Ensure that we start on the opening brace.
68 const FormatToken *LBrace = State.NextToken->Previous->Previous;
Daniel Jasperb05a81d2014-05-09 13:11:16 +000069 if (LBrace->isNot(tok::l_brace) || LBrace->BlockKind == BK_Block ||
Daniel Jasperb596fb22013-10-24 10:31:50 +000070 LBrace->Type == TT_DictLiteral ||
Daniel Jasper8de9ed02013-08-22 15:00:41 +000071 LBrace->Next->Type == TT_DesignatedInitializerPeriod)
72 return 0;
73
Daniel Jaspercb3f0ed2013-08-27 08:43:47 +000074 // Calculate the number of code points we have to format this list. As the
75 // first token is already placed, we have to subtract it.
Daniel Jasperb05a81d2014-05-09 13:11:16 +000076 unsigned RemainingCodePoints =
77 Style.ColumnLimit - State.Column + State.NextToken->Previous->ColumnWidth;
Daniel Jaspercb3f0ed2013-08-27 08:43:47 +000078
Daniel Jasper8de9ed02013-08-22 15:00:41 +000079 // Find the best ColumnFormat, i.e. the best number of columns to use.
Daniel Jaspercb3f0ed2013-08-27 08:43:47 +000080 const ColumnFormat *Format = getColumnFormat(RemainingCodePoints);
Daniel Jasper1a1a2ab2013-11-23 10:22:59 +000081 // If no ColumnFormat can be used, the braced list would generally be
82 // bin-packed. Add a severe penalty to this so that column layouts are
Alp Tokerf6a24ce2013-12-05 16:25:25 +000083 // preferred if possible.
Daniel Jasper8de9ed02013-08-22 15:00:41 +000084 if (!Format)
Daniel Jasper1a1a2ab2013-11-23 10:22:59 +000085 return 10000;
Daniel Jasper8de9ed02013-08-22 15:00:41 +000086
87 // Format the entire list.
88 unsigned Penalty = 0;
89 unsigned Column = 0;
90 unsigned Item = 0;
91 while (State.NextToken != LBrace->MatchingParen) {
92 bool NewLine = false;
93 unsigned ExtraSpaces = 0;
94
95 // If the previous token was one of our commas, we are now on the next item.
96 if (Item < Commas.size() && State.NextToken->Previous == Commas[Item]) {
97 if (!State.NextToken->isTrailingComment()) {
98 ExtraSpaces += Format->ColumnSizes[Column] - ItemLengths[Item];
99 ++Column;
100 }
101 ++Item;
102 }
103
104 if (Column == Format->Columns || State.NextToken->MustBreakBefore) {
105 Column = 0;
106 NewLine = true;
107 }
108
109 // Place token using the continuation indenter and store the penalty.
110 Penalty += Indenter->addTokenToState(State, NewLine, DryRun, ExtraSpaces);
111 }
112 return Penalty;
113}
114
Daniel Jasper01603472014-01-09 13:42:56 +0000115unsigned CommaSeparatedList::formatFromToken(LineState &State,
116 ContinuationIndenter *Indenter,
117 bool DryRun) {
118 if (HasNestedBracedList)
119 State.Stack.back().AvoidBinPacking = true;
120 return 0;
121}
122
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000123// Returns the lengths in code points between Begin and End (both included),
124// assuming that the entire sequence is put on a single line.
125static unsigned CodePointsBetween(const FormatToken *Begin,
126 const FormatToken *End) {
Daniel Jasper8863ada2013-08-26 08:10:17 +0000127 assert(End->TotalLength >= Begin->TotalLength);
Alexander Kornienko39856b72013-09-10 09:38:25 +0000128 return End->TotalLength - Begin->TotalLength + Begin->ColumnWidth;
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000129}
130
131void CommaSeparatedList::precomputeFormattingInfos(const FormatToken *Token) {
Daniel Jasper8863ada2013-08-26 08:10:17 +0000132 // FIXME: At some point we might want to do this for other lists, too.
Daniel Jasper01603472014-01-09 13:42:56 +0000133 if (!Token->MatchingParen || Token->isNot(tok::l_brace))
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000134 return;
135
Daniel Jasper839922e2014-08-13 08:46:21 +0000136 // In C++11 braced list style, we should not format in columns unless they
137 // have many items (20 or more) or we allow bin-packing of function
138 // parameters.
139 if (Style.Cpp11BracedListStyle && !Style.BinPackParameters &&
140 Commas.size() < 19)
Daniel Jasperae8e0d82014-04-17 11:32:02 +0000141 return;
142
Daniel Jasper13404da2014-11-27 14:40:48 +0000143 // Column format doesn't really make sense if we don't align after brackets.
144 if (!Style.AlignAfterOpenBracket)
145 return;
146
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000147 FormatToken *ItemBegin = Token->Next;
148 SmallVector<bool, 8> MustBreakBeforeItem;
149
150 // The lengths of an item if it is put at the end of the line. This includes
151 // trailing comments which are otherwise ignored for column alignment.
152 SmallVector<unsigned, 8> EndOfLineItemLength;
153
154 for (unsigned i = 0, e = Commas.size() + 1; i != e; ++i) {
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000155 // Skip comments on their own line.
156 while (ItemBegin->HasUnescapedNewline && ItemBegin->isTrailingComment())
157 ItemBegin = ItemBegin->Next;
158
159 MustBreakBeforeItem.push_back(ItemBegin->MustBreakBefore);
Daniel Jasper7c72d9f2013-10-24 14:14:49 +0000160 if (ItemBegin->is(tok::l_brace))
161 HasNestedBracedList = true;
Craig Topper2145bc02014-05-09 08:15:10 +0000162 const FormatToken *ItemEnd = nullptr;
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000163 if (i == Commas.size()) {
164 ItemEnd = Token->MatchingParen;
165 const FormatToken *NonCommentEnd = ItemEnd->getPreviousNonComment();
166 ItemLengths.push_back(CodePointsBetween(ItemBegin, NonCommentEnd));
167 if (Style.Cpp11BracedListStyle) {
168 // In Cpp11 braced list style, the } and possibly other subsequent
169 // tokens will need to stay on a line with the last element.
170 while (ItemEnd->Next && !ItemEnd->Next->CanBreakBefore)
171 ItemEnd = ItemEnd->Next;
172 } else {
173 // In other braced lists styles, the "}" can be wrapped to the new line.
174 ItemEnd = Token->MatchingParen->Previous;
175 }
176 } else {
177 ItemEnd = Commas[i];
178 // The comma is counted as part of the item when calculating the length.
Daniel Jasper8863ada2013-08-26 08:10:17 +0000179 ItemLengths.push_back(CodePointsBetween(ItemBegin, ItemEnd));
Daniel Jasper540dbe22014-09-19 08:28:43 +0000180
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000181 // Consume trailing comments so the are included in EndOfLineItemLength.
182 if (ItemEnd->Next && !ItemEnd->Next->HasUnescapedNewline &&
183 ItemEnd->Next->isTrailingComment())
184 ItemEnd = ItemEnd->Next;
185 }
186 EndOfLineItemLength.push_back(CodePointsBetween(ItemBegin, ItemEnd));
Daniel Jasper8863ada2013-08-26 08:10:17 +0000187 // If there is a trailing comma in the list, the next item will start at the
188 // closing brace. Don't create an extra item for this.
189 if (ItemEnd->getNextNonComment() == Token->MatchingParen)
190 break;
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000191 ItemBegin = ItemEnd->Next;
192 }
193
Daniel Jasper01603472014-01-09 13:42:56 +0000194 // If this doesn't have a nested list, we require at least 6 elements in order
195 // create a column layout. If it has a nested list, column layout ensures one
Daniel Jasperd57843d2015-05-11 13:35:40 +0000196 // list element per line.
Daniel Jaspere4c16c72015-05-08 13:51:14 +0000197 if (Commas.size() < 5 || Token->NestingLevel != 0)
Daniel Jasper01603472014-01-09 13:42:56 +0000198 return;
199
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000200 // We can never place more than ColumnLimit / 3 items in a row (because of the
201 // spaces and the comma).
Daniel Jasperd57843d2015-05-11 13:35:40 +0000202 for (unsigned Columns = 1; Columns <= Style.ColumnLimit / 3; ++Columns) {
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000203 ColumnFormat Format;
204 Format.Columns = Columns;
205 Format.ColumnSizes.resize(Columns);
Daniel Jasperd57843d2015-05-11 13:35:40 +0000206 std::vector<unsigned> MinSizeInColumn(Columns, UINT_MAX);
Daniel Jasper7c72d9f2013-10-24 14:14:49 +0000207 Format.LineCount = 1;
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000208 bool HasRowWithSufficientColumns = false;
209 unsigned Column = 0;
210 for (unsigned i = 0, e = ItemLengths.size(); i != e; ++i) {
Manuel Klimek71814b42013-10-11 21:25:45 +0000211 assert(i < MustBreakBeforeItem.size());
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000212 if (MustBreakBeforeItem[i] || Column == Columns) {
213 ++Format.LineCount;
214 Column = 0;
215 }
216 if (Column == Columns - 1)
217 HasRowWithSufficientColumns = true;
Daniel Jasperd57843d2015-05-11 13:35:40 +0000218 unsigned Length =
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000219 (Column == Columns - 1) ? EndOfLineItemLength[i] : ItemLengths[i];
Daniel Jasperd57843d2015-05-11 13:35:40 +0000220 Format.ColumnSizes[Column] = std::max(Format.ColumnSizes[Column], Length);
221 MinSizeInColumn[Column] = std::min(MinSizeInColumn[Column], Length);
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000222 ++Column;
223 }
224 // If all rows are terminated early (e.g. by trailing comments), we don't
225 // need to look further.
226 if (!HasRowWithSufficientColumns)
227 break;
228 Format.TotalWidth = Columns - 1; // Width of the N-1 spaces.
Daniel Jasperd57843d2015-05-11 13:35:40 +0000229
230 for (unsigned i = 0; i < Columns; ++i)
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000231 Format.TotalWidth += Format.ColumnSizes[i];
Daniel Jasperd57843d2015-05-11 13:35:40 +0000232
233 // Don't use this Format, if the difference between the longest and shortest
234 // element in a column exceeds a threshold to avoid excessive spaces.
235 if ([&] {
236 for (unsigned i = 0; i < Columns - 1; ++i)
237 if (Format.ColumnSizes[i] - MinSizeInColumn[i] > 10)
238 return true;
239 return false;
240 }())
241 continue;
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000242
243 // Ignore layouts that are bound to violate the column limit.
244 if (Format.TotalWidth > Style.ColumnLimit)
245 continue;
246
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000247 Formats.push_back(Format);
248 }
249}
250
251const CommaSeparatedList::ColumnFormat *
252CommaSeparatedList::getColumnFormat(unsigned RemainingCharacters) const {
Craig Topper2145bc02014-05-09 08:15:10 +0000253 const ColumnFormat *BestFormat = nullptr;
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000254 for (SmallVector<ColumnFormat, 4>::const_reverse_iterator
255 I = Formats.rbegin(),
256 E = Formats.rend();
257 I != E; ++I) {
258 if (I->TotalWidth <= RemainingCharacters) {
259 if (BestFormat && I->LineCount > BestFormat->LineCount)
260 break;
261 BestFormat = &*I;
262 }
263 }
264 return BestFormat;
265}
266
267} // namespace format
268} // namespace clang