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