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"
25 // FIXME: This is copy&pasted from Sema. Put it in a common place and remove
27 bool FormatToken::isSimpleTypeSpecifier() const {
28 switch (Tok.getKind()) {
32 case tok::kw___int128:
34 case tok::kw_unsigned:
43 case tok::kw___underlying_type:
44 case tok::annot_typename:
45 case tok::kw_char16_t:
46 case tok::kw_char32_t:
48 case tok::kw_decltype:
55 TokenRole::~TokenRole() {}
57 void TokenRole::precomputeFormattingInfos(const FormatToken *Token) {}
59 unsigned CommaSeparatedList::formatAfterToken(LineState &State,
60 ContinuationIndenter *Indenter,
62 if (!State.NextToken->Previous || !State.NextToken->Previous->Previous)
65 // Ensure that we start on the opening brace.
66 const FormatToken *LBrace = State.NextToken->Previous->Previous;
67 if (LBrace->isNot(tok::l_brace) || LBrace->BlockKind == BK_Block ||
68 LBrace->Type == TT_DictLiteral ||
69 LBrace->Next->Type == TT_DesignatedInitializerPeriod)
72 // Calculate the number of code points we have to format this list. As the
73 // first token is already placed, we have to subtract it.
74 unsigned RemainingCodePoints =
75 Style.ColumnLimit - State.Column + State.NextToken->Previous->ColumnWidth;
77 // Find the best ColumnFormat, i.e. the best number of columns to use.
78 const ColumnFormat *Format = getColumnFormat(RemainingCodePoints);
79 // If no ColumnFormat can be used, the braced list would generally be
80 // bin-packed. Add a severe penalty to this so that column layouts are
81 // preferred if possible.
85 // Format the entire list.
89 while (State.NextToken != LBrace->MatchingParen) {
91 unsigned ExtraSpaces = 0;
93 // If the previous token was one of our commas, we are now on the next item.
94 if (Item < Commas.size() && State.NextToken->Previous == Commas[Item]) {
95 if (!State.NextToken->isTrailingComment()) {
96 ExtraSpaces += Format->ColumnSizes[Column] - ItemLengths[Item];
102 if (Column == Format->Columns || State.NextToken->MustBreakBefore) {
107 // Place token using the continuation indenter and store the penalty.
108 Penalty += Indenter->addTokenToState(State, NewLine, DryRun, ExtraSpaces);
113 unsigned CommaSeparatedList::formatFromToken(LineState &State,
114 ContinuationIndenter *Indenter,
116 if (HasNestedBracedList)
117 State.Stack.back().AvoidBinPacking = true;
121 // Returns the lengths in code points between Begin and End (both included),
122 // assuming that the entire sequence is put on a single line.
123 static unsigned CodePointsBetween(const FormatToken *Begin,
124 const FormatToken *End) {
125 assert(End->TotalLength >= Begin->TotalLength);
126 return End->TotalLength - Begin->TotalLength + Begin->ColumnWidth;
129 void CommaSeparatedList::precomputeFormattingInfos(const FormatToken *Token) {
130 // FIXME: At some point we might want to do this for other lists, too.
131 if (!Token->MatchingParen || Token->isNot(tok::l_brace))
134 // In C++11 braced list style, we should not format in columns unless they
135 // have many items (20 or more) or we allow bin-packing of function
137 if (Style.Cpp11BracedListStyle && !Style.BinPackParameters &&
141 // Column format doesn't really make sense if we don't align after brackets.
142 if (!Style.AlignAfterOpenBracket)
145 FormatToken *ItemBegin = Token->Next;
146 SmallVector<bool, 8> MustBreakBeforeItem;
148 // The lengths of an item if it is put at the end of the line. This includes
149 // trailing comments which are otherwise ignored for column alignment.
150 SmallVector<unsigned, 8> EndOfLineItemLength;
152 unsigned MinItemLength = Style.ColumnLimit;
153 unsigned MaxItemLength = 0;
155 for (unsigned i = 0, e = Commas.size() + 1; i != e; ++i) {
156 // Skip comments on their own line.
157 while (ItemBegin->HasUnescapedNewline && ItemBegin->isTrailingComment())
158 ItemBegin = ItemBegin->Next;
160 MustBreakBeforeItem.push_back(ItemBegin->MustBreakBefore);
161 if (ItemBegin->is(tok::l_brace))
162 HasNestedBracedList = true;
163 const FormatToken *ItemEnd = nullptr;
164 if (i == Commas.size()) {
165 ItemEnd = Token->MatchingParen;
166 const FormatToken *NonCommentEnd = ItemEnd->getPreviousNonComment();
167 ItemLengths.push_back(CodePointsBetween(ItemBegin, NonCommentEnd));
168 if (Style.Cpp11BracedListStyle) {
169 // In Cpp11 braced list style, the } and possibly other subsequent
170 // tokens will need to stay on a line with the last element.
171 while (ItemEnd->Next && !ItemEnd->Next->CanBreakBefore)
172 ItemEnd = ItemEnd->Next;
174 // In other braced lists styles, the "}" can be wrapped to the new line.
175 ItemEnd = Token->MatchingParen->Previous;
179 // The comma is counted as part of the item when calculating the length.
180 ItemLengths.push_back(CodePointsBetween(ItemBegin, ItemEnd));
181 MinItemLength = std::min(MinItemLength, ItemLengths.back());
182 MaxItemLength = std::max(MaxItemLength, ItemLengths.back());
184 // Consume trailing comments so the are included in EndOfLineItemLength.
185 if (ItemEnd->Next && !ItemEnd->Next->HasUnescapedNewline &&
186 ItemEnd->Next->isTrailingComment())
187 ItemEnd = ItemEnd->Next;
189 EndOfLineItemLength.push_back(CodePointsBetween(ItemBegin, ItemEnd));
190 // If there is a trailing comma in the list, the next item will start at the
191 // closing brace. Don't create an extra item for this.
192 if (ItemEnd->getNextNonComment() == Token->MatchingParen)
194 ItemBegin = ItemEnd->Next;
197 // If this doesn't have a nested list, we require at least 6 elements in order
198 // create a column layout. If it has a nested list, column layout ensures one
199 // list element per line. If the difference between the shortest and longest
200 // element is too large, column layout would create too much whitespace.
201 if (HasNestedBracedList || Commas.size() < 5 || Token->NestingLevel != 0 ||
202 MaxItemLength - MinItemLength > 10)
205 // We can never place more than ColumnLimit / 3 items in a row (because of the
206 // spaces and the comma).
207 for (unsigned Columns = 1; Columns <= Style.ColumnLimit / 3; ++Columns) {
209 Format.Columns = Columns;
210 Format.ColumnSizes.resize(Columns);
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);
227 // If all rows are terminated early (e.g. by trailing comments), we don't
228 // need to look further.
229 if (!HasRowWithSufficientColumns)
231 Format.TotalWidth = Columns - 1; // Width of the N-1 spaces.
232 for (unsigned i = 0; i < Columns; ++i) {
233 Format.TotalWidth += Format.ColumnSizes[i];
236 // Ignore layouts that are bound to violate the column limit.
237 if (Format.TotalWidth > Style.ColumnLimit)
240 Formats.push_back(Format);
244 const CommaSeparatedList::ColumnFormat *
245 CommaSeparatedList::getColumnFormat(unsigned RemainingCharacters) const {
246 const ColumnFormat *BestFormat = nullptr;
247 for (SmallVector<ColumnFormat, 4>::const_reverse_iterator
248 I = Formats.rbegin(),
251 if (I->TotalWidth <= RemainingCharacters) {
252 if (BestFormat && I->LineCount > BestFormat->LineCount)
260 } // namespace format