1 //===--- 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 
22 namespace clang {
23 namespace format {
24 
25 TokenRole::~TokenRole() {}
26 
27 void TokenRole::precomputeFormattingInfos(const FormatToken *Token) {}
28 
29 unsigned 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->BlockKind == BK_Block ||
40       LBrace->Type == TT_DictLiteral ||
41       LBrace->Next->Type == TT_DesignatedInitializerPeriod)
42     return 0;
43 
44   // 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 +
47                                  State.NextToken->Previous->ColumnWidth;
48 
49   // Find the best ColumnFormat, i.e. the best number of columns to use.
50   const ColumnFormat *Format = getColumnFormat(RemainingCodePoints);
51   // 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   // preferred if possible.
54   if (!Format)
55     return 10000;
56 
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.
87 static unsigned CodePointsBetween(const FormatToken *Begin,
88                                   const FormatToken *End) {
89   assert(End->TotalLength >= Begin->TotalLength);
90   return End->TotalLength - Begin->TotalLength + Begin->ColumnWidth;
91 }
92 
93 void CommaSeparatedList::precomputeFormattingInfos(const FormatToken *Token) {
94   // FIXME: At some point we might want to do this for other lists, too.
95   if (!Token->MatchingParen || Token->isNot(tok::l_brace) ||
96       Token->NestingLevel != 0)
97     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 
106   bool HasNestedBracedList = false;
107   for (unsigned i = 0, e = Commas.size() + 1; i != e; ++i) {
108     // Skip comments on their own line.
109     while (ItemBegin->HasUnescapedNewline && ItemBegin->isTrailingComment())
110       ItemBegin = ItemBegin->Next;
111 
112     MustBreakBeforeItem.push_back(ItemBegin->MustBreakBefore);
113     if (ItemBegin->is(tok::l_brace))
114       HasNestedBracedList = true;
115     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.
132       ItemLengths.push_back(CodePointsBetween(ItemBegin, ItemEnd));
133       // 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));
139     // 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;
143     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);
152     Format.LineCount = 1;
153     bool HasRowWithSufficientColumns = false;
154     unsigned Column = 0;
155     for (unsigned i = 0, e = ItemLengths.size(); i != e; ++i) {
156       assert(i < MustBreakBeforeItem.size());
157       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 
182     // 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 
187     Formats.push_back(Format);
188   }
189 }
190 
191 const CommaSeparatedList::ColumnFormat *
192 CommaSeparatedList::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
209