1 //===--- FormatToken.cpp - Format C++ code --------------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 /// 9 /// \file 10 /// This file implements specific functions of \c FormatTokens and their 11 /// roles. 12 /// 13 //===----------------------------------------------------------------------===// 14 15 #include "FormatToken.h" 16 #include "ContinuationIndenter.h" 17 #include "llvm/ADT/SmallVector.h" 18 #include "llvm/Support/Debug.h" 19 #include <climits> 20 21 namespace clang { 22 namespace format { 23 24 const char *getTokenTypeName(TokenType Type) { 25 static const char *const TokNames[] = { 26 #define TYPE(X) #X, 27 LIST_TOKEN_TYPES 28 #undef TYPE 29 nullptr}; 30 31 if (Type < NUM_TOKEN_TYPES) 32 return TokNames[Type]; 33 llvm_unreachable("unknown TokenType"); 34 return nullptr; 35 } 36 37 // FIXME: This is copy&pasted from Sema. Put it in a common place and remove 38 // duplication. 39 bool FormatToken::isSimpleTypeSpecifier() const { 40 switch (Tok.getKind()) { 41 case tok::kw_short: 42 case tok::kw_long: 43 case tok::kw___int64: 44 case tok::kw___int128: 45 case tok::kw_signed: 46 case tok::kw_unsigned: 47 case tok::kw_void: 48 case tok::kw_char: 49 case tok::kw_int: 50 case tok::kw_half: 51 case tok::kw_float: 52 case tok::kw_double: 53 case tok::kw___bf16: 54 case tok::kw__Float16: 55 case tok::kw___float128: 56 case tok::kw___ibm128: 57 case tok::kw_wchar_t: 58 case tok::kw_bool: 59 case tok::kw___underlying_type: 60 case tok::annot_typename: 61 case tok::kw_char8_t: 62 case tok::kw_char16_t: 63 case tok::kw_char32_t: 64 case tok::kw_typeof: 65 case tok::kw_decltype: 66 case tok::kw__Atomic: 67 return true; 68 default: 69 return false; 70 } 71 } 72 73 bool FormatToken::isTypeOrIdentifier() const { 74 return isSimpleTypeSpecifier() || Tok.isOneOf(tok::kw_auto, tok::identifier); 75 } 76 77 TokenRole::~TokenRole() {} 78 79 void TokenRole::precomputeFormattingInfos(const FormatToken *Token) {} 80 81 unsigned CommaSeparatedList::formatAfterToken(LineState &State, 82 ContinuationIndenter *Indenter, 83 bool DryRun) { 84 if (State.NextToken == nullptr || !State.NextToken->Previous) 85 return 0; 86 87 if (Formats.size() == 1) 88 return 0; // Handled by formatFromToken 89 90 // Ensure that we start on the opening brace. 91 const FormatToken *LBrace = 92 State.NextToken->Previous->getPreviousNonComment(); 93 if (!LBrace || !LBrace->isOneOf(tok::l_brace, TT_ArrayInitializerLSquare) || 94 LBrace->is(BK_Block) || LBrace->is(TT_DictLiteral) || 95 LBrace->Next->is(TT_DesignatedInitializerPeriod)) 96 return 0; 97 98 // Calculate the number of code points we have to format this list. As the 99 // first token is already placed, we have to subtract it. 100 unsigned RemainingCodePoints = 101 Style.ColumnLimit - State.Column + State.NextToken->Previous->ColumnWidth; 102 103 // Find the best ColumnFormat, i.e. the best number of columns to use. 104 const ColumnFormat *Format = getColumnFormat(RemainingCodePoints); 105 106 // If no ColumnFormat can be used, the braced list would generally be 107 // bin-packed. Add a severe penalty to this so that column layouts are 108 // preferred if possible. 109 if (!Format) 110 return 10000; 111 112 // Format the entire list. 113 unsigned Penalty = 0; 114 unsigned Column = 0; 115 unsigned Item = 0; 116 while (State.NextToken != LBrace->MatchingParen) { 117 bool NewLine = false; 118 unsigned ExtraSpaces = 0; 119 120 // If the previous token was one of our commas, we are now on the next item. 121 if (Item < Commas.size() && State.NextToken->Previous == Commas[Item]) { 122 if (!State.NextToken->isTrailingComment()) { 123 ExtraSpaces += Format->ColumnSizes[Column] - ItemLengths[Item]; 124 ++Column; 125 } 126 ++Item; 127 } 128 129 if (Column == Format->Columns || State.NextToken->MustBreakBefore) { 130 Column = 0; 131 NewLine = true; 132 } 133 134 // Place token using the continuation indenter and store the penalty. 135 Penalty += Indenter->addTokenToState(State, NewLine, DryRun, ExtraSpaces); 136 } 137 return Penalty; 138 } 139 140 unsigned CommaSeparatedList::formatFromToken(LineState &State, 141 ContinuationIndenter *Indenter, 142 bool DryRun) { 143 // Formatting with 1 Column isn't really a column layout, so we don't need the 144 // special logic here. We can just avoid bin packing any of the parameters. 145 if (Formats.size() == 1 || HasNestedBracedList) 146 State.Stack.back().AvoidBinPacking = true; 147 return 0; 148 } 149 150 // Returns the lengths in code points between Begin and End (both included), 151 // assuming that the entire sequence is put on a single line. 152 static unsigned CodePointsBetween(const FormatToken *Begin, 153 const FormatToken *End) { 154 assert(End->TotalLength >= Begin->TotalLength); 155 return End->TotalLength - Begin->TotalLength + Begin->ColumnWidth; 156 } 157 158 void CommaSeparatedList::precomputeFormattingInfos(const FormatToken *Token) { 159 // FIXME: At some point we might want to do this for other lists, too. 160 if (!Token->MatchingParen || 161 !Token->isOneOf(tok::l_brace, TT_ArrayInitializerLSquare)) 162 return; 163 164 // In C++11 braced list style, we should not format in columns unless they 165 // have many items (20 or more) or we allow bin-packing of function call 166 // arguments. 167 if (Style.Cpp11BracedListStyle && !Style.BinPackArguments && 168 Commas.size() < 19) 169 return; 170 171 // Limit column layout for JavaScript array initializers to 20 or more items 172 // for now to introduce it carefully. We can become more aggressive if this 173 // necessary. 174 if (Token->is(TT_ArrayInitializerLSquare) && Commas.size() < 19) 175 return; 176 177 // Column format doesn't really make sense if we don't align after brackets. 178 if (Style.AlignAfterOpenBracket == FormatStyle::BAS_DontAlign) 179 return; 180 181 FormatToken *ItemBegin = Token->Next; 182 while (ItemBegin->isTrailingComment()) 183 ItemBegin = ItemBegin->Next; 184 SmallVector<bool, 8> MustBreakBeforeItem; 185 186 // The lengths of an item if it is put at the end of the line. This includes 187 // trailing comments which are otherwise ignored for column alignment. 188 SmallVector<unsigned, 8> EndOfLineItemLength; 189 190 bool HasSeparatingComment = false; 191 for (unsigned i = 0, e = Commas.size() + 1; i != e; ++i) { 192 // Skip comments on their own line. 193 while (ItemBegin->HasUnescapedNewline && ItemBegin->isTrailingComment()) { 194 ItemBegin = ItemBegin->Next; 195 HasSeparatingComment = i > 0; 196 } 197 198 MustBreakBeforeItem.push_back(ItemBegin->MustBreakBefore); 199 if (ItemBegin->is(tok::l_brace)) 200 HasNestedBracedList = true; 201 const FormatToken *ItemEnd = nullptr; 202 if (i == Commas.size()) { 203 ItemEnd = Token->MatchingParen; 204 const FormatToken *NonCommentEnd = ItemEnd->getPreviousNonComment(); 205 ItemLengths.push_back(CodePointsBetween(ItemBegin, NonCommentEnd)); 206 if (Style.Cpp11BracedListStyle && 207 !ItemEnd->Previous->isTrailingComment()) { 208 // In Cpp11 braced list style, the } and possibly other subsequent 209 // tokens will need to stay on a line with the last element. 210 while (ItemEnd->Next && !ItemEnd->Next->CanBreakBefore) 211 ItemEnd = ItemEnd->Next; 212 } else { 213 // In other braced lists styles, the "}" can be wrapped to the new line. 214 ItemEnd = Token->MatchingParen->Previous; 215 } 216 } else { 217 ItemEnd = Commas[i]; 218 // The comma is counted as part of the item when calculating the length. 219 ItemLengths.push_back(CodePointsBetween(ItemBegin, ItemEnd)); 220 221 // Consume trailing comments so the are included in EndOfLineItemLength. 222 if (ItemEnd->Next && !ItemEnd->Next->HasUnescapedNewline && 223 ItemEnd->Next->isTrailingComment()) 224 ItemEnd = ItemEnd->Next; 225 } 226 EndOfLineItemLength.push_back(CodePointsBetween(ItemBegin, ItemEnd)); 227 // If there is a trailing comma in the list, the next item will start at the 228 // closing brace. Don't create an extra item for this. 229 if (ItemEnd->getNextNonComment() == Token->MatchingParen) 230 break; 231 ItemBegin = ItemEnd->Next; 232 } 233 234 // Don't use column layout for lists with few elements and in presence of 235 // separating comments. 236 if (Commas.size() < 5 || HasSeparatingComment) 237 return; 238 239 if (Token->NestingLevel != 0 && Token->is(tok::l_brace) && Commas.size() < 19) 240 return; 241 242 // We can never place more than ColumnLimit / 3 items in a row (because of the 243 // spaces and the comma). 244 unsigned MaxItems = Style.ColumnLimit / 3; 245 std::vector<unsigned> MinSizeInColumn; 246 MinSizeInColumn.reserve(MaxItems); 247 for (unsigned Columns = 1; Columns <= MaxItems; ++Columns) { 248 ColumnFormat Format; 249 Format.Columns = Columns; 250 Format.ColumnSizes.resize(Columns); 251 MinSizeInColumn.assign(Columns, UINT_MAX); 252 Format.LineCount = 1; 253 bool HasRowWithSufficientColumns = false; 254 unsigned Column = 0; 255 for (unsigned i = 0, e = ItemLengths.size(); i != e; ++i) { 256 assert(i < MustBreakBeforeItem.size()); 257 if (MustBreakBeforeItem[i] || Column == Columns) { 258 ++Format.LineCount; 259 Column = 0; 260 } 261 if (Column == Columns - 1) 262 HasRowWithSufficientColumns = true; 263 unsigned Length = 264 (Column == Columns - 1) ? EndOfLineItemLength[i] : ItemLengths[i]; 265 Format.ColumnSizes[Column] = std::max(Format.ColumnSizes[Column], Length); 266 MinSizeInColumn[Column] = std::min(MinSizeInColumn[Column], Length); 267 ++Column; 268 } 269 // If all rows are terminated early (e.g. by trailing comments), we don't 270 // need to look further. 271 if (!HasRowWithSufficientColumns) 272 break; 273 Format.TotalWidth = Columns - 1; // Width of the N-1 spaces. 274 275 for (unsigned i = 0; i < Columns; ++i) 276 Format.TotalWidth += Format.ColumnSizes[i]; 277 278 // Don't use this Format, if the difference between the longest and shortest 279 // element in a column exceeds a threshold to avoid excessive spaces. 280 if ([&] { 281 for (unsigned i = 0; i < Columns - 1; ++i) 282 if (Format.ColumnSizes[i] - MinSizeInColumn[i] > 10) 283 return true; 284 return false; 285 }()) 286 continue; 287 288 // Ignore layouts that are bound to violate the column limit. 289 if (Format.TotalWidth > Style.ColumnLimit && Columns > 1) 290 continue; 291 292 Formats.push_back(Format); 293 } 294 } 295 296 const CommaSeparatedList::ColumnFormat * 297 CommaSeparatedList::getColumnFormat(unsigned RemainingCharacters) const { 298 const ColumnFormat *BestFormat = nullptr; 299 for (SmallVector<ColumnFormat, 4>::const_reverse_iterator 300 I = Formats.rbegin(), 301 E = Formats.rend(); 302 I != E; ++I) { 303 if (I->TotalWidth <= RemainingCharacters || I->Columns == 1) { 304 if (BestFormat && I->LineCount > BestFormat->LineCount) 305 break; 306 BestFormat = &*I; 307 } 308 } 309 return BestFormat; 310 } 311 312 } // namespace format 313 } // namespace clang 314