Path: blob/main/contrib/llvm-project/clang/lib/Format/FormatToken.cpp
35232 views
//===--- FormatToken.cpp - Format C++ code --------------------------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//7///8/// \file9/// This file implements specific functions of \c FormatTokens and their10/// roles.11///12//===----------------------------------------------------------------------===//1314#include "FormatToken.h"15#include "ContinuationIndenter.h"16#include "llvm/ADT/SmallVector.h"17#include "llvm/Support/Debug.h"18#include <climits>1920namespace clang {21namespace format {2223const char *getTokenTypeName(TokenType Type) {24static const char *const TokNames[] = {25#define TYPE(X) #X,26LIST_TOKEN_TYPES27#undef TYPE28nullptr};2930if (Type < NUM_TOKEN_TYPES)31return TokNames[Type];32llvm_unreachable("unknown TokenType");33return nullptr;34}3536// Sorted common C++ non-keyword types.37static SmallVector<StringRef> CppNonKeywordTypes = {38"clock_t", "int16_t", "int32_t", "int64_t", "int8_t",39"intptr_t", "ptrdiff_t", "size_t", "time_t", "uint16_t",40"uint32_t", "uint64_t", "uint8_t", "uintptr_t",41};4243bool FormatToken::isTypeName(const LangOptions &LangOpts) const {44const bool IsCpp = LangOpts.CXXOperatorNames;45return is(TT_TypeName) || Tok.isSimpleTypeSpecifier(LangOpts) ||46(IsCpp && is(tok::identifier) &&47std::binary_search(CppNonKeywordTypes.begin(),48CppNonKeywordTypes.end(), TokenText));49}5051bool FormatToken::isTypeOrIdentifier(const LangOptions &LangOpts) const {52return isTypeName(LangOpts) || isOneOf(tok::kw_auto, tok::identifier);53}5455bool FormatToken::isBlockIndentedInitRBrace(const FormatStyle &Style) const {56assert(is(tok::r_brace));57if (!Style.Cpp11BracedListStyle ||58Style.AlignAfterOpenBracket != FormatStyle::BAS_BlockIndent) {59return false;60}61const auto *LBrace = MatchingParen;62assert(LBrace && LBrace->is(tok::l_brace));63if (LBrace->is(BK_BracedInit))64return true;65if (LBrace->Previous && LBrace->Previous->is(tok::equal))66return true;67return false;68}6970bool FormatToken::opensBlockOrBlockTypeList(const FormatStyle &Style) const {71// C# Does not indent object initialisers as continuations.72if (is(tok::l_brace) && getBlockKind() == BK_BracedInit && Style.isCSharp())73return true;74if (is(TT_TemplateString) && opensScope())75return true;76return is(TT_ArrayInitializerLSquare) || is(TT_ProtoExtensionLSquare) ||77(is(tok::l_brace) &&78(getBlockKind() == BK_Block || is(TT_DictLiteral) ||79(!Style.Cpp11BracedListStyle && NestingLevel == 0))) ||80(is(tok::less) && Style.isProto());81}8283TokenRole::~TokenRole() {}8485void TokenRole::precomputeFormattingInfos(const FormatToken *Token) {}8687unsigned CommaSeparatedList::formatAfterToken(LineState &State,88ContinuationIndenter *Indenter,89bool DryRun) {90if (!State.NextToken || !State.NextToken->Previous)91return 0;9293if (Formats.size() <= 1)94return 0; // Handled by formatFromToken (1) or avoid severe penalty (0).9596// Ensure that we start on the opening brace.97const FormatToken *LBrace =98State.NextToken->Previous->getPreviousNonComment();99if (!LBrace || !LBrace->isOneOf(tok::l_brace, TT_ArrayInitializerLSquare) ||100LBrace->is(BK_Block) || LBrace->is(TT_DictLiteral) ||101LBrace->Next->is(TT_DesignatedInitializerPeriod)) {102return 0;103}104105// Calculate the number of code points we have to format this list. As the106// first token is already placed, we have to subtract it.107unsigned RemainingCodePoints =108Style.ColumnLimit - State.Column + State.NextToken->Previous->ColumnWidth;109110// Find the best ColumnFormat, i.e. the best number of columns to use.111const ColumnFormat *Format = getColumnFormat(RemainingCodePoints);112113// If no ColumnFormat can be used, the braced list would generally be114// bin-packed. Add a severe penalty to this so that column layouts are115// preferred if possible.116if (!Format)117return 10'000;118119// Format the entire list.120unsigned Penalty = 0;121unsigned Column = 0;122unsigned Item = 0;123while (State.NextToken != LBrace->MatchingParen) {124bool NewLine = false;125unsigned ExtraSpaces = 0;126127// If the previous token was one of our commas, we are now on the next item.128if (Item < Commas.size() && State.NextToken->Previous == Commas[Item]) {129if (!State.NextToken->isTrailingComment()) {130ExtraSpaces += Format->ColumnSizes[Column] - ItemLengths[Item];131++Column;132}133++Item;134}135136if (Column == Format->Columns || State.NextToken->MustBreakBefore) {137Column = 0;138NewLine = true;139}140141// Place token using the continuation indenter and store the penalty.142Penalty += Indenter->addTokenToState(State, NewLine, DryRun, ExtraSpaces);143}144return Penalty;145}146147unsigned CommaSeparatedList::formatFromToken(LineState &State,148ContinuationIndenter *Indenter,149bool DryRun) {150// Formatting with 1 Column isn't really a column layout, so we don't need the151// special logic here. We can just avoid bin packing any of the parameters.152if (Formats.size() == 1 || HasNestedBracedList)153State.Stack.back().AvoidBinPacking = true;154return 0;155}156157// Returns the lengths in code points between Begin and End (both included),158// assuming that the entire sequence is put on a single line.159static unsigned CodePointsBetween(const FormatToken *Begin,160const FormatToken *End) {161assert(End->TotalLength >= Begin->TotalLength);162return End->TotalLength - Begin->TotalLength + Begin->ColumnWidth;163}164165void CommaSeparatedList::precomputeFormattingInfos(const FormatToken *Token) {166// FIXME: At some point we might want to do this for other lists, too.167if (!Token->MatchingParen ||168!Token->isOneOf(tok::l_brace, TT_ArrayInitializerLSquare)) {169return;170}171172// In C++11 braced list style, we should not format in columns unless they173// have many items (20 or more) or we allow bin-packing of function call174// arguments.175if (Style.Cpp11BracedListStyle && !Style.BinPackArguments &&176Commas.size() < 19) {177return;178}179180// Limit column layout for JavaScript array initializers to 20 or more items181// for now to introduce it carefully. We can become more aggressive if this182// necessary.183if (Token->is(TT_ArrayInitializerLSquare) && Commas.size() < 19)184return;185186// Column format doesn't really make sense if we don't align after brackets.187if (Style.AlignAfterOpenBracket == FormatStyle::BAS_DontAlign)188return;189190FormatToken *ItemBegin = Token->Next;191while (ItemBegin->isTrailingComment())192ItemBegin = ItemBegin->Next;193SmallVector<bool, 8> MustBreakBeforeItem;194195// The lengths of an item if it is put at the end of the line. This includes196// trailing comments which are otherwise ignored for column alignment.197SmallVector<unsigned, 8> EndOfLineItemLength;198MustBreakBeforeItem.reserve(Commas.size() + 1);199EndOfLineItemLength.reserve(Commas.size() + 1);200ItemLengths.reserve(Commas.size() + 1);201202bool HasSeparatingComment = false;203for (unsigned i = 0, e = Commas.size() + 1; i != e; ++i) {204assert(ItemBegin);205// Skip comments on their own line.206while (ItemBegin->HasUnescapedNewline && ItemBegin->isTrailingComment()) {207ItemBegin = ItemBegin->Next;208HasSeparatingComment = i > 0;209}210211MustBreakBeforeItem.push_back(ItemBegin->MustBreakBefore);212if (ItemBegin->is(tok::l_brace))213HasNestedBracedList = true;214const FormatToken *ItemEnd = nullptr;215if (i == Commas.size()) {216ItemEnd = Token->MatchingParen;217const FormatToken *NonCommentEnd = ItemEnd->getPreviousNonComment();218ItemLengths.push_back(CodePointsBetween(ItemBegin, NonCommentEnd));219if (Style.Cpp11BracedListStyle &&220!ItemEnd->Previous->isTrailingComment()) {221// In Cpp11 braced list style, the } and possibly other subsequent222// tokens will need to stay on a line with the last element.223while (ItemEnd->Next && !ItemEnd->Next->CanBreakBefore)224ItemEnd = ItemEnd->Next;225} else {226// In other braced lists styles, the "}" can be wrapped to the new line.227ItemEnd = Token->MatchingParen->Previous;228}229} else {230ItemEnd = Commas[i];231// The comma is counted as part of the item when calculating the length.232ItemLengths.push_back(CodePointsBetween(ItemBegin, ItemEnd));233234// Consume trailing comments so the are included in EndOfLineItemLength.235if (ItemEnd->Next && !ItemEnd->Next->HasUnescapedNewline &&236ItemEnd->Next->isTrailingComment()) {237ItemEnd = ItemEnd->Next;238}239}240EndOfLineItemLength.push_back(CodePointsBetween(ItemBegin, ItemEnd));241// If there is a trailing comma in the list, the next item will start at the242// closing brace. Don't create an extra item for this.243if (ItemEnd->getNextNonComment() == Token->MatchingParen)244break;245ItemBegin = ItemEnd->Next;246}247248// Don't use column layout for lists with few elements and in presence of249// separating comments.250if (Commas.size() < 5 || HasSeparatingComment)251return;252253if (Token->NestingLevel != 0 && Token->is(tok::l_brace) && Commas.size() < 19)254return;255256// We can never place more than ColumnLimit / 3 items in a row (because of the257// spaces and the comma).258unsigned MaxItems = Style.ColumnLimit / 3;259SmallVector<unsigned> MinSizeInColumn;260MinSizeInColumn.reserve(MaxItems);261for (unsigned Columns = 1; Columns <= MaxItems; ++Columns) {262ColumnFormat Format;263Format.Columns = Columns;264Format.ColumnSizes.resize(Columns);265MinSizeInColumn.assign(Columns, UINT_MAX);266Format.LineCount = 1;267bool HasRowWithSufficientColumns = false;268unsigned Column = 0;269for (unsigned i = 0, e = ItemLengths.size(); i != e; ++i) {270assert(i < MustBreakBeforeItem.size());271if (MustBreakBeforeItem[i] || Column == Columns) {272++Format.LineCount;273Column = 0;274}275if (Column == Columns - 1)276HasRowWithSufficientColumns = true;277unsigned Length =278(Column == Columns - 1) ? EndOfLineItemLength[i] : ItemLengths[i];279Format.ColumnSizes[Column] = std::max(Format.ColumnSizes[Column], Length);280MinSizeInColumn[Column] = std::min(MinSizeInColumn[Column], Length);281++Column;282}283// If all rows are terminated early (e.g. by trailing comments), we don't284// need to look further.285if (!HasRowWithSufficientColumns)286break;287Format.TotalWidth = Columns - 1; // Width of the N-1 spaces.288289for (unsigned i = 0; i < Columns; ++i)290Format.TotalWidth += Format.ColumnSizes[i];291292// Don't use this Format, if the difference between the longest and shortest293// element in a column exceeds a threshold to avoid excessive spaces.294if ([&] {295for (unsigned i = 0; i < Columns - 1; ++i)296if (Format.ColumnSizes[i] - MinSizeInColumn[i] > 10)297return true;298return false;299}()) {300continue;301}302303// Ignore layouts that are bound to violate the column limit.304if (Format.TotalWidth > Style.ColumnLimit && Columns > 1)305continue;306307Formats.push_back(Format);308}309}310311const CommaSeparatedList::ColumnFormat *312CommaSeparatedList::getColumnFormat(unsigned RemainingCharacters) const {313const ColumnFormat *BestFormat = nullptr;314for (const ColumnFormat &Format : llvm::reverse(Formats)) {315if (Format.TotalWidth <= RemainingCharacters || Format.Columns == 1) {316if (BestFormat && Format.LineCount > BestFormat->LineCount)317break;318BestFormat = &Format;319}320}321return BestFormat;322}323324} // namespace format325} // namespace clang326327328