1 //===--- FormatToken.cpp - Format C++ code --------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
11 /// \brief This file implements specific functions of \c FormatTokens and their
14 //===----------------------------------------------------------------------===//
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"
26 // FIXME: This is copy&pasted from Sema. Put it in a common place and remove
28 bool FormatToken::isSimpleTypeSpecifier() const {
29 switch (Tok.getKind()) {
33 case tok::kw___int128:
35 case tok::kw_unsigned:
44 case tok::kw___underlying_type:
45 case tok::annot_typename:
46 case tok::kw_char16_t:
47 case tok::kw_char32_t:
49 case tok::kw_decltype:
56 TokenRole::~TokenRole() {}
58 void TokenRole::precomputeFormattingInfos(const FormatToken *Token) {}
60 unsigned CommaSeparatedList::formatAfterToken(LineState &State,
61 ContinuationIndenter *Indenter,
63 if (State.NextToken == nullptr || !State.NextToken->Previous)
66 // Ensure that we start on the opening brace.
67 const FormatToken *LBrace =
68 State.NextToken->Previous->getPreviousNonComment();
69 if (!LBrace || LBrace->isNot(tok::l_brace) || LBrace->BlockKind == BK_Block ||
70 LBrace->Type == TT_DictLiteral ||
71 LBrace->Next->Type == TT_DesignatedInitializerPeriod)
74 // 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.
76 unsigned RemainingCodePoints =
77 Style.ColumnLimit - State.Column + State.NextToken->Previous->ColumnWidth;
79 // Find the best ColumnFormat, i.e. the best number of columns to use.
80 const ColumnFormat *Format = getColumnFormat(RemainingCodePoints);
81 // 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
83 // preferred if possible.
87 // Format the entire list.
91 while (State.NextToken != LBrace->MatchingParen) {
93 unsigned ExtraSpaces = 0;
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];
104 if (Column == Format->Columns || State.NextToken->MustBreakBefore) {
109 // Place token using the continuation indenter and store the penalty.
110 Penalty += Indenter->addTokenToState(State, NewLine, DryRun, ExtraSpaces);
115 unsigned CommaSeparatedList::formatFromToken(LineState &State,
116 ContinuationIndenter *Indenter,
118 if (HasNestedBracedList)
119 State.Stack.back().AvoidBinPacking = true;
123 // Returns the lengths in code points between Begin and End (both included),
124 // assuming that the entire sequence is put on a single line.
125 static unsigned CodePointsBetween(const FormatToken *Begin,
126 const FormatToken *End) {
127 assert(End->TotalLength >= Begin->TotalLength);
128 return End->TotalLength - Begin->TotalLength + Begin->ColumnWidth;
131 void CommaSeparatedList::precomputeFormattingInfos(const FormatToken *Token) {
132 // FIXME: At some point we might want to do this for other lists, too.
133 if (!Token->MatchingParen || Token->isNot(tok::l_brace))
136 // 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 call
139 if (Style.Cpp11BracedListStyle && !Style.BinPackArguments &&
143 // Column format doesn't really make sense if we don't align after brackets.
144 if (!Style.AlignAfterOpenBracket)
147 FormatToken *ItemBegin = Token->Next;
148 while (ItemBegin->isTrailingComment())
149 ItemBegin = ItemBegin->Next;
150 SmallVector<bool, 8> MustBreakBeforeItem;
152 // The lengths of an item if it is put at the end of the line. This includes
153 // trailing comments which are otherwise ignored for column alignment.
154 SmallVector<unsigned, 8> EndOfLineItemLength;
156 bool HasSeparatingComment = false;
157 for (unsigned i = 0, e = Commas.size() + 1; i != e; ++i) {
158 // Skip comments on their own line.
159 while (ItemBegin->HasUnescapedNewline && ItemBegin->isTrailingComment()) {
160 ItemBegin = ItemBegin->Next;
161 HasSeparatingComment = i > 0;
164 MustBreakBeforeItem.push_back(ItemBegin->MustBreakBefore);
165 if (ItemBegin->is(tok::l_brace))
166 HasNestedBracedList = true;
167 const FormatToken *ItemEnd = nullptr;
168 if (i == Commas.size()) {
169 ItemEnd = Token->MatchingParen;
170 const FormatToken *NonCommentEnd = ItemEnd->getPreviousNonComment();
171 ItemLengths.push_back(CodePointsBetween(ItemBegin, NonCommentEnd));
172 if (Style.Cpp11BracedListStyle) {
173 // In Cpp11 braced list style, the } and possibly other subsequent
174 // tokens will need to stay on a line with the last element.
175 while (ItemEnd->Next && !ItemEnd->Next->CanBreakBefore)
176 ItemEnd = ItemEnd->Next;
178 // In other braced lists styles, the "}" can be wrapped to the new line.
179 ItemEnd = Token->MatchingParen->Previous;
183 // The comma is counted as part of the item when calculating the length.
184 ItemLengths.push_back(CodePointsBetween(ItemBegin, ItemEnd));
186 // Consume trailing comments so the are included in EndOfLineItemLength.
187 if (ItemEnd->Next && !ItemEnd->Next->HasUnescapedNewline &&
188 ItemEnd->Next->isTrailingComment())
189 ItemEnd = ItemEnd->Next;
191 EndOfLineItemLength.push_back(CodePointsBetween(ItemBegin, ItemEnd));
192 // If there is a trailing comma in the list, the next item will start at the
193 // closing brace. Don't create an extra item for this.
194 if (ItemEnd->getNextNonComment() == Token->MatchingParen)
196 ItemBegin = ItemEnd->Next;
199 // Don't use column layout for nested lists, lists with few elements and in
200 // presence of separating comments.
201 if (Token->NestingLevel != 0 || Commas.size() < 5 || HasSeparatingComment)
204 // We can never place more than ColumnLimit / 3 items in a row (because of the
205 // spaces and the comma).
206 for (unsigned Columns = 1; Columns <= Style.ColumnLimit / 3; ++Columns) {
208 Format.Columns = Columns;
209 Format.ColumnSizes.resize(Columns);
210 std::vector<unsigned> MinSizeInColumn(Columns, UINT_MAX);
211 Format.LineCount = 1;
212 bool HasRowWithSufficientColumns = false;
214 for (unsigned i = 0, e = ItemLengths.size(); i != e; ++i) {
215 assert(i < MustBreakBeforeItem.size());
216 if (MustBreakBeforeItem[i] || Column == Columns) {
220 if (Column == Columns - 1)
221 HasRowWithSufficientColumns = true;
223 (Column == Columns - 1) ? EndOfLineItemLength[i] : ItemLengths[i];
224 Format.ColumnSizes[Column] = std::max(Format.ColumnSizes[Column], Length);
225 MinSizeInColumn[Column] = std::min(MinSizeInColumn[Column], Length);
228 // If all rows are terminated early (e.g. by trailing comments), we don't
229 // need to look further.
230 if (!HasRowWithSufficientColumns)
232 Format.TotalWidth = Columns - 1; // Width of the N-1 spaces.
234 for (unsigned i = 0; i < Columns; ++i)
235 Format.TotalWidth += Format.ColumnSizes[i];
237 // Don't use this Format, if the difference between the longest and shortest
238 // element in a column exceeds a threshold to avoid excessive spaces.
240 for (unsigned i = 0; i < Columns - 1; ++i)
241 if (Format.ColumnSizes[i] - MinSizeInColumn[i] > 10)
247 // Ignore layouts that are bound to violate the column limit.
248 if (Format.TotalWidth > Style.ColumnLimit)
251 Formats.push_back(Format);
255 const CommaSeparatedList::ColumnFormat *
256 CommaSeparatedList::getColumnFormat(unsigned RemainingCharacters) const {
257 const ColumnFormat *BestFormat = nullptr;
258 for (SmallVector<ColumnFormat, 4>::const_reverse_iterator
259 I = Formats.rbegin(),
262 if (I->TotalWidth <= RemainingCharacters) {
263 if (BestFormat && I->LineCount > BestFormat->LineCount)
271 } // namespace format