blob: bab2425205cc42de3ac7c06e5e17f910f58109a7 [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
25TokenRole::~TokenRole() {}
26
27void TokenRole::precomputeFormattingInfos(const FormatToken *Token) {}
28
29unsigned CommaSeparatedList::format(LineState &State,
30 ContinuationIndenter *Indenter,
31 bool DryRun) {
32 if (!State.NextToken->Previous || !State.NextToken->Previous->Previous ||
33 Commas.size() <= 2)
34 return 0;
35
36 // Ensure that we start on the opening brace.
37 const FormatToken *LBrace = State.NextToken->Previous->Previous;
38 if (LBrace->isNot(tok::l_brace) ||
Daniel Jasper015ed022013-09-13 09:20:45 +000039 LBrace->BlockKind == BK_Block ||
Daniel Jasperb596fb22013-10-24 10:31:50 +000040 LBrace->Type == TT_DictLiteral ||
Daniel Jasper8de9ed02013-08-22 15:00:41 +000041 LBrace->Next->Type == TT_DesignatedInitializerPeriod)
42 return 0;
43
Daniel Jaspercb3f0ed2013-08-27 08:43:47 +000044 // 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 +
Alexander Kornienko39856b72013-09-10 09:38:25 +000047 State.NextToken->Previous->ColumnWidth;
Daniel Jaspercb3f0ed2013-08-27 08:43:47 +000048
Daniel Jasper8de9ed02013-08-22 15:00:41 +000049 // Find the best ColumnFormat, i.e. the best number of columns to use.
Daniel Jaspercb3f0ed2013-08-27 08:43:47 +000050 const ColumnFormat *Format = getColumnFormat(RemainingCodePoints);
Daniel Jasper1a1a2ab2013-11-23 10:22:59 +000051 // If no ColumnFormat can be used, the braced list would generally be
52 // bin-packed. Add a severe penalty to this so that column layouts are
53 // prefered if possible.
Daniel Jasper8de9ed02013-08-22 15:00:41 +000054 if (!Format)
Daniel Jasper1a1a2ab2013-11-23 10:22:59 +000055 return 10000;
Daniel Jasper8de9ed02013-08-22 15:00:41 +000056
57 // Format the entire list.
58 unsigned Penalty = 0;
59 unsigned Column = 0;
60 unsigned Item = 0;
61 while (State.NextToken != LBrace->MatchingParen) {
62 bool NewLine = false;
63 unsigned ExtraSpaces = 0;
64
65 // If the previous token was one of our commas, we are now on the next item.
66 if (Item < Commas.size() && State.NextToken->Previous == Commas[Item]) {
67 if (!State.NextToken->isTrailingComment()) {
68 ExtraSpaces += Format->ColumnSizes[Column] - ItemLengths[Item];
69 ++Column;
70 }
71 ++Item;
72 }
73
74 if (Column == Format->Columns || State.NextToken->MustBreakBefore) {
75 Column = 0;
76 NewLine = true;
77 }
78
79 // Place token using the continuation indenter and store the penalty.
80 Penalty += Indenter->addTokenToState(State, NewLine, DryRun, ExtraSpaces);
81 }
82 return Penalty;
83}
84
85// Returns the lengths in code points between Begin and End (both included),
86// assuming that the entire sequence is put on a single line.
87static unsigned CodePointsBetween(const FormatToken *Begin,
88 const FormatToken *End) {
Daniel Jasper8863ada2013-08-26 08:10:17 +000089 assert(End->TotalLength >= Begin->TotalLength);
Alexander Kornienko39856b72013-09-10 09:38:25 +000090 return End->TotalLength - Begin->TotalLength + Begin->ColumnWidth;
Daniel Jasper8de9ed02013-08-22 15:00:41 +000091}
92
93void CommaSeparatedList::precomputeFormattingInfos(const FormatToken *Token) {
Daniel Jasper8863ada2013-08-26 08:10:17 +000094 // FIXME: At some point we might want to do this for other lists, too.
95 if (!Token->MatchingParen || Token->isNot(tok::l_brace))
Daniel Jasper8de9ed02013-08-22 15:00:41 +000096 return;
97
98 FormatToken *ItemBegin = Token->Next;
99 SmallVector<bool, 8> MustBreakBeforeItem;
100
101 // The lengths of an item if it is put at the end of the line. This includes
102 // trailing comments which are otherwise ignored for column alignment.
103 SmallVector<unsigned, 8> EndOfLineItemLength;
104
Daniel Jasper7c72d9f2013-10-24 14:14:49 +0000105 bool HasNestedBracedList = false;
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000106 for (unsigned i = 0, e = Commas.size() + 1; i != e; ++i) {
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000107 // Skip comments on their own line.
108 while (ItemBegin->HasUnescapedNewline && ItemBegin->isTrailingComment())
109 ItemBegin = ItemBegin->Next;
110
111 MustBreakBeforeItem.push_back(ItemBegin->MustBreakBefore);
Daniel Jasper7c72d9f2013-10-24 14:14:49 +0000112 if (ItemBegin->is(tok::l_brace))
113 HasNestedBracedList = true;
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000114 const FormatToken *ItemEnd = NULL;
115 if (i == Commas.size()) {
116 ItemEnd = Token->MatchingParen;
117 const FormatToken *NonCommentEnd = ItemEnd->getPreviousNonComment();
118 ItemLengths.push_back(CodePointsBetween(ItemBegin, NonCommentEnd));
119 if (Style.Cpp11BracedListStyle) {
120 // In Cpp11 braced list style, the } and possibly other subsequent
121 // tokens will need to stay on a line with the last element.
122 while (ItemEnd->Next && !ItemEnd->Next->CanBreakBefore)
123 ItemEnd = ItemEnd->Next;
124 } else {
125 // In other braced lists styles, the "}" can be wrapped to the new line.
126 ItemEnd = Token->MatchingParen->Previous;
127 }
128 } else {
129 ItemEnd = Commas[i];
130 // The comma is counted as part of the item when calculating the length.
Daniel Jasper8863ada2013-08-26 08:10:17 +0000131 ItemLengths.push_back(CodePointsBetween(ItemBegin, ItemEnd));
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000132 // Consume trailing comments so the are included in EndOfLineItemLength.
133 if (ItemEnd->Next && !ItemEnd->Next->HasUnescapedNewline &&
134 ItemEnd->Next->isTrailingComment())
135 ItemEnd = ItemEnd->Next;
136 }
137 EndOfLineItemLength.push_back(CodePointsBetween(ItemBegin, ItemEnd));
Daniel Jasper8863ada2013-08-26 08:10:17 +0000138 // If there is a trailing comma in the list, the next item will start at the
139 // closing brace. Don't create an extra item for this.
140 if (ItemEnd->getNextNonComment() == Token->MatchingParen)
141 break;
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000142 ItemBegin = ItemEnd->Next;
143 }
144
145 // We can never place more than ColumnLimit / 3 items in a row (because of the
146 // spaces and the comma).
147 for (unsigned Columns = 1; Columns <= Style.ColumnLimit / 3; ++Columns) {
148 ColumnFormat Format;
149 Format.Columns = Columns;
150 Format.ColumnSizes.resize(Columns);
Daniel Jasper7c72d9f2013-10-24 14:14:49 +0000151 Format.LineCount = 1;
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000152 bool HasRowWithSufficientColumns = false;
153 unsigned Column = 0;
154 for (unsigned i = 0, e = ItemLengths.size(); i != e; ++i) {
Manuel Klimek71814b42013-10-11 21:25:45 +0000155 assert(i < MustBreakBeforeItem.size());
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000156 if (MustBreakBeforeItem[i] || Column == Columns) {
157 ++Format.LineCount;
158 Column = 0;
159 }
160 if (Column == Columns - 1)
161 HasRowWithSufficientColumns = true;
162 unsigned length =
163 (Column == Columns - 1) ? EndOfLineItemLength[i] : ItemLengths[i];
164 Format.ColumnSizes[Column] =
165 std::max(Format.ColumnSizes[Column], length);
166 ++Column;
167 }
168 // If all rows are terminated early (e.g. by trailing comments), we don't
169 // need to look further.
170 if (!HasRowWithSufficientColumns)
171 break;
172 Format.TotalWidth = Columns - 1; // Width of the N-1 spaces.
173 for (unsigned i = 0; i < Columns; ++i) {
174 Format.TotalWidth += Format.ColumnSizes[i];
175 }
176
177 // Ignore layouts that are bound to violate the column limit.
178 if (Format.TotalWidth > Style.ColumnLimit)
179 continue;
180
Daniel Jasper7c72d9f2013-10-24 14:14:49 +0000181 // If this braced list has nested braced list, we format it either with one
182 // element per line or with all elements on one line.
183 if (HasNestedBracedList && Columns > 1 && Format.LineCount > 1)
184 continue;
185
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000186 Formats.push_back(Format);
187 }
188}
189
190const CommaSeparatedList::ColumnFormat *
191CommaSeparatedList::getColumnFormat(unsigned RemainingCharacters) const {
192 const ColumnFormat *BestFormat = NULL;
193 for (SmallVector<ColumnFormat, 4>::const_reverse_iterator
194 I = Formats.rbegin(),
195 E = Formats.rend();
196 I != E; ++I) {
197 if (I->TotalWidth <= RemainingCharacters) {
198 if (BestFormat && I->LineCount > BestFormat->LineCount)
199 break;
200 BestFormat = &*I;
201 }
202 }
203 return BestFormat;
204}
205
206} // namespace format
207} // namespace clang