blob: 1b6d360190510d9d88252bfafaa59573a00a049c [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) {
80 return End->TotalLength - Begin->TotalLength + Begin->CodePointCount;
81}
82
83void CommaSeparatedList::precomputeFormattingInfos(const FormatToken *Token) {
84 if (!Token->MatchingParen)
85 return;
86
87 FormatToken *ItemBegin = Token->Next;
88 SmallVector<bool, 8> MustBreakBeforeItem;
89
90 // The lengths of an item if it is put at the end of the line. This includes
91 // trailing comments which are otherwise ignored for column alignment.
92 SmallVector<unsigned, 8> EndOfLineItemLength;
93
94 for (unsigned i = 0, e = Commas.size() + 1; i != e; ++i) {
Daniel Jaspered51c022013-08-23 10:05:49 +000095 // If there is a trailing comma in the list, the next item will start at the
96 // closing brace. Don't create an extra item for this.
97 if (ItemBegin == Token->MatchingParen)
98 break;
99
Daniel Jasperd4a03db2013-08-22 15:00:41 +0000100 // Skip comments on their own line.
101 while (ItemBegin->HasUnescapedNewline && ItemBegin->isTrailingComment())
102 ItemBegin = ItemBegin->Next;
103
104 MustBreakBeforeItem.push_back(ItemBegin->MustBreakBefore);
105 const FormatToken *ItemEnd = NULL;
106 if (i == Commas.size()) {
107 ItemEnd = Token->MatchingParen;
108 const FormatToken *NonCommentEnd = ItemEnd->getPreviousNonComment();
109 ItemLengths.push_back(CodePointsBetween(ItemBegin, NonCommentEnd));
110 if (Style.Cpp11BracedListStyle) {
111 // In Cpp11 braced list style, the } and possibly other subsequent
112 // tokens will need to stay on a line with the last element.
113 while (ItemEnd->Next && !ItemEnd->Next->CanBreakBefore)
114 ItemEnd = ItemEnd->Next;
115 } else {
116 // In other braced lists styles, the "}" can be wrapped to the new line.
117 ItemEnd = Token->MatchingParen->Previous;
118 }
119 } else {
120 ItemEnd = Commas[i];
121 // The comma is counted as part of the item when calculating the length.
122 ItemLengths.push_back(ItemEnd->TotalLength - ItemBegin->TotalLength +
123 ItemBegin->CodePointCount);
124 // Consume trailing comments so the are included in EndOfLineItemLength.
125 if (ItemEnd->Next && !ItemEnd->Next->HasUnescapedNewline &&
126 ItemEnd->Next->isTrailingComment())
127 ItemEnd = ItemEnd->Next;
128 }
129 EndOfLineItemLength.push_back(CodePointsBetween(ItemBegin, ItemEnd));
130 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