17330f729Sjoerg //===--- FormatToken.cpp - Format C++ code --------------------------------===//
27330f729Sjoerg //
37330f729Sjoerg // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
47330f729Sjoerg // See https://llvm.org/LICENSE.txt for license information.
57330f729Sjoerg // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
67330f729Sjoerg //
77330f729Sjoerg //===----------------------------------------------------------------------===//
87330f729Sjoerg ///
97330f729Sjoerg /// \file
107330f729Sjoerg /// This file implements specific functions of \c FormatTokens and their
117330f729Sjoerg /// roles.
127330f729Sjoerg ///
137330f729Sjoerg //===----------------------------------------------------------------------===//
147330f729Sjoerg
157330f729Sjoerg #include "FormatToken.h"
167330f729Sjoerg #include "ContinuationIndenter.h"
177330f729Sjoerg #include "llvm/ADT/SmallVector.h"
187330f729Sjoerg #include "llvm/Support/Debug.h"
197330f729Sjoerg #include <climits>
207330f729Sjoerg
217330f729Sjoerg namespace clang {
227330f729Sjoerg namespace format {
237330f729Sjoerg
getTokenTypeName(TokenType Type)247330f729Sjoerg const char *getTokenTypeName(TokenType Type) {
257330f729Sjoerg static const char *const TokNames[] = {
267330f729Sjoerg #define TYPE(X) #X,
277330f729Sjoerg LIST_TOKEN_TYPES
287330f729Sjoerg #undef TYPE
297330f729Sjoerg nullptr};
307330f729Sjoerg
317330f729Sjoerg if (Type < NUM_TOKEN_TYPES)
327330f729Sjoerg return TokNames[Type];
337330f729Sjoerg llvm_unreachable("unknown TokenType");
347330f729Sjoerg return nullptr;
357330f729Sjoerg }
367330f729Sjoerg
377330f729Sjoerg // FIXME: This is copy&pasted from Sema. Put it in a common place and remove
387330f729Sjoerg // duplication.
isSimpleTypeSpecifier() const397330f729Sjoerg bool FormatToken::isSimpleTypeSpecifier() const {
407330f729Sjoerg switch (Tok.getKind()) {
417330f729Sjoerg case tok::kw_short:
427330f729Sjoerg case tok::kw_long:
437330f729Sjoerg case tok::kw___int64:
447330f729Sjoerg case tok::kw___int128:
457330f729Sjoerg case tok::kw_signed:
467330f729Sjoerg case tok::kw_unsigned:
477330f729Sjoerg case tok::kw_void:
487330f729Sjoerg case tok::kw_char:
497330f729Sjoerg case tok::kw_int:
507330f729Sjoerg case tok::kw_half:
517330f729Sjoerg case tok::kw_float:
527330f729Sjoerg case tok::kw_double:
53*e038c9c4Sjoerg case tok::kw___bf16:
547330f729Sjoerg case tok::kw__Float16:
557330f729Sjoerg case tok::kw___float128:
567330f729Sjoerg case tok::kw_wchar_t:
577330f729Sjoerg case tok::kw_bool:
587330f729Sjoerg case tok::kw___underlying_type:
597330f729Sjoerg case tok::annot_typename:
607330f729Sjoerg case tok::kw_char8_t:
617330f729Sjoerg case tok::kw_char16_t:
627330f729Sjoerg case tok::kw_char32_t:
637330f729Sjoerg case tok::kw_typeof:
647330f729Sjoerg case tok::kw_decltype:
65*e038c9c4Sjoerg case tok::kw__Atomic:
667330f729Sjoerg return true;
677330f729Sjoerg default:
687330f729Sjoerg return false;
697330f729Sjoerg }
707330f729Sjoerg }
717330f729Sjoerg
~TokenRole()727330f729Sjoerg TokenRole::~TokenRole() {}
737330f729Sjoerg
precomputeFormattingInfos(const FormatToken * Token)747330f729Sjoerg void TokenRole::precomputeFormattingInfos(const FormatToken *Token) {}
757330f729Sjoerg
formatAfterToken(LineState & State,ContinuationIndenter * Indenter,bool DryRun)767330f729Sjoerg unsigned CommaSeparatedList::formatAfterToken(LineState &State,
777330f729Sjoerg ContinuationIndenter *Indenter,
787330f729Sjoerg bool DryRun) {
797330f729Sjoerg if (State.NextToken == nullptr || !State.NextToken->Previous)
807330f729Sjoerg return 0;
817330f729Sjoerg
827330f729Sjoerg if (Formats.size() == 1)
837330f729Sjoerg return 0; // Handled by formatFromToken
847330f729Sjoerg
857330f729Sjoerg // Ensure that we start on the opening brace.
867330f729Sjoerg const FormatToken *LBrace =
877330f729Sjoerg State.NextToken->Previous->getPreviousNonComment();
887330f729Sjoerg if (!LBrace || !LBrace->isOneOf(tok::l_brace, TT_ArrayInitializerLSquare) ||
89*e038c9c4Sjoerg LBrace->is(BK_Block) || LBrace->is(TT_DictLiteral) ||
90*e038c9c4Sjoerg LBrace->Next->is(TT_DesignatedInitializerPeriod))
917330f729Sjoerg return 0;
927330f729Sjoerg
937330f729Sjoerg // Calculate the number of code points we have to format this list. As the
947330f729Sjoerg // first token is already placed, we have to subtract it.
957330f729Sjoerg unsigned RemainingCodePoints =
967330f729Sjoerg Style.ColumnLimit - State.Column + State.NextToken->Previous->ColumnWidth;
977330f729Sjoerg
987330f729Sjoerg // Find the best ColumnFormat, i.e. the best number of columns to use.
997330f729Sjoerg const ColumnFormat *Format = getColumnFormat(RemainingCodePoints);
1007330f729Sjoerg
1017330f729Sjoerg // If no ColumnFormat can be used, the braced list would generally be
1027330f729Sjoerg // bin-packed. Add a severe penalty to this so that column layouts are
1037330f729Sjoerg // preferred if possible.
1047330f729Sjoerg if (!Format)
1057330f729Sjoerg return 10000;
1067330f729Sjoerg
1077330f729Sjoerg // Format the entire list.
1087330f729Sjoerg unsigned Penalty = 0;
1097330f729Sjoerg unsigned Column = 0;
1107330f729Sjoerg unsigned Item = 0;
1117330f729Sjoerg while (State.NextToken != LBrace->MatchingParen) {
1127330f729Sjoerg bool NewLine = false;
1137330f729Sjoerg unsigned ExtraSpaces = 0;
1147330f729Sjoerg
1157330f729Sjoerg // If the previous token was one of our commas, we are now on the next item.
1167330f729Sjoerg if (Item < Commas.size() && State.NextToken->Previous == Commas[Item]) {
1177330f729Sjoerg if (!State.NextToken->isTrailingComment()) {
1187330f729Sjoerg ExtraSpaces += Format->ColumnSizes[Column] - ItemLengths[Item];
1197330f729Sjoerg ++Column;
1207330f729Sjoerg }
1217330f729Sjoerg ++Item;
1227330f729Sjoerg }
1237330f729Sjoerg
1247330f729Sjoerg if (Column == Format->Columns || State.NextToken->MustBreakBefore) {
1257330f729Sjoerg Column = 0;
1267330f729Sjoerg NewLine = true;
1277330f729Sjoerg }
1287330f729Sjoerg
1297330f729Sjoerg // Place token using the continuation indenter and store the penalty.
1307330f729Sjoerg Penalty += Indenter->addTokenToState(State, NewLine, DryRun, ExtraSpaces);
1317330f729Sjoerg }
1327330f729Sjoerg return Penalty;
1337330f729Sjoerg }
1347330f729Sjoerg
formatFromToken(LineState & State,ContinuationIndenter * Indenter,bool DryRun)1357330f729Sjoerg unsigned CommaSeparatedList::formatFromToken(LineState &State,
1367330f729Sjoerg ContinuationIndenter *Indenter,
1377330f729Sjoerg bool DryRun) {
1387330f729Sjoerg // Formatting with 1 Column isn't really a column layout, so we don't need the
1397330f729Sjoerg // special logic here. We can just avoid bin packing any of the parameters.
1407330f729Sjoerg if (Formats.size() == 1 || HasNestedBracedList)
1417330f729Sjoerg State.Stack.back().AvoidBinPacking = true;
1427330f729Sjoerg return 0;
1437330f729Sjoerg }
1447330f729Sjoerg
1457330f729Sjoerg // Returns the lengths in code points between Begin and End (both included),
1467330f729Sjoerg // assuming that the entire sequence is put on a single line.
CodePointsBetween(const FormatToken * Begin,const FormatToken * End)1477330f729Sjoerg static unsigned CodePointsBetween(const FormatToken *Begin,
1487330f729Sjoerg const FormatToken *End) {
1497330f729Sjoerg assert(End->TotalLength >= Begin->TotalLength);
1507330f729Sjoerg return End->TotalLength - Begin->TotalLength + Begin->ColumnWidth;
1517330f729Sjoerg }
1527330f729Sjoerg
precomputeFormattingInfos(const FormatToken * Token)1537330f729Sjoerg void CommaSeparatedList::precomputeFormattingInfos(const FormatToken *Token) {
1547330f729Sjoerg // FIXME: At some point we might want to do this for other lists, too.
1557330f729Sjoerg if (!Token->MatchingParen ||
1567330f729Sjoerg !Token->isOneOf(tok::l_brace, TT_ArrayInitializerLSquare))
1577330f729Sjoerg return;
1587330f729Sjoerg
1597330f729Sjoerg // In C++11 braced list style, we should not format in columns unless they
1607330f729Sjoerg // have many items (20 or more) or we allow bin-packing of function call
1617330f729Sjoerg // arguments.
1627330f729Sjoerg if (Style.Cpp11BracedListStyle && !Style.BinPackArguments &&
1637330f729Sjoerg Commas.size() < 19)
1647330f729Sjoerg return;
1657330f729Sjoerg
1667330f729Sjoerg // Limit column layout for JavaScript array initializers to 20 or more items
1677330f729Sjoerg // for now to introduce it carefully. We can become more aggressive if this
1687330f729Sjoerg // necessary.
1697330f729Sjoerg if (Token->is(TT_ArrayInitializerLSquare) && Commas.size() < 19)
1707330f729Sjoerg return;
1717330f729Sjoerg
1727330f729Sjoerg // Column format doesn't really make sense if we don't align after brackets.
1737330f729Sjoerg if (Style.AlignAfterOpenBracket == FormatStyle::BAS_DontAlign)
1747330f729Sjoerg return;
1757330f729Sjoerg
1767330f729Sjoerg FormatToken *ItemBegin = Token->Next;
1777330f729Sjoerg while (ItemBegin->isTrailingComment())
1787330f729Sjoerg ItemBegin = ItemBegin->Next;
1797330f729Sjoerg SmallVector<bool, 8> MustBreakBeforeItem;
1807330f729Sjoerg
1817330f729Sjoerg // The lengths of an item if it is put at the end of the line. This includes
1827330f729Sjoerg // trailing comments which are otherwise ignored for column alignment.
1837330f729Sjoerg SmallVector<unsigned, 8> EndOfLineItemLength;
1847330f729Sjoerg
1857330f729Sjoerg bool HasSeparatingComment = false;
1867330f729Sjoerg for (unsigned i = 0, e = Commas.size() + 1; i != e; ++i) {
1877330f729Sjoerg // Skip comments on their own line.
1887330f729Sjoerg while (ItemBegin->HasUnescapedNewline && ItemBegin->isTrailingComment()) {
1897330f729Sjoerg ItemBegin = ItemBegin->Next;
1907330f729Sjoerg HasSeparatingComment = i > 0;
1917330f729Sjoerg }
1927330f729Sjoerg
1937330f729Sjoerg MustBreakBeforeItem.push_back(ItemBegin->MustBreakBefore);
1947330f729Sjoerg if (ItemBegin->is(tok::l_brace))
1957330f729Sjoerg HasNestedBracedList = true;
1967330f729Sjoerg const FormatToken *ItemEnd = nullptr;
1977330f729Sjoerg if (i == Commas.size()) {
1987330f729Sjoerg ItemEnd = Token->MatchingParen;
1997330f729Sjoerg const FormatToken *NonCommentEnd = ItemEnd->getPreviousNonComment();
2007330f729Sjoerg ItemLengths.push_back(CodePointsBetween(ItemBegin, NonCommentEnd));
2017330f729Sjoerg if (Style.Cpp11BracedListStyle &&
2027330f729Sjoerg !ItemEnd->Previous->isTrailingComment()) {
2037330f729Sjoerg // In Cpp11 braced list style, the } and possibly other subsequent
2047330f729Sjoerg // tokens will need to stay on a line with the last element.
2057330f729Sjoerg while (ItemEnd->Next && !ItemEnd->Next->CanBreakBefore)
2067330f729Sjoerg ItemEnd = ItemEnd->Next;
2077330f729Sjoerg } else {
2087330f729Sjoerg // In other braced lists styles, the "}" can be wrapped to the new line.
2097330f729Sjoerg ItemEnd = Token->MatchingParen->Previous;
2107330f729Sjoerg }
2117330f729Sjoerg } else {
2127330f729Sjoerg ItemEnd = Commas[i];
2137330f729Sjoerg // The comma is counted as part of the item when calculating the length.
2147330f729Sjoerg ItemLengths.push_back(CodePointsBetween(ItemBegin, ItemEnd));
2157330f729Sjoerg
2167330f729Sjoerg // Consume trailing comments so the are included in EndOfLineItemLength.
2177330f729Sjoerg if (ItemEnd->Next && !ItemEnd->Next->HasUnescapedNewline &&
2187330f729Sjoerg ItemEnd->Next->isTrailingComment())
2197330f729Sjoerg ItemEnd = ItemEnd->Next;
2207330f729Sjoerg }
2217330f729Sjoerg EndOfLineItemLength.push_back(CodePointsBetween(ItemBegin, ItemEnd));
2227330f729Sjoerg // If there is a trailing comma in the list, the next item will start at the
2237330f729Sjoerg // closing brace. Don't create an extra item for this.
2247330f729Sjoerg if (ItemEnd->getNextNonComment() == Token->MatchingParen)
2257330f729Sjoerg break;
2267330f729Sjoerg ItemBegin = ItemEnd->Next;
2277330f729Sjoerg }
2287330f729Sjoerg
2297330f729Sjoerg // Don't use column layout for lists with few elements and in presence of
2307330f729Sjoerg // separating comments.
2317330f729Sjoerg if (Commas.size() < 5 || HasSeparatingComment)
2327330f729Sjoerg return;
2337330f729Sjoerg
2347330f729Sjoerg if (Token->NestingLevel != 0 && Token->is(tok::l_brace) && Commas.size() < 19)
2357330f729Sjoerg return;
2367330f729Sjoerg
2377330f729Sjoerg // We can never place more than ColumnLimit / 3 items in a row (because of the
2387330f729Sjoerg // spaces and the comma).
2397330f729Sjoerg unsigned MaxItems = Style.ColumnLimit / 3;
2407330f729Sjoerg std::vector<unsigned> MinSizeInColumn;
2417330f729Sjoerg MinSizeInColumn.reserve(MaxItems);
2427330f729Sjoerg for (unsigned Columns = 1; Columns <= MaxItems; ++Columns) {
2437330f729Sjoerg ColumnFormat Format;
2447330f729Sjoerg Format.Columns = Columns;
2457330f729Sjoerg Format.ColumnSizes.resize(Columns);
2467330f729Sjoerg MinSizeInColumn.assign(Columns, UINT_MAX);
2477330f729Sjoerg Format.LineCount = 1;
2487330f729Sjoerg bool HasRowWithSufficientColumns = false;
2497330f729Sjoerg unsigned Column = 0;
2507330f729Sjoerg for (unsigned i = 0, e = ItemLengths.size(); i != e; ++i) {
2517330f729Sjoerg assert(i < MustBreakBeforeItem.size());
2527330f729Sjoerg if (MustBreakBeforeItem[i] || Column == Columns) {
2537330f729Sjoerg ++Format.LineCount;
2547330f729Sjoerg Column = 0;
2557330f729Sjoerg }
2567330f729Sjoerg if (Column == Columns - 1)
2577330f729Sjoerg HasRowWithSufficientColumns = true;
2587330f729Sjoerg unsigned Length =
2597330f729Sjoerg (Column == Columns - 1) ? EndOfLineItemLength[i] : ItemLengths[i];
2607330f729Sjoerg Format.ColumnSizes[Column] = std::max(Format.ColumnSizes[Column], Length);
2617330f729Sjoerg MinSizeInColumn[Column] = std::min(MinSizeInColumn[Column], Length);
2627330f729Sjoerg ++Column;
2637330f729Sjoerg }
2647330f729Sjoerg // If all rows are terminated early (e.g. by trailing comments), we don't
2657330f729Sjoerg // need to look further.
2667330f729Sjoerg if (!HasRowWithSufficientColumns)
2677330f729Sjoerg break;
2687330f729Sjoerg Format.TotalWidth = Columns - 1; // Width of the N-1 spaces.
2697330f729Sjoerg
2707330f729Sjoerg for (unsigned i = 0; i < Columns; ++i)
2717330f729Sjoerg Format.TotalWidth += Format.ColumnSizes[i];
2727330f729Sjoerg
2737330f729Sjoerg // Don't use this Format, if the difference between the longest and shortest
2747330f729Sjoerg // element in a column exceeds a threshold to avoid excessive spaces.
2757330f729Sjoerg if ([&] {
2767330f729Sjoerg for (unsigned i = 0; i < Columns - 1; ++i)
2777330f729Sjoerg if (Format.ColumnSizes[i] - MinSizeInColumn[i] > 10)
2787330f729Sjoerg return true;
2797330f729Sjoerg return false;
2807330f729Sjoerg }())
2817330f729Sjoerg continue;
2827330f729Sjoerg
2837330f729Sjoerg // Ignore layouts that are bound to violate the column limit.
2847330f729Sjoerg if (Format.TotalWidth > Style.ColumnLimit && Columns > 1)
2857330f729Sjoerg continue;
2867330f729Sjoerg
2877330f729Sjoerg Formats.push_back(Format);
2887330f729Sjoerg }
2897330f729Sjoerg }
2907330f729Sjoerg
2917330f729Sjoerg const CommaSeparatedList::ColumnFormat *
getColumnFormat(unsigned RemainingCharacters) const2927330f729Sjoerg CommaSeparatedList::getColumnFormat(unsigned RemainingCharacters) const {
2937330f729Sjoerg const ColumnFormat *BestFormat = nullptr;
2947330f729Sjoerg for (SmallVector<ColumnFormat, 4>::const_reverse_iterator
2957330f729Sjoerg I = Formats.rbegin(),
2967330f729Sjoerg E = Formats.rend();
2977330f729Sjoerg I != E; ++I) {
2987330f729Sjoerg if (I->TotalWidth <= RemainingCharacters || I->Columns == 1) {
2997330f729Sjoerg if (BestFormat && I->LineCount > BestFormat->LineCount)
3007330f729Sjoerg break;
3017330f729Sjoerg BestFormat = &*I;
3027330f729Sjoerg }
3037330f729Sjoerg }
3047330f729Sjoerg return BestFormat;
3057330f729Sjoerg }
3067330f729Sjoerg
3077330f729Sjoerg } // namespace format
3087330f729Sjoerg } // namespace clang
309