blob: 4ca4edbe1587e44dcd397fc69a6df43222d7d6ba [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 Jasper8de9ed02013-08-22 15:00:41 +000051 if (!Format)
52 return 0;
53
54 // Format the entire list.
55 unsigned Penalty = 0;
56 unsigned Column = 0;
57 unsigned Item = 0;
58 while (State.NextToken != LBrace->MatchingParen) {
59 bool NewLine = false;
60 unsigned ExtraSpaces = 0;
61
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];
66 ++Column;
67 }
68 ++Item;
69 }
70
71 if (Column == Format->Columns || State.NextToken->MustBreakBefore) {
72 Column = 0;
73 NewLine = true;
74 }
75
76 // Place token using the continuation indenter and store the penalty.
77 Penalty += Indenter->addTokenToState(State, NewLine, DryRun, ExtraSpaces);
78 }
79 return Penalty;
80}
81
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.
84static unsigned CodePointsBetween(const FormatToken *Begin,
85 const FormatToken *End) {
Daniel Jasper8863ada2013-08-26 08:10:17 +000086 assert(End->TotalLength >= Begin->TotalLength);
Alexander Kornienko39856b72013-09-10 09:38:25 +000087 return End->TotalLength - Begin->TotalLength + Begin->ColumnWidth;
Daniel Jasper8de9ed02013-08-22 15:00:41 +000088}
89
90void CommaSeparatedList::precomputeFormattingInfos(const FormatToken *Token) {
Daniel Jasper8863ada2013-08-26 08:10:17 +000091 // FIXME: At some point we might want to do this for other lists, too.
92 if (!Token->MatchingParen || Token->isNot(tok::l_brace))
Daniel Jasper8de9ed02013-08-22 15:00:41 +000093 return;
94
95 FormatToken *ItemBegin = Token->Next;
96 SmallVector<bool, 8> MustBreakBeforeItem;
97
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;
101
102 for (unsigned i = 0, e = Commas.size() + 1; i != e; ++i) {
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000103 // Skip comments on their own line.
104 while (ItemBegin->HasUnescapedNewline && ItemBegin->isTrailingComment())
105 ItemBegin = ItemBegin->Next;
106
107 MustBreakBeforeItem.push_back(ItemBegin->MustBreakBefore);
108 const FormatToken *ItemEnd = NULL;
109 if (i == Commas.size()) {
110 ItemEnd = Token->MatchingParen;
111 const FormatToken *NonCommentEnd = ItemEnd->getPreviousNonComment();
112 ItemLengths.push_back(CodePointsBetween(ItemBegin, NonCommentEnd));
113 if (Style.Cpp11BracedListStyle) {
114 // In Cpp11 braced list style, the } and possibly other subsequent
115 // tokens will need to stay on a line with the last element.
116 while (ItemEnd->Next && !ItemEnd->Next->CanBreakBefore)
117 ItemEnd = ItemEnd->Next;
118 } else {
119 // In other braced lists styles, the "}" can be wrapped to the new line.
120 ItemEnd = Token->MatchingParen->Previous;
121 }
122 } else {
123 ItemEnd = Commas[i];
124 // The comma is counted as part of the item when calculating the length.
Daniel Jasper8863ada2013-08-26 08:10:17 +0000125 ItemLengths.push_back(CodePointsBetween(ItemBegin, ItemEnd));
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000126 // Consume trailing comments so the are included in EndOfLineItemLength.
127 if (ItemEnd->Next && !ItemEnd->Next->HasUnescapedNewline &&
128 ItemEnd->Next->isTrailingComment())
129 ItemEnd = ItemEnd->Next;
130 }
131 EndOfLineItemLength.push_back(CodePointsBetween(ItemBegin, ItemEnd));
Daniel Jasper8863ada2013-08-26 08:10:17 +0000132 // If there is a trailing comma in the list, the next item will start at the
133 // closing brace. Don't create an extra item for this.
134 if (ItemEnd->getNextNonComment() == Token->MatchingParen)
135 break;
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000136 ItemBegin = ItemEnd->Next;
137 }
138
139 // We can never place more than ColumnLimit / 3 items in a row (because of the
140 // spaces and the comma).
141 for (unsigned Columns = 1; Columns <= Style.ColumnLimit / 3; ++Columns) {
142 ColumnFormat Format;
143 Format.Columns = Columns;
144 Format.ColumnSizes.resize(Columns);
145 Format.LineCount = 0;
146 bool HasRowWithSufficientColumns = false;
147 unsigned Column = 0;
148 for (unsigned i = 0, e = ItemLengths.size(); i != e; ++i) {
Manuel Klimek71814b42013-10-11 21:25:45 +0000149 assert(i < MustBreakBeforeItem.size());
Daniel Jasper8de9ed02013-08-22 15:00:41 +0000150 if (MustBreakBeforeItem[i] || Column == Columns) {
151 ++Format.LineCount;
152 Column = 0;
153 }
154 if (Column == Columns - 1)
155 HasRowWithSufficientColumns = true;
156 unsigned length =
157 (Column == Columns - 1) ? EndOfLineItemLength[i] : ItemLengths[i];
158 Format.ColumnSizes[Column] =
159 std::max(Format.ColumnSizes[Column], length);
160 ++Column;
161 }
162 // If all rows are terminated early (e.g. by trailing comments), we don't
163 // need to look further.
164 if (!HasRowWithSufficientColumns)
165 break;
166 Format.TotalWidth = Columns - 1; // Width of the N-1 spaces.
167 for (unsigned i = 0; i < Columns; ++i) {
168 Format.TotalWidth += Format.ColumnSizes[i];
169 }
170
171 // Ignore layouts that are bound to violate the column limit.
172 if (Format.TotalWidth > Style.ColumnLimit)
173 continue;
174
175 Formats.push_back(Format);
176 }
177}
178
179const CommaSeparatedList::ColumnFormat *
180CommaSeparatedList::getColumnFormat(unsigned RemainingCharacters) const {
181 const ColumnFormat *BestFormat = NULL;
182 for (SmallVector<ColumnFormat, 4>::const_reverse_iterator
183 I = Formats.rbegin(),
184 E = Formats.rend();
185 I != E; ++I) {
186 if (I->TotalWidth <= RemainingCharacters) {
187 if (BestFormat && I->LineCount > BestFormat->LineCount)
188 break;
189 BestFormat = &*I;
190 }
191 }
192 return BestFormat;
193}
194
195} // namespace format
196} // namespace clang