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
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->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 (!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) {
86  assert(End->TotalLength >= Begin->TotalLength);
87  return End->TotalLength - Begin->TotalLength + Begin->ColumnWidth;
88}
89
90void CommaSeparatedList::precomputeFormattingInfos(const FormatToken *Token) {
91  // FIXME: At some point we might want to do this for other lists, too.
92  if (!Token->MatchingParen || Token->isNot(tok::l_brace))
93    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  bool HasNestedBracedList = false;
103  for (unsigned i = 0, e = Commas.size() + 1; i != e; ++i) {
104    // Skip comments on their own line.
105    while (ItemBegin->HasUnescapedNewline && ItemBegin->isTrailingComment())
106      ItemBegin = ItemBegin->Next;
107
108    MustBreakBeforeItem.push_back(ItemBegin->MustBreakBefore);
109    if (ItemBegin->is(tok::l_brace))
110      HasNestedBracedList = true;
111    const FormatToken *ItemEnd = NULL;
112    if (i == Commas.size()) {
113      ItemEnd = Token->MatchingParen;
114      const FormatToken *NonCommentEnd = ItemEnd->getPreviousNonComment();
115      ItemLengths.push_back(CodePointsBetween(ItemBegin, NonCommentEnd));
116      if (Style.Cpp11BracedListStyle) {
117        // In Cpp11 braced list style, the } and possibly other subsequent
118        // tokens will need to stay on a line with the last element.
119        while (ItemEnd->Next && !ItemEnd->Next->CanBreakBefore)
120          ItemEnd = ItemEnd->Next;
121      } else {
122        // In other braced lists styles, the "}" can be wrapped to the new line.
123        ItemEnd = Token->MatchingParen->Previous;
124      }
125    } else {
126      ItemEnd = Commas[i];
127      // The comma is counted as part of the item when calculating the length.
128      ItemLengths.push_back(CodePointsBetween(ItemBegin, ItemEnd));
129      // Consume trailing comments so the are included in EndOfLineItemLength.
130      if (ItemEnd->Next && !ItemEnd->Next->HasUnescapedNewline &&
131          ItemEnd->Next->isTrailingComment())
132        ItemEnd = ItemEnd->Next;
133    }
134    EndOfLineItemLength.push_back(CodePointsBetween(ItemBegin, ItemEnd));
135    // If there is a trailing comma in the list, the next item will start at the
136    // closing brace. Don't create an extra item for this.
137    if (ItemEnd->getNextNonComment() == Token->MatchingParen)
138      break;
139    ItemBegin = ItemEnd->Next;
140  }
141
142  // We can never place more than ColumnLimit / 3 items in a row (because of the
143  // spaces and the comma).
144  for (unsigned Columns = 1; Columns <= Style.ColumnLimit / 3; ++Columns) {
145    ColumnFormat Format;
146    Format.Columns = Columns;
147    Format.ColumnSizes.resize(Columns);
148    Format.LineCount = 1;
149    bool HasRowWithSufficientColumns = false;
150    unsigned Column = 0;
151    for (unsigned i = 0, e = ItemLengths.size(); i != e; ++i) {
152      assert(i < MustBreakBeforeItem.size());
153      if (MustBreakBeforeItem[i] || Column == Columns) {
154        ++Format.LineCount;
155        Column = 0;
156      }
157      if (Column == Columns - 1)
158        HasRowWithSufficientColumns = true;
159      unsigned length =
160          (Column == Columns - 1) ? EndOfLineItemLength[i] : ItemLengths[i];
161      Format.ColumnSizes[Column] =
162          std::max(Format.ColumnSizes[Column], length);
163      ++Column;
164    }
165    // If all rows are terminated early (e.g. by trailing comments), we don't
166    // need to look further.
167    if (!HasRowWithSufficientColumns)
168      break;
169    Format.TotalWidth = Columns - 1; // Width of the N-1 spaces.
170    for (unsigned i = 0; i < Columns; ++i) {
171      Format.TotalWidth += Format.ColumnSizes[i];
172    }
173
174    // Ignore layouts that are bound to violate the column limit.
175    if (Format.TotalWidth > Style.ColumnLimit)
176      continue;
177
178    // If this braced list has nested braced list, we format it either with one
179    // element per line or with all elements on one line.
180    if (HasNestedBracedList && Columns > 1 && Format.LineCount > 1)
181      continue;
182
183    Formats.push_back(Format);
184  }
185}
186
187const CommaSeparatedList::ColumnFormat *
188CommaSeparatedList::getColumnFormat(unsigned RemainingCharacters) const {
189  const ColumnFormat *BestFormat = NULL;
190  for (SmallVector<ColumnFormat, 4>::const_reverse_iterator
191           I = Formats.rbegin(),
192           E = Formats.rend();
193       I != E; ++I) {
194    if (I->TotalWidth <= RemainingCharacters) {
195      if (BestFormat && I->LineCount > BestFormat->LineCount)
196        break;
197      BestFormat = &*I;
198    }
199  }
200  return BestFormat;
201}
202
203} // namespace format
204} // namespace clang
205