Thanks to visit codestin.com
Credit goes to clang.llvm.org

clang 22.0.0git
FormatToken.cpp
Go to the documentation of this file.
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"
17#include "llvm/ADT/SmallVector.h"
18#include <climits>
19
20namespace clang {
21namespace format {
22
24 static const char *const TokNames[] = {
25#define TYPE(X) #X,
27#undef TYPE
28 nullptr};
29
31 return TokNames[Type];
32 llvm_unreachable("unknown TokenType");
33 return nullptr;
34}
35
36static constexpr std::array<StringRef, 14> QtPropertyKeywords = {
37 "BINDABLE", "CONSTANT", "DESIGNABLE", "FINAL", "MEMBER",
38 "NOTIFY", "READ", "REQUIRED", "RESET", "REVISION",
39 "SCRIPTABLE", "STORED", "USER", "WRITE",
40};
41
42bool FormatToken::isQtProperty() const {
43 assert(llvm::is_sorted(QtPropertyKeywords));
44 return std::binary_search(QtPropertyKeywords.begin(),
46}
47
48// Sorted common C++ non-keyword types.
49static constexpr std::array<StringRef, 14> CppNonKeywordTypes = {
50 "clock_t", "int16_t", "int32_t", "int64_t", "int8_t",
51 "intptr_t", "ptrdiff_t", "size_t", "time_t", "uint16_t",
52 "uint32_t", "uint64_t", "uint8_t", "uintptr_t",
53};
54
55bool FormatToken::isTypeName(const LangOptions &LangOpts) const {
56 if (is(TT_TypeName) || Tok.isSimpleTypeSpecifier(LangOpts))
57 return true;
58 assert(llvm::is_sorted(CppNonKeywordTypes));
59 return (LangOpts.CXXOperatorNames || LangOpts.C11) && is(tok::identifier) &&
60 llvm::binary_search(CppNonKeywordTypes, TokenText);
61}
62
63bool FormatToken::isTypeOrIdentifier(const LangOptions &LangOpts) const {
64 return isTypeName(LangOpts) || isOneOf(tok::kw_auto, tok::identifier);
65}
66
67bool FormatToken::isBlockIndentedInitRBrace(const FormatStyle &Style) const {
68 assert(is(tok::r_brace));
69 if (!Style.Cpp11BracedListStyle ||
70 Style.AlignAfterOpenBracket != FormatStyle::BAS_BlockIndent) {
71 return false;
72 }
73 const auto *LBrace = MatchingParen;
74 assert(LBrace && LBrace->is(tok::l_brace));
75 if (LBrace->is(BK_BracedInit))
76 return true;
77 if (LBrace->Previous && LBrace->Previous->is(tok::equal))
78 return true;
79 return false;
80}
81
82bool FormatToken::opensBlockOrBlockTypeList(const FormatStyle &Style) const {
83 // C# Does not indent object initialisers as continuations.
84 if (is(tok::l_brace) && getBlockKind() == BK_BracedInit && Style.isCSharp())
85 return true;
86 if (is(TT_TemplateString) && opensScope())
87 return true;
88 return is(TT_ArrayInitializerLSquare) || is(TT_ProtoExtensionLSquare) ||
89 (is(tok::l_brace) &&
90 (getBlockKind() == BK_Block || is(TT_DictLiteral) ||
91 (!Style.Cpp11BracedListStyle && NestingLevel == 0))) ||
92 (is(tok::less) && Style.isProto());
93}
94
96
98
99unsigned CommaSeparatedList::formatAfterToken(LineState &State,
100 ContinuationIndenter *Indenter,
101 bool DryRun) {
102 if (!State.NextToken || !State.NextToken->Previous)
103 return 0;
104
105 if (Formats.size() <= 1)
106 return 0; // Handled by formatFromToken (1) or avoid severe penalty (0).
107
108 // Ensure that we start on the opening brace.
109 const FormatToken *LBrace =
110 State.NextToken->Previous->getPreviousNonComment();
111 if (!LBrace || !LBrace->isOneOf(tok::l_brace, TT_ArrayInitializerLSquare) ||
112 LBrace->is(BK_Block) || LBrace->is(TT_DictLiteral) ||
113 LBrace->Next->is(TT_DesignatedInitializerPeriod)) {
114 return 0;
115 }
116
117 // Calculate the number of code points we have to format this list. As the
118 // first token is already placed, we have to subtract it.
119 unsigned RemainingCodePoints =
120 Style.ColumnLimit - State.Column + State.NextToken->Previous->ColumnWidth;
121
122 // Find the best ColumnFormat, i.e. the best number of columns to use.
123 const ColumnFormat *Format = getColumnFormat(RemainingCodePoints);
124
125 // If no ColumnFormat can be used, the braced list would generally be
126 // bin-packed. Add a severe penalty to this so that column layouts are
127 // preferred if possible.
128 if (!Format)
129 return 10'000;
130
131 // Format the entire list.
132 unsigned Penalty = 0;
133 unsigned Column = 0;
134 unsigned Item = 0;
135 while (State.NextToken != LBrace->MatchingParen) {
136 bool NewLine = false;
137 unsigned ExtraSpaces = 0;
138
139 // If the previous token was one of our commas, we are now on the next item.
140 if (Item < Commas.size() && State.NextToken->Previous == Commas[Item]) {
141 if (!State.NextToken->isTrailingComment()) {
142 ExtraSpaces += Format->ColumnSizes[Column] - ItemLengths[Item];
143 ++Column;
144 }
145 ++Item;
146 }
147
148 if (Column == Format->Columns || State.NextToken->MustBreakBefore) {
149 Column = 0;
150 NewLine = true;
151 }
152
153 // Place token using the continuation indenter and store the penalty.
154 Penalty += Indenter->addTokenToState(State, NewLine, DryRun, ExtraSpaces);
155 }
156 return Penalty;
157}
158
159unsigned CommaSeparatedList::formatFromToken(LineState &State,
160 ContinuationIndenter *Indenter,
161 bool DryRun) {
162 // Formatting with 1 Column isn't really a column layout, so we don't need the
163 // special logic here. We can just avoid bin packing any of the parameters.
164 if (Formats.size() == 1 || HasNestedBracedList)
165 State.Stack.back().AvoidBinPacking = true;
166 return 0;
167}
168
169// Returns the lengths in code points between Begin and End (both included),
170// assuming that the entire sequence is put on a single line.
171static unsigned CodePointsBetween(const FormatToken *Begin,
172 const FormatToken *End) {
173 assert(End->TotalLength >= Begin->TotalLength);
174 return End->TotalLength - Begin->TotalLength + Begin->ColumnWidth;
175}
176
178 // FIXME: At some point we might want to do this for other lists, too.
179 if (!Token->MatchingParen ||
180 !Token->isOneOf(tok::l_brace, TT_ArrayInitializerLSquare)) {
181 return;
182 }
183
184 // In C++11 braced list style, we should not format in columns unless they
185 // have many items (20 or more) or we allow bin-packing of function call
186 // arguments.
187 if (Style.Cpp11BracedListStyle && !Style.BinPackArguments &&
188 (Commas.size() < 19 || !Style.BinPackLongBracedList)) {
189 return;
190 }
191
192 // Limit column layout for JavaScript array initializers to 20 or more items
193 // for now to introduce it carefully. We can become more aggressive if this
194 // necessary.
195 if (Token->is(TT_ArrayInitializerLSquare) && Commas.size() < 19)
196 return;
197
198 // Column format doesn't really make sense if we don't align after brackets.
199 if (Style.AlignAfterOpenBracket == FormatStyle::BAS_DontAlign)
200 return;
201
202 FormatToken *ItemBegin = Token->Next;
203 while (ItemBegin->isTrailingComment())
204 ItemBegin = ItemBegin->Next;
205 SmallVector<bool, 8> MustBreakBeforeItem;
206
207 // The lengths of an item if it is put at the end of the line. This includes
208 // trailing comments which are otherwise ignored for column alignment.
209 SmallVector<unsigned, 8> EndOfLineItemLength;
210 MustBreakBeforeItem.reserve(Commas.size() + 1);
211 EndOfLineItemLength.reserve(Commas.size() + 1);
212 ItemLengths.reserve(Commas.size() + 1);
213
214 bool HasSeparatingComment = false;
215 for (unsigned i = 0, e = Commas.size() + 1; i != e; ++i) {
216 assert(ItemBegin);
217 // Skip comments on their own line.
218 while (ItemBegin->HasUnescapedNewline && ItemBegin->isTrailingComment()) {
219 ItemBegin = ItemBegin->Next;
220 HasSeparatingComment = i > 0;
221 }
222
223 MustBreakBeforeItem.push_back(ItemBegin->MustBreakBefore);
224 if (ItemBegin->is(tok::l_brace))
225 HasNestedBracedList = true;
226 const FormatToken *ItemEnd = nullptr;
227 if (i == Commas.size()) {
228 ItemEnd = Token->MatchingParen;
229 const FormatToken *NonCommentEnd = ItemEnd->getPreviousNonComment();
230 ItemLengths.push_back(CodePointsBetween(ItemBegin, NonCommentEnd));
231 if (Style.Cpp11BracedListStyle &&
232 !ItemEnd->Previous->isTrailingComment()) {
233 // In Cpp11 braced list style, the } and possibly other subsequent
234 // tokens will need to stay on a line with the last element.
235 while (ItemEnd->Next && !ItemEnd->Next->CanBreakBefore)
236 ItemEnd = ItemEnd->Next;
237 } else {
238 // In other braced lists styles, the "}" can be wrapped to the new line.
239 ItemEnd = Token->MatchingParen->Previous;
240 }
241 } else {
242 ItemEnd = Commas[i];
243 // The comma is counted as part of the item when calculating the length.
244 ItemLengths.push_back(CodePointsBetween(ItemBegin, ItemEnd));
245
246 // Consume trailing comments so the are included in EndOfLineItemLength.
247 if (ItemEnd->Next && !ItemEnd->Next->HasUnescapedNewline &&
248 ItemEnd->Next->isTrailingComment()) {
249 ItemEnd = ItemEnd->Next;
250 }
251 }
252 EndOfLineItemLength.push_back(CodePointsBetween(ItemBegin, ItemEnd));
253 // If there is a trailing comma in the list, the next item will start at the
254 // closing brace. Don't create an extra item for this.
255 if (ItemEnd->getNextNonComment() == Token->MatchingParen)
256 break;
257 ItemBegin = ItemEnd->Next;
258 }
259
260 // Don't use column layout for lists with few elements and in presence of
261 // separating comments.
262 if (Commas.size() < 5 || HasSeparatingComment)
263 return;
264
265 if (Token->NestingLevel != 0 && Token->is(tok::l_brace) && Commas.size() < 19)
266 return;
267
268 // We can never place more than ColumnLimit / 3 items in a row (because of the
269 // spaces and the comma).
270 unsigned MaxItems = Style.ColumnLimit / 3;
271 SmallVector<unsigned> MinSizeInColumn;
272 MinSizeInColumn.reserve(MaxItems);
273 for (unsigned Columns = 1; Columns <= MaxItems; ++Columns) {
274 ColumnFormat Format;
275 Format.Columns = Columns;
276 Format.ColumnSizes.resize(Columns);
277 MinSizeInColumn.assign(Columns, UINT_MAX);
278 Format.LineCount = 1;
279 bool HasRowWithSufficientColumns = false;
280 unsigned Column = 0;
281 for (unsigned i = 0, e = ItemLengths.size(); i != e; ++i) {
282 assert(i < MustBreakBeforeItem.size());
283 if (MustBreakBeforeItem[i] || Column == Columns) {
284 ++Format.LineCount;
285 Column = 0;
286 }
287 if (Column == Columns - 1)
288 HasRowWithSufficientColumns = true;
289 unsigned Length =
290 (Column == Columns - 1) ? EndOfLineItemLength[i] : ItemLengths[i];
291 Format.ColumnSizes[Column] = std::max(Format.ColumnSizes[Column], Length);
292 MinSizeInColumn[Column] = std::min(MinSizeInColumn[Column], Length);
293 ++Column;
294 }
295 // If all rows are terminated early (e.g. by trailing comments), we don't
296 // need to look further.
297 if (!HasRowWithSufficientColumns)
298 break;
299 Format.TotalWidth = Columns - 1; // Width of the N-1 spaces.
300
301 for (unsigned i = 0; i < Columns; ++i)
302 Format.TotalWidth += Format.ColumnSizes[i];
303
304 // Don't use this Format, if the difference between the longest and shortest
305 // element in a column exceeds a threshold to avoid excessive spaces.
306 if ([&] {
307 for (unsigned i = 0; i < Columns - 1; ++i)
308 if (Format.ColumnSizes[i] - MinSizeInColumn[i] > 10)
309 return true;
310 return false;
311 }()) {
312 continue;
313 }
314
315 // Ignore layouts that are bound to violate the column limit.
316 if (Format.TotalWidth > Style.ColumnLimit && Columns > 1)
317 continue;
318
319 Formats.push_back(Format);
320 }
321}
322
323const CommaSeparatedList::ColumnFormat *
324CommaSeparatedList::getColumnFormat(unsigned RemainingCharacters) const {
325 const ColumnFormat *BestFormat = nullptr;
326 for (const ColumnFormat &Format : llvm::reverse(Formats)) {
327 if (Format.TotalWidth <= RemainingCharacters || Format.Columns == 1) {
328 if (BestFormat && Format.LineCount > BestFormat->LineCount)
329 break;
330 BestFormat = &Format;
331 }
332 }
333 return BestFormat;
334}
335
336bool startsNextParameter(const FormatToken &Current, const FormatStyle &Style) {
337 assert(Current.Previous);
338 const auto &Previous = *Current.Previous;
339 if (Current.is(TT_CtorInitializerComma) &&
340 Style.BreakConstructorInitializers == FormatStyle::BCIS_BeforeComma) {
341 return true;
342 }
343 if (Style.Language == FormatStyle::LK_Proto && Current.is(TT_SelectorName))
344 return true;
345 if (Current.is(TT_QtProperty))
346 return true;
347 return Previous.is(tok::comma) && !Current.isTrailingComment() &&
348 ((Previous.isNot(TT_CtorInitializerComma) ||
349 Style.BreakConstructorInitializers !=
350 FormatStyle::BCIS_BeforeComma) &&
351 (Previous.isNot(TT_InheritanceComma) ||
352 Style.BreakInheritanceList != FormatStyle::BILS_BeforeComma));
353}
354
355} // namespace format
356} // namespace clang
This file implements an indenter that manages the indentation of continuations.
This file contains the declaration of the FormatToken, a wrapper around Token with additional informa...
unsigned NestingLevel
The nesting level of this token, i.e.
#define LIST_TOKEN_TYPES
Definition FormatToken.h:27
StringRef TokenText
The raw text of the token.
FormatToken()
Token Tok
The Token.
FormatToken * MatchingParen
If this is a bracket, this points to the matching one.
FormatToken * Previous
The previous token in the unwrapped line.
static constexpr bool isOneOf()
static const char *const TokNames[]
unsigned formatFromToken(LineState &State, ContinuationIndenter *Indenter, bool DryRun) override
Apply the special formatting that the given role demands.
unsigned formatAfterToken(LineState &State, ContinuationIndenter *Indenter, bool DryRun) override
Same as formatFromToken, but assumes that the first token has already been set thereby deciding on th...
void precomputeFormattingInfos(const FormatToken *Token) override
After the TokenAnnotator has finished annotating all the tokens, this function precomputes required i...
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
virtual void precomputeFormattingInfos(const FormatToken *Token)
After the TokenAnnotator has finished annotating all the tokens, this function precomputes required i...
const FormatStyle & Style
virtual ~TokenRole()
Token - This structure provides full information about a lexed token.
Definition Token.h:36
bool is(tok::TokenKind K) const
is/isNot - Predicates to check if this token is a specific kind, as in "if (Tok.is(tok::l_brace)) {....
Definition Token.h:102
bool isOneOf(Ts... Ks) const
Definition Token.h:104
The base class of the type hierarchy.
Definition TypeBase.h:1833
#define UINT_MAX
Definition limits.h:64
const char * getTokenTypeName(TokenType Type)
Determines the name of a token type.
static constexpr std::array< StringRef, 14 > QtPropertyKeywords
static unsigned CodePointsBetween(const FormatToken *Begin, const FormatToken *End)
TokenType
Determines the semantic type of a syntactic token, e.g.
static constexpr std::array< StringRef, 14 > CppNonKeywordTypes
bool startsNextParameter(const FormatToken &Current, const FormatStyle &Style)
The JSON file list parser is used to communicate input to InstallAPI.
A wrapper around a Token storing information about the whitespace characters preceding it.
BraceBlockKind getBlockKind() const
unsigned ColumnWidth
The width of the non-whitespace parts of the token (or its first line for multi-line tokens) in colum...
bool is(tok::TokenKind Kind) const
unsigned TotalLength
The total length of the unwrapped line up to and including this token.
FormatToken * Previous
The previous token in the unwrapped line.