blob: 16600f24ee80f87862d0d4b7bfd03e8569f93bc9 [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
Alp Tokerf6a24ce2013-12-05 16:25:25 +000053 // preferred 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.
Daniel Jasper63af7c42013-12-09 14:40:19 +000095 if (!Token->MatchingParen || Token->isNot(tok::l_brace) ||
96 Token->NestingLevel != 0)
Daniel Jasper8de9ed02013-08-22 15:00:41 +000097 return;
98
99 FormatToken *ItemBegin = Token->Next;
100 SmallVector<bool, 8> MustBreakBeforeItem;
101
102 // The lengths of an item if it is put at the end of the line. This includes
103 // trailing comments which are otherwise ignored for column alignment.
104 SmallVector<unsigned, 8> EndOfLineItemLength;
105
Daniel Jasper7c72d9f2013-10-24 14:14:49 +0000106 bool HasNestedBracedList = false;
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000107 for (unsigned i = 0, e = Commas.size() + 1; i != e; ++i) {
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000108 // Skip comments on their own line.
109 while (ItemBegin->HasUnescapedNewline && ItemBegin->isTrailingComment())
110 ItemBegin = ItemBegin->Next;
111
112 MustBreakBeforeItem.push_back(ItemBegin->MustBreakBefore);
Daniel Jasper7c72d9f2013-10-24 14:14:49 +0000113 if (ItemBegin->is(tok::l_brace))
114 HasNestedBracedList = true;
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000115 const FormatToken *ItemEnd = NULL;
116 if (i == Commas.size()) {
117 ItemEnd = Token->MatchingParen;
118 const FormatToken *NonCommentEnd = ItemEnd->getPreviousNonComment();
119 ItemLengths.push_back(CodePointsBetween(ItemBegin, NonCommentEnd));
120 if (Style.Cpp11BracedListStyle) {
121 // In Cpp11 braced list style, the } and possibly other subsequent
122 // tokens will need to stay on a line with the last element.
123 while (ItemEnd->Next && !ItemEnd->Next->CanBreakBefore)
124 ItemEnd = ItemEnd->Next;
125 } else {
126 // In other braced lists styles, the "}" can be wrapped to the new line.
127 ItemEnd = Token->MatchingParen->Previous;
128 }
129 } else {
130 ItemEnd = Commas[i];
131 // The comma is counted as part of the item when calculating the length.
Daniel Jasper8863ada2013-08-26 08:10:17 +0000132 ItemLengths.push_back(CodePointsBetween(ItemBegin, ItemEnd));
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000133 // Consume trailing comments so the are included in EndOfLineItemLength.
134 if (ItemEnd->Next && !ItemEnd->Next->HasUnescapedNewline &&
135 ItemEnd->Next->isTrailingComment())
136 ItemEnd = ItemEnd->Next;
137 }
138 EndOfLineItemLength.push_back(CodePointsBetween(ItemBegin, ItemEnd));
Daniel Jasper8863ada2013-08-26 08:10:17 +0000139 // If there is a trailing comma in the list, the next item will start at the
140 // closing brace. Don't create an extra item for this.
141 if (ItemEnd->getNextNonComment() == Token->MatchingParen)
142 break;
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000143 ItemBegin = ItemEnd->Next;
144 }
145
146 // We can never place more than ColumnLimit / 3 items in a row (because of the
147 // spaces and the comma).
148 for (unsigned Columns = 1; Columns <= Style.ColumnLimit / 3; ++Columns) {
149 ColumnFormat Format;
150 Format.Columns = Columns;
151 Format.ColumnSizes.resize(Columns);
Daniel Jasper7c72d9f2013-10-24 14:14:49 +0000152 Format.LineCount = 1;
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000153 bool HasRowWithSufficientColumns = false;
154 unsigned Column = 0;
155 for (unsigned i = 0, e = ItemLengths.size(); i != e; ++i) {
Manuel Klimek71814b42013-10-11 21:25:45 +0000156 assert(i < MustBreakBeforeItem.size());
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000157 if (MustBreakBeforeItem[i] || Column == Columns) {
158 ++Format.LineCount;
159 Column = 0;
160 }
161 if (Column == Columns - 1)
162 HasRowWithSufficientColumns = true;
163 unsigned length =
164 (Column == Columns - 1) ? EndOfLineItemLength[i] : ItemLengths[i];
165 Format.ColumnSizes[Column] =
166 std::max(Format.ColumnSizes[Column], length);
167 ++Column;
168 }
169 // If all rows are terminated early (e.g. by trailing comments), we don't
170 // need to look further.
171 if (!HasRowWithSufficientColumns)
172 break;
173 Format.TotalWidth = Columns - 1; // Width of the N-1 spaces.
174 for (unsigned i = 0; i < Columns; ++i) {
175 Format.TotalWidth += Format.ColumnSizes[i];
176 }
177
178 // Ignore layouts that are bound to violate the column limit.
179 if (Format.TotalWidth > Style.ColumnLimit)
180 continue;
181
Daniel Jasper7c72d9f2013-10-24 14:14:49 +0000182 // If this braced list has nested braced list, we format it either with one
183 // element per line or with all elements on one line.
184 if (HasNestedBracedList && Columns > 1 && Format.LineCount > 1)
185 continue;
186
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000187 Formats.push_back(Format);
188 }
189}
190
191const CommaSeparatedList::ColumnFormat *
192CommaSeparatedList::getColumnFormat(unsigned RemainingCharacters) const {
193 const ColumnFormat *BestFormat = NULL;
194 for (SmallVector<ColumnFormat, 4>::const_reverse_iterator
195 I = Formats.rbegin(),
196 E = Formats.rend();
197 I != E; ++I) {
198 if (I->TotalWidth <= RemainingCharacters) {
199 if (BestFormat && I->LineCount > BestFormat->LineCount)
200 break;
201 BestFormat = &*I;
202 }
203 }
204 return BestFormat;
205}
206
207} // namespace format
208} // namespace clang