FormatToken.cpp revision d4a03dbb0bdbd4908375306283cb61813bd8f454
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->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) {
95    // Skip comments on their own line.
96    while (ItemBegin->HasUnescapedNewline && ItemBegin->isTrailingComment())
97      ItemBegin = ItemBegin->Next;
98
99    MustBreakBeforeItem.push_back(ItemBegin->MustBreakBefore);
100    const FormatToken *ItemEnd = NULL;
101    if (i == Commas.size()) {
102      ItemEnd = Token->MatchingParen;
103      const FormatToken *NonCommentEnd = ItemEnd->getPreviousNonComment();
104      ItemLengths.push_back(CodePointsBetween(ItemBegin, NonCommentEnd));
105      if (Style.Cpp11BracedListStyle) {
106        // In Cpp11 braced list style, the } and possibly other subsequent
107        // tokens will need to stay on a line with the last element.
108        while (ItemEnd->Next && !ItemEnd->Next->CanBreakBefore)
109          ItemEnd = ItemEnd->Next;
110      } else {
111        // In other braced lists styles, the "}" can be wrapped to the new line.
112        ItemEnd = Token->MatchingParen->Previous;
113      }
114    } else {
115      ItemEnd = Commas[i];
116      // The comma is counted as part of the item when calculating the length.
117      ItemLengths.push_back(ItemEnd->TotalLength - ItemBegin->TotalLength +
118                            ItemBegin->CodePointCount);
119      // Consume trailing comments so the are included in EndOfLineItemLength.
120      if (ItemEnd->Next && !ItemEnd->Next->HasUnescapedNewline &&
121          ItemEnd->Next->isTrailingComment())
122        ItemEnd = ItemEnd->Next;
123    }
124    EndOfLineItemLength.push_back(CodePointsBetween(ItemBegin, ItemEnd));
125    ItemBegin = ItemEnd->Next;
126  }
127
128  // We can never place more than ColumnLimit / 3 items in a row (because of the
129  // spaces and the comma).
130  for (unsigned Columns = 1; Columns <= Style.ColumnLimit / 3; ++Columns) {
131    ColumnFormat Format;
132    Format.Columns = Columns;
133    Format.ColumnSizes.resize(Columns);
134    Format.LineCount = 0;
135    bool HasRowWithSufficientColumns = false;
136    unsigned Column = 0;
137    for (unsigned i = 0, e = ItemLengths.size(); i != e; ++i) {
138      if (MustBreakBeforeItem[i] || Column == Columns) {
139        ++Format.LineCount;
140        Column = 0;
141      }
142      if (Column == Columns - 1)
143        HasRowWithSufficientColumns = true;
144      unsigned length =
145          (Column == Columns - 1) ? EndOfLineItemLength[i] : ItemLengths[i];
146      Format.ColumnSizes[Column] =
147          std::max(Format.ColumnSizes[Column], length);
148      ++Column;
149    }
150    // If all rows are terminated early (e.g. by trailing comments), we don't
151    // need to look further.
152    if (!HasRowWithSufficientColumns)
153      break;
154    Format.TotalWidth = Columns - 1; // Width of the N-1 spaces.
155    for (unsigned i = 0; i < Columns; ++i) {
156      Format.TotalWidth += Format.ColumnSizes[i];
157    }
158
159    // Ignore layouts that are bound to violate the column limit.
160    if (Format.TotalWidth > Style.ColumnLimit)
161      continue;
162
163    Formats.push_back(Format);
164  }
165}
166
167const CommaSeparatedList::ColumnFormat *
168CommaSeparatedList::getColumnFormat(unsigned RemainingCharacters) const {
169  const ColumnFormat *BestFormat = NULL;
170  for (SmallVector<ColumnFormat, 4>::const_reverse_iterator
171           I = Formats.rbegin(),
172           E = Formats.rend();
173       I != E; ++I) {
174    if (I->TotalWidth <= RemainingCharacters) {
175      if (BestFormat && I->LineCount > BestFormat->LineCount)
176        break;
177      BestFormat = &*I;
178    }
179  }
180  return BestFormat;
181}
182
183} // namespace format
184} // namespace clang
185