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