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 TokenRole::~TokenRole() {}
27 void TokenRole::precomputeFormattingInfos(const FormatToken *Token) {}
29 unsigned CommaSeparatedList::format(LineState &State,
30 ContinuationIndenter *Indenter,
32 if (!State.NextToken->Previous || !State.NextToken->Previous->Previous ||
36 // Ensure that we start on the opening brace.
37 const FormatToken *LBrace = State.NextToken->Previous->Previous;
38 if (LBrace->isNot(tok::l_brace) ||
39 LBrace->BlockKind == BK_Block ||
40 LBrace->Type == TT_DictLiteral ||
41 LBrace->Next->Type == TT_DesignatedInitializerPeriod)
44 // Calculate the number of code points we have to format this list. As the
45 // first token is already placed, we have to subtract it.
46 unsigned RemainingCodePoints = Style.ColumnLimit - State.Column +
47 State.NextToken->Previous->ColumnWidth;
49 // Find the best ColumnFormat, i.e. the best number of columns to use.
50 const ColumnFormat *Format = getColumnFormat(RemainingCodePoints);
54 // Format the entire list.
58 while (State.NextToken != LBrace->MatchingParen) {
60 unsigned ExtraSpaces = 0;
62 // If the previous token was one of our commas, we are now on the next item.
63 if (Item < Commas.size() && State.NextToken->Previous == Commas[Item]) {
64 if (!State.NextToken->isTrailingComment()) {
65 ExtraSpaces += Format->ColumnSizes[Column] - ItemLengths[Item];
71 if (Column == Format->Columns || State.NextToken->MustBreakBefore) {
76 // Place token using the continuation indenter and store the penalty.
77 Penalty += Indenter->addTokenToState(State, NewLine, DryRun, ExtraSpaces);
82 // Returns the lengths in code points between Begin and End (both included),
83 // assuming that the entire sequence is put on a single line.
84 static unsigned CodePointsBetween(const FormatToken *Begin,
85 const FormatToken *End) {
86 assert(End->TotalLength >= Begin->TotalLength);
87 return End->TotalLength - Begin->TotalLength + Begin->ColumnWidth;
90 void CommaSeparatedList::precomputeFormattingInfos(const FormatToken *Token) {
91 // FIXME: At some point we might want to do this for other lists, too.
92 if (!Token->MatchingParen || Token->isNot(tok::l_brace))
95 FormatToken *ItemBegin = Token->Next;
96 SmallVector<bool, 8> MustBreakBeforeItem;
98 // The lengths of an item if it is put at the end of the line. This includes
99 // trailing comments which are otherwise ignored for column alignment.
100 SmallVector<unsigned, 8> EndOfLineItemLength;
102 bool HasNestedBracedList = false;
103 for (unsigned i = 0, e = Commas.size() + 1; i != e; ++i) {
104 // Skip comments on their own line.
105 while (ItemBegin->HasUnescapedNewline && ItemBegin->isTrailingComment())
106 ItemBegin = ItemBegin->Next;
108 MustBreakBeforeItem.push_back(ItemBegin->MustBreakBefore);
109 if (ItemBegin->is(tok::l_brace))
110 HasNestedBracedList = true;
111 const FormatToken *ItemEnd = NULL;
112 if (i == Commas.size()) {
113 ItemEnd = Token->MatchingParen;
114 const FormatToken *NonCommentEnd = ItemEnd->getPreviousNonComment();
115 ItemLengths.push_back(CodePointsBetween(ItemBegin, NonCommentEnd));
116 if (Style.Cpp11BracedListStyle) {
117 // In Cpp11 braced list style, the } and possibly other subsequent
118 // tokens will need to stay on a line with the last element.
119 while (ItemEnd->Next && !ItemEnd->Next->CanBreakBefore)
120 ItemEnd = ItemEnd->Next;
122 // In other braced lists styles, the "}" can be wrapped to the new line.
123 ItemEnd = Token->MatchingParen->Previous;
127 // The comma is counted as part of the item when calculating the length.
128 ItemLengths.push_back(CodePointsBetween(ItemBegin, ItemEnd));
129 // Consume trailing comments so the are included in EndOfLineItemLength.
130 if (ItemEnd->Next && !ItemEnd->Next->HasUnescapedNewline &&
131 ItemEnd->Next->isTrailingComment())
132 ItemEnd = ItemEnd->Next;
134 EndOfLineItemLength.push_back(CodePointsBetween(ItemBegin, ItemEnd));
135 // If there is a trailing comma in the list, the next item will start at the
136 // closing brace. Don't create an extra item for this.
137 if (ItemEnd->getNextNonComment() == Token->MatchingParen)
139 ItemBegin = ItemEnd->Next;
142 // We can never place more than ColumnLimit / 3 items in a row (because of the
143 // spaces and the comma).
144 for (unsigned Columns = 1; Columns <= Style.ColumnLimit / 3; ++Columns) {
146 Format.Columns = Columns;
147 Format.ColumnSizes.resize(Columns);
148 Format.LineCount = 1;
149 bool HasRowWithSufficientColumns = false;
151 for (unsigned i = 0, e = ItemLengths.size(); i != e; ++i) {
152 assert(i < MustBreakBeforeItem.size());
153 if (MustBreakBeforeItem[i] || Column == Columns) {
157 if (Column == Columns - 1)
158 HasRowWithSufficientColumns = true;
160 (Column == Columns - 1) ? EndOfLineItemLength[i] : ItemLengths[i];
161 Format.ColumnSizes[Column] =
162 std::max(Format.ColumnSizes[Column], length);
165 // If all rows are terminated early (e.g. by trailing comments), we don't
166 // need to look further.
167 if (!HasRowWithSufficientColumns)
169 Format.TotalWidth = Columns - 1; // Width of the N-1 spaces.
170 for (unsigned i = 0; i < Columns; ++i) {
171 Format.TotalWidth += Format.ColumnSizes[i];
174 // Ignore layouts that are bound to violate the column limit.
175 if (Format.TotalWidth > Style.ColumnLimit)
178 // If this braced list has nested braced list, we format it either with one
179 // element per line or with all elements on one line.
180 if (HasNestedBracedList && Columns > 1 && Format.LineCount > 1)
183 Formats.push_back(Format);
187 const CommaSeparatedList::ColumnFormat *
188 CommaSeparatedList::getColumnFormat(unsigned RemainingCharacters) const {
189 const ColumnFormat *BestFormat = NULL;
190 for (SmallVector<ColumnFormat, 4>::const_reverse_iterator
191 I = Formats.rbegin(),
194 if (I->TotalWidth <= RemainingCharacters) {
195 if (BestFormat && I->LineCount > BestFormat->LineCount)
203 } // namespace format