blob: 24a296adc2404a723ff3d09a66deb8611567fe2d [file] [log] [blame]
Daniel Jasperd4a03db2013-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) ||
39 LBrace->Next->Type == TT_DesignatedInitializerPeriod)
40 return 0;
41
42 // Find the best ColumnFormat, i.e. the best number of columns to use.
43 unsigned RemainingCharacters = Style.ColumnLimit - State.Stack.back().Indent;
44 const ColumnFormat *Format = getColumnFormat(RemainingCharacters);
45 if (!Format)
46 return 0;
47
48 // Format the entire list.
49 unsigned Penalty = 0;
50 unsigned Column = 0;
51 unsigned Item = 0;
52 while (State.NextToken != LBrace->MatchingParen) {
53 bool NewLine = false;
54 unsigned ExtraSpaces = 0;
55
56 // If the previous token was one of our commas, we are now on the next item.
57 if (Item < Commas.size() && State.NextToken->Previous == Commas[Item]) {
58 if (!State.NextToken->isTrailingComment()) {
59 ExtraSpaces += Format->ColumnSizes[Column] - ItemLengths[Item];
60 ++Column;
61 }
62 ++Item;
63 }
64
65 if (Column == Format->Columns || State.NextToken->MustBreakBefore) {
66 Column = 0;
67 NewLine = true;
68 }
69
70 // Place token using the continuation indenter and store the penalty.
71 Penalty += Indenter->addTokenToState(State, NewLine, DryRun, ExtraSpaces);
72 }
73 return Penalty;
74}
75
76// Returns the lengths in code points between Begin and End (both included),
77// assuming that the entire sequence is put on a single line.
78static unsigned CodePointsBetween(const FormatToken *Begin,
79 const FormatToken *End) {
Daniel Jasper332c6772013-08-26 08:10:17 +000080 assert(End->TotalLength >= Begin->TotalLength);
Daniel Jasperd4a03db2013-08-22 15:00:41 +000081 return End->TotalLength - Begin->TotalLength + Begin->CodePointCount;
82}
83
84void CommaSeparatedList::precomputeFormattingInfos(const FormatToken *Token) {
Daniel Jasper332c6772013-08-26 08:10:17 +000085 // FIXME: At some point we might want to do this for other lists, too.
86 if (!Token->MatchingParen || Token->isNot(tok::l_brace))
Daniel Jasperd4a03db2013-08-22 15:00:41 +000087 return;
88
89 FormatToken *ItemBegin = Token->Next;
90 SmallVector<bool, 8> MustBreakBeforeItem;
91
92 // The lengths of an item if it is put at the end of the line. This includes
93 // trailing comments which are otherwise ignored for column alignment.
94 SmallVector<unsigned, 8> EndOfLineItemLength;
95
96 for (unsigned i = 0, e = Commas.size() + 1; i != e; ++i) {
Daniel Jasperd4a03db2013-08-22 15:00:41 +000097 // Skip comments on their own line.
98 while (ItemBegin->HasUnescapedNewline && ItemBegin->isTrailingComment())
99 ItemBegin = ItemBegin->Next;
100
101 MustBreakBeforeItem.push_back(ItemBegin->MustBreakBefore);
102 const FormatToken *ItemEnd = NULL;
103 if (i == Commas.size()) {
104 ItemEnd = Token->MatchingParen;
105 const FormatToken *NonCommentEnd = ItemEnd->getPreviousNonComment();
106 ItemLengths.push_back(CodePointsBetween(ItemBegin, NonCommentEnd));
107 if (Style.Cpp11BracedListStyle) {
108 // In Cpp11 braced list style, the } and possibly other subsequent
109 // tokens will need to stay on a line with the last element.
110 while (ItemEnd->Next && !ItemEnd->Next->CanBreakBefore)
111 ItemEnd = ItemEnd->Next;
112 } else {
113 // In other braced lists styles, the "}" can be wrapped to the new line.
114 ItemEnd = Token->MatchingParen->Previous;
115 }
116 } else {
117 ItemEnd = Commas[i];
118 // The comma is counted as part of the item when calculating the length.
Daniel Jasper332c6772013-08-26 08:10:17 +0000119 ItemLengths.push_back(CodePointsBetween(ItemBegin, ItemEnd));
Daniel Jasperd4a03db2013-08-22 15:00:41 +0000120 // Consume trailing comments so the are included in EndOfLineItemLength.
121 if (ItemEnd->Next && !ItemEnd->Next->HasUnescapedNewline &&
122 ItemEnd->Next->isTrailingComment())
123 ItemEnd = ItemEnd->Next;
124 }
125 EndOfLineItemLength.push_back(CodePointsBetween(ItemBegin, ItemEnd));
Daniel Jasper332c6772013-08-26 08:10:17 +0000126 // If there is a trailing comma in the list, the next item will start at the
127 // closing brace. Don't create an extra item for this.
128 if (ItemEnd->getNextNonComment() == Token->MatchingParen)
129 break;
Daniel Jasperd4a03db2013-08-22 15:00:41 +0000130 ItemBegin = ItemEnd->Next;
131 }
132
133 // We can never place more than ColumnLimit / 3 items in a row (because of the
134 // spaces and the comma).
135 for (unsigned Columns = 1; Columns <= Style.ColumnLimit / 3; ++Columns) {
136 ColumnFormat Format;
137 Format.Columns = Columns;
138 Format.ColumnSizes.resize(Columns);
139 Format.LineCount = 0;
140 bool HasRowWithSufficientColumns = false;
141 unsigned Column = 0;
142 for (unsigned i = 0, e = ItemLengths.size(); i != e; ++i) {
143 if (MustBreakBeforeItem[i] || Column == Columns) {
144 ++Format.LineCount;
145 Column = 0;
146 }
147 if (Column == Columns - 1)
148 HasRowWithSufficientColumns = true;
149 unsigned length =
150 (Column == Columns - 1) ? EndOfLineItemLength[i] : ItemLengths[i];
151 Format.ColumnSizes[Column] =
152 std::max(Format.ColumnSizes[Column], length);
153 ++Column;
154 }
155 // If all rows are terminated early (e.g. by trailing comments), we don't
156 // need to look further.
157 if (!HasRowWithSufficientColumns)
158 break;
159 Format.TotalWidth = Columns - 1; // Width of the N-1 spaces.
160 for (unsigned i = 0; i < Columns; ++i) {
161 Format.TotalWidth += Format.ColumnSizes[i];
162 }
163
164 // Ignore layouts that are bound to violate the column limit.
165 if (Format.TotalWidth > Style.ColumnLimit)
166 continue;
167
168 Formats.push_back(Format);
169 }
170}
171
172const CommaSeparatedList::ColumnFormat *
173CommaSeparatedList::getColumnFormat(unsigned RemainingCharacters) const {
174 const ColumnFormat *BestFormat = NULL;
175 for (SmallVector<ColumnFormat, 4>::const_reverse_iterator
176 I = Formats.rbegin(),
177 E = Formats.rend();
178 I != E; ++I) {
179 if (I->TotalWidth <= RemainingCharacters) {
180 if (BestFormat && I->LineCount > BestFormat->LineCount)
181 break;
182 BestFormat = &*I;
183 }
184 }
185 return BestFormat;
186}
187
188} // namespace format
189} // namespace clang