blob: b565ee1f200e0cd30fd3ba5a7ecf6275bb83c8ce [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"
21
22namespace clang {
23namespace format {
24
Daniel Jaspercb51cf42014-01-16 09:11:55 +000025// FIXME: This is copy&pasted from Sema. Put it in a common place and remove
26// duplication.
27bool FormatToken::isSimpleTypeSpecifier() const {
28 switch (Tok.getKind()) {
29 case tok::kw_short:
30 case tok::kw_long:
31 case tok::kw___int64:
32 case tok::kw___int128:
33 case tok::kw_signed:
34 case tok::kw_unsigned:
35 case tok::kw_void:
36 case tok::kw_char:
37 case tok::kw_int:
38 case tok::kw_half:
39 case tok::kw_float:
40 case tok::kw_double:
41 case tok::kw_wchar_t:
42 case tok::kw_bool:
43 case tok::kw___underlying_type:
44 case tok::annot_typename:
45 case tok::kw_char16_t:
46 case tok::kw_char32_t:
47 case tok::kw_typeof:
48 case tok::kw_decltype:
49 return true;
50 default:
51 return false;
52 }
53}
54
Daniel Jasper8de9ed02013-08-22 15:00:41 +000055TokenRole::~TokenRole() {}
56
57void TokenRole::precomputeFormattingInfos(const FormatToken *Token) {}
58
Daniel Jasper01603472014-01-09 13:42:56 +000059unsigned CommaSeparatedList::formatAfterToken(LineState &State,
60 ContinuationIndenter *Indenter,
61 bool DryRun) {
Daniel Jasper20e8c3b2015-01-19 10:51:42 +000062 if (State.NextToken == nullptr || !State.NextToken->Previous ||
63 !State.NextToken->Previous->Previous)
Daniel Jasper8de9ed02013-08-22 15:00:41 +000064 return 0;
65
66 // Ensure that we start on the opening brace.
67 const FormatToken *LBrace = State.NextToken->Previous->Previous;
Daniel Jasperb05a81d2014-05-09 13:11:16 +000068 if (LBrace->isNot(tok::l_brace) || LBrace->BlockKind == BK_Block ||
Daniel Jasperb596fb22013-10-24 10:31:50 +000069 LBrace->Type == TT_DictLiteral ||
Daniel Jasper8de9ed02013-08-22 15:00:41 +000070 LBrace->Next->Type == TT_DesignatedInitializerPeriod)
71 return 0;
72
Daniel Jaspercb3f0ed2013-08-27 08:43:47 +000073 // Calculate the number of code points we have to format this list. As the
74 // first token is already placed, we have to subtract it.
Daniel Jasperb05a81d2014-05-09 13:11:16 +000075 unsigned RemainingCodePoints =
76 Style.ColumnLimit - State.Column + State.NextToken->Previous->ColumnWidth;
Daniel Jaspercb3f0ed2013-08-27 08:43:47 +000077
Daniel Jasper8de9ed02013-08-22 15:00:41 +000078 // Find the best ColumnFormat, i.e. the best number of columns to use.
Daniel Jaspercb3f0ed2013-08-27 08:43:47 +000079 const ColumnFormat *Format = getColumnFormat(RemainingCodePoints);
Daniel Jasper1a1a2ab2013-11-23 10:22:59 +000080 // If no ColumnFormat can be used, the braced list would generally be
81 // bin-packed. Add a severe penalty to this so that column layouts are
Alp Tokerf6a24ce2013-12-05 16:25:25 +000082 // preferred if possible.
Daniel Jasper8de9ed02013-08-22 15:00:41 +000083 if (!Format)
Daniel Jasper1a1a2ab2013-11-23 10:22:59 +000084 return 10000;
Daniel Jasper8de9ed02013-08-22 15:00:41 +000085
86 // Format the entire list.
87 unsigned Penalty = 0;
88 unsigned Column = 0;
89 unsigned Item = 0;
90 while (State.NextToken != LBrace->MatchingParen) {
91 bool NewLine = false;
92 unsigned ExtraSpaces = 0;
93
94 // If the previous token was one of our commas, we are now on the next item.
95 if (Item < Commas.size() && State.NextToken->Previous == Commas[Item]) {
96 if (!State.NextToken->isTrailingComment()) {
97 ExtraSpaces += Format->ColumnSizes[Column] - ItemLengths[Item];
98 ++Column;
99 }
100 ++Item;
101 }
102
103 if (Column == Format->Columns || State.NextToken->MustBreakBefore) {
104 Column = 0;
105 NewLine = true;
106 }
107
108 // Place token using the continuation indenter and store the penalty.
109 Penalty += Indenter->addTokenToState(State, NewLine, DryRun, ExtraSpaces);
110 }
111 return Penalty;
112}
113
Daniel Jasper01603472014-01-09 13:42:56 +0000114unsigned CommaSeparatedList::formatFromToken(LineState &State,
115 ContinuationIndenter *Indenter,
116 bool DryRun) {
117 if (HasNestedBracedList)
118 State.Stack.back().AvoidBinPacking = true;
119 return 0;
120}
121
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000122// Returns the lengths in code points between Begin and End (both included),
123// assuming that the entire sequence is put on a single line.
124static unsigned CodePointsBetween(const FormatToken *Begin,
125 const FormatToken *End) {
Daniel Jasper8863ada2013-08-26 08:10:17 +0000126 assert(End->TotalLength >= Begin->TotalLength);
Alexander Kornienko39856b72013-09-10 09:38:25 +0000127 return End->TotalLength - Begin->TotalLength + Begin->ColumnWidth;
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000128}
129
130void CommaSeparatedList::precomputeFormattingInfos(const FormatToken *Token) {
Daniel Jasper8863ada2013-08-26 08:10:17 +0000131 // FIXME: At some point we might want to do this for other lists, too.
Daniel Jasper01603472014-01-09 13:42:56 +0000132 if (!Token->MatchingParen || Token->isNot(tok::l_brace))
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000133 return;
134
Daniel Jasper839922e2014-08-13 08:46:21 +0000135 // In C++11 braced list style, we should not format in columns unless they
136 // have many items (20 or more) or we allow bin-packing of function
137 // parameters.
138 if (Style.Cpp11BracedListStyle && !Style.BinPackParameters &&
139 Commas.size() < 19)
Daniel Jasperae8e0d82014-04-17 11:32:02 +0000140 return;
141
Daniel Jasper13404da2014-11-27 14:40:48 +0000142 // Column format doesn't really make sense if we don't align after brackets.
143 if (!Style.AlignAfterOpenBracket)
144 return;
145
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000146 FormatToken *ItemBegin = Token->Next;
147 SmallVector<bool, 8> MustBreakBeforeItem;
148
149 // The lengths of an item if it is put at the end of the line. This includes
150 // trailing comments which are otherwise ignored for column alignment.
151 SmallVector<unsigned, 8> EndOfLineItemLength;
152
153 for (unsigned i = 0, e = Commas.size() + 1; i != e; ++i) {
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000154 // Skip comments on their own line.
155 while (ItemBegin->HasUnescapedNewline && ItemBegin->isTrailingComment())
156 ItemBegin = ItemBegin->Next;
157
158 MustBreakBeforeItem.push_back(ItemBegin->MustBreakBefore);
Daniel Jasper7c72d9f2013-10-24 14:14:49 +0000159 if (ItemBegin->is(tok::l_brace))
160 HasNestedBracedList = true;
Craig Topper2145bc02014-05-09 08:15:10 +0000161 const FormatToken *ItemEnd = nullptr;
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000162 if (i == Commas.size()) {
163 ItemEnd = Token->MatchingParen;
164 const FormatToken *NonCommentEnd = ItemEnd->getPreviousNonComment();
165 ItemLengths.push_back(CodePointsBetween(ItemBegin, NonCommentEnd));
166 if (Style.Cpp11BracedListStyle) {
167 // In Cpp11 braced list style, the } and possibly other subsequent
168 // tokens will need to stay on a line with the last element.
169 while (ItemEnd->Next && !ItemEnd->Next->CanBreakBefore)
170 ItemEnd = ItemEnd->Next;
171 } else {
172 // In other braced lists styles, the "}" can be wrapped to the new line.
173 ItemEnd = Token->MatchingParen->Previous;
174 }
175 } else {
176 ItemEnd = Commas[i];
177 // The comma is counted as part of the item when calculating the length.
Daniel Jasper8863ada2013-08-26 08:10:17 +0000178 ItemLengths.push_back(CodePointsBetween(ItemBegin, ItemEnd));
Daniel Jasper540dbe22014-09-19 08:28:43 +0000179
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000180 // Consume trailing comments so the are included in EndOfLineItemLength.
181 if (ItemEnd->Next && !ItemEnd->Next->HasUnescapedNewline &&
182 ItemEnd->Next->isTrailingComment())
183 ItemEnd = ItemEnd->Next;
184 }
185 EndOfLineItemLength.push_back(CodePointsBetween(ItemBegin, ItemEnd));
Daniel Jasper8863ada2013-08-26 08:10:17 +0000186 // If there is a trailing comma in the list, the next item will start at the
187 // closing brace. Don't create an extra item for this.
188 if (ItemEnd->getNextNonComment() == Token->MatchingParen)
189 break;
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000190 ItemBegin = ItemEnd->Next;
191 }
192
Daniel Jasper01603472014-01-09 13:42:56 +0000193 // If this doesn't have a nested list, we require at least 6 elements in order
194 // create a column layout. If it has a nested list, column layout ensures one
Daniel Jasperd57843d2015-05-11 13:35:40 +0000195 // list element per line.
Daniel Jaspere4c16c72015-05-08 13:51:14 +0000196 if (Commas.size() < 5 || Token->NestingLevel != 0)
Daniel Jasper01603472014-01-09 13:42:56 +0000197 return;
198
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000199 // We can never place more than ColumnLimit / 3 items in a row (because of the
200 // spaces and the comma).
Daniel Jasperd57843d2015-05-11 13:35:40 +0000201 for (unsigned Columns = 1; Columns <= Style.ColumnLimit / 3; ++Columns) {
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000202 ColumnFormat Format;
203 Format.Columns = Columns;
204 Format.ColumnSizes.resize(Columns);
Daniel Jasperd57843d2015-05-11 13:35:40 +0000205 std::vector<unsigned> MinSizeInColumn(Columns, UINT_MAX);
Daniel Jasper7c72d9f2013-10-24 14:14:49 +0000206 Format.LineCount = 1;
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000207 bool HasRowWithSufficientColumns = false;
208 unsigned Column = 0;
209 for (unsigned i = 0, e = ItemLengths.size(); i != e; ++i) {
Manuel Klimek71814b42013-10-11 21:25:45 +0000210 assert(i < MustBreakBeforeItem.size());
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000211 if (MustBreakBeforeItem[i] || Column == Columns) {
212 ++Format.LineCount;
213 Column = 0;
214 }
215 if (Column == Columns - 1)
216 HasRowWithSufficientColumns = true;
Daniel Jasperd57843d2015-05-11 13:35:40 +0000217 unsigned Length =
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000218 (Column == Columns - 1) ? EndOfLineItemLength[i] : ItemLengths[i];
Daniel Jasperd57843d2015-05-11 13:35:40 +0000219 Format.ColumnSizes[Column] = std::max(Format.ColumnSizes[Column], Length);
220 MinSizeInColumn[Column] = std::min(MinSizeInColumn[Column], Length);
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000221 ++Column;
222 }
223 // If all rows are terminated early (e.g. by trailing comments), we don't
224 // need to look further.
225 if (!HasRowWithSufficientColumns)
226 break;
227 Format.TotalWidth = Columns - 1; // Width of the N-1 spaces.
Daniel Jasperd57843d2015-05-11 13:35:40 +0000228
229 for (unsigned i = 0; i < Columns; ++i)
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000230 Format.TotalWidth += Format.ColumnSizes[i];
Daniel Jasperd57843d2015-05-11 13:35:40 +0000231
232 // Don't use this Format, if the difference between the longest and shortest
233 // element in a column exceeds a threshold to avoid excessive spaces.
234 if ([&] {
235 for (unsigned i = 0; i < Columns - 1; ++i)
236 if (Format.ColumnSizes[i] - MinSizeInColumn[i] > 10)
237 return true;
238 return false;
239 }())
240 continue;
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000241
242 // Ignore layouts that are bound to violate the column limit.
243 if (Format.TotalWidth > Style.ColumnLimit)
244 continue;
245
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000246 Formats.push_back(Format);
247 }
248}
249
250const CommaSeparatedList::ColumnFormat *
251CommaSeparatedList::getColumnFormat(unsigned RemainingCharacters) const {
Craig Topper2145bc02014-05-09 08:15:10 +0000252 const ColumnFormat *BestFormat = nullptr;
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000253 for (SmallVector<ColumnFormat, 4>::const_reverse_iterator
254 I = Formats.rbegin(),
255 E = Formats.rend();
256 I != E; ++I) {
257 if (I->TotalWidth <= RemainingCharacters) {
258 if (BestFormat && I->LineCount > BestFormat->LineCount)
259 break;
260 BestFormat = &*I;
261 }
262 }
263 return BestFormat;
264}
265
266} // namespace format
267} // namespace clang