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 // FIXME: This is copy&pasted from Sema. Put it in a common place and remove
26 // duplication.
27 bool FormatToken::isSimpleTypeSpecifier() const {
28   switch (Tok.getKind()) {
29   case tok::kw_short:
30   case tok::kw_long:
31   case tok::kw___int64:
32   case tok::kw___int128:
33   case tok::kw_signed:
34   case tok::kw_unsigned:
35   case tok::kw_void:
36   case tok::kw_char:
37   case tok::kw_int:
38   case tok::kw_half:
39   case tok::kw_float:
40   case tok::kw_double:
41   case tok::kw_wchar_t:
42   case tok::kw_bool:
43   case tok::kw___underlying_type:
44   case tok::annot_typename:
45   case tok::kw_char16_t:
46   case tok::kw_char32_t:
47   case tok::kw_typeof:
48   case tok::kw_decltype:
49     return true;
50   default:
51     return false;
52   }
53 }
54 
55 TokenRole::~TokenRole() {}
56 
57 void TokenRole::precomputeFormattingInfos(const FormatToken *Token) {}
58 
59 unsigned CommaSeparatedList::formatAfterToken(LineState &State,
60                                               ContinuationIndenter *Indenter,
61                                               bool DryRun) {
62   if (!State.NextToken->Previous || !State.NextToken->Previous->Previous)
63     return 0;
64 
65   // Ensure that we start on the opening brace.
66   const FormatToken *LBrace = State.NextToken->Previous->Previous;
67   if (LBrace->isNot(tok::l_brace) ||
68       LBrace->BlockKind == BK_Block ||
69       LBrace->Type == TT_DictLiteral ||
70       LBrace->Next->Type == TT_DesignatedInitializerPeriod)
71     return 0;
72 
73   // Calculate the number of code points we have to format this list. As the
74   // first token is already placed, we have to subtract it.
75   unsigned RemainingCodePoints = Style.ColumnLimit - State.Column +
76                                  State.NextToken->Previous->ColumnWidth;
77 
78   // Find the best ColumnFormat, i.e. the best number of columns to use.
79   const ColumnFormat *Format = getColumnFormat(RemainingCodePoints);
80   // If no ColumnFormat can be used, the braced list would generally be
81   // bin-packed. Add a severe penalty to this so that column layouts are
82   // preferred if possible.
83   if (!Format)
84     return 10000;
85 
86   // Format the entire list.
87   unsigned Penalty = 0;
88   unsigned Column = 0;
89   unsigned Item = 0;
90   while (State.NextToken != LBrace->MatchingParen) {
91     bool NewLine = false;
92     unsigned ExtraSpaces = 0;
93 
94     // If the previous token was one of our commas, we are now on the next item.
95     if (Item < Commas.size() && State.NextToken->Previous == Commas[Item]) {
96       if (!State.NextToken->isTrailingComment()) {
97         ExtraSpaces += Format->ColumnSizes[Column] - ItemLengths[Item];
98         ++Column;
99       }
100       ++Item;
101     }
102 
103     if (Column == Format->Columns || State.NextToken->MustBreakBefore) {
104       Column = 0;
105       NewLine = true;
106     }
107 
108     // Place token using the continuation indenter and store the penalty.
109     Penalty += Indenter->addTokenToState(State, NewLine, DryRun, ExtraSpaces);
110   }
111   return Penalty;
112 }
113 
114 unsigned CommaSeparatedList::formatFromToken(LineState &State,
115                                              ContinuationIndenter *Indenter,
116                                              bool DryRun) {
117   if (HasNestedBracedList)
118     State.Stack.back().AvoidBinPacking = true;
119   return 0;
120 }
121 
122 // Returns the lengths in code points between Begin and End (both included),
123 // assuming that the entire sequence is put on a single line.
124 static unsigned CodePointsBetween(const FormatToken *Begin,
125                                   const FormatToken *End) {
126   assert(End->TotalLength >= Begin->TotalLength);
127   return End->TotalLength - Begin->TotalLength + Begin->ColumnWidth;
128 }
129 
130 void CommaSeparatedList::precomputeFormattingInfos(const FormatToken *Token) {
131   // FIXME: At some point we might want to do this for other lists, too.
132   if (!Token->MatchingParen || Token->isNot(tok::l_brace))
133     return;
134 
135   FormatToken *ItemBegin = Token->Next;
136   SmallVector<bool, 8> MustBreakBeforeItem;
137 
138   // The lengths of an item if it is put at the end of the line. This includes
139   // trailing comments which are otherwise ignored for column alignment.
140   SmallVector<unsigned, 8> EndOfLineItemLength;
141 
142   for (unsigned i = 0, e = Commas.size() + 1; i != e; ++i) {
143     // Skip comments on their own line.
144     while (ItemBegin->HasUnescapedNewline && ItemBegin->isTrailingComment())
145       ItemBegin = ItemBegin->Next;
146 
147     MustBreakBeforeItem.push_back(ItemBegin->MustBreakBefore);
148     if (ItemBegin->is(tok::l_brace))
149       HasNestedBracedList = true;
150     const FormatToken *ItemEnd = NULL;
151     if (i == Commas.size()) {
152       ItemEnd = Token->MatchingParen;
153       const FormatToken *NonCommentEnd = ItemEnd->getPreviousNonComment();
154       ItemLengths.push_back(CodePointsBetween(ItemBegin, NonCommentEnd));
155       if (Style.Cpp11BracedListStyle) {
156         // In Cpp11 braced list style, the } and possibly other subsequent
157         // tokens will need to stay on a line with the last element.
158         while (ItemEnd->Next && !ItemEnd->Next->CanBreakBefore)
159           ItemEnd = ItemEnd->Next;
160       } else {
161         // In other braced lists styles, the "}" can be wrapped to the new line.
162         ItemEnd = Token->MatchingParen->Previous;
163       }
164     } else {
165       ItemEnd = Commas[i];
166       // The comma is counted as part of the item when calculating the length.
167       ItemLengths.push_back(CodePointsBetween(ItemBegin, ItemEnd));
168       // Consume trailing comments so the are included in EndOfLineItemLength.
169       if (ItemEnd->Next && !ItemEnd->Next->HasUnescapedNewline &&
170           ItemEnd->Next->isTrailingComment())
171         ItemEnd = ItemEnd->Next;
172     }
173     EndOfLineItemLength.push_back(CodePointsBetween(ItemBegin, ItemEnd));
174     // If there is a trailing comma in the list, the next item will start at the
175     // closing brace. Don't create an extra item for this.
176     if (ItemEnd->getNextNonComment() == Token->MatchingParen)
177       break;
178     ItemBegin = ItemEnd->Next;
179   }
180 
181   // If this doesn't have a nested list, we require at least 6 elements in order
182   // create a column layout. If it has a nested list, column layout ensures one
183   // list element per line.
184   if (HasNestedBracedList || Commas.size() < 5 ||
185       Token->NestingLevel != 0)
186     return;
187 
188   // We can never place more than ColumnLimit / 3 items in a row (because of the
189   // spaces and the comma).
190   for (unsigned Columns = 1; Columns <= Style.ColumnLimit / 3; ++Columns) {
191     ColumnFormat Format;
192     Format.Columns = Columns;
193     Format.ColumnSizes.resize(Columns);
194     Format.LineCount = 1;
195     bool HasRowWithSufficientColumns = false;
196     unsigned Column = 0;
197     for (unsigned i = 0, e = ItemLengths.size(); i != e; ++i) {
198       assert(i < MustBreakBeforeItem.size());
199       if (MustBreakBeforeItem[i] || Column == Columns) {
200         ++Format.LineCount;
201         Column = 0;
202       }
203       if (Column == Columns - 1)
204         HasRowWithSufficientColumns = true;
205       unsigned length =
206           (Column == Columns - 1) ? EndOfLineItemLength[i] : ItemLengths[i];
207       Format.ColumnSizes[Column] =
208           std::max(Format.ColumnSizes[Column], length);
209       ++Column;
210     }
211     // If all rows are terminated early (e.g. by trailing comments), we don't
212     // need to look further.
213     if (!HasRowWithSufficientColumns)
214       break;
215     Format.TotalWidth = Columns - 1; // Width of the N-1 spaces.
216     for (unsigned i = 0; i < Columns; ++i) {
217       Format.TotalWidth += Format.ColumnSizes[i];
218     }
219 
220     // Ignore layouts that are bound to violate the column limit.
221     if (Format.TotalWidth > Style.ColumnLimit)
222       continue;
223 
224     Formats.push_back(Format);
225   }
226 }
227 
228 const CommaSeparatedList::ColumnFormat *
229 CommaSeparatedList::getColumnFormat(unsigned RemainingCharacters) const {
230   const ColumnFormat *BestFormat = NULL;
231   for (SmallVector<ColumnFormat, 4>::const_reverse_iterator
232            I = Formats.rbegin(),
233            E = Formats.rend();
234        I != E; ++I) {
235     if (I->TotalWidth <= RemainingCharacters) {
236       if (BestFormat && I->LineCount > BestFormat->LineCount)
237         break;
238       BestFormat = &*I;
239     }
240   }
241   return BestFormat;
242 }
243 
244 } // namespace format
245 } // namespace clang
246