clang 21.0.0git
FormatToken.h
Go to the documentation of this file.
1//===--- FormatToken.h - Format C++ code ------------------------*- C++ -*-===//
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 contains the declaration of the FormatToken, a wrapper
11/// around Token with additional information related to formatting.
12///
13//===----------------------------------------------------------------------===//
14
15#ifndef LLVM_CLANG_LIB_FORMAT_FORMATTOKEN_H
16#define LLVM_CLANG_LIB_FORMAT_FORMATTOKEN_H
17
20#include "clang/Format/Format.h"
21#include "clang/Lex/Lexer.h"
22#include <unordered_set>
23
24namespace clang {
25namespace format {
26
27#define LIST_TOKEN_TYPES \
28 TYPE(AfterPPDirective) \
29 TYPE(ArrayInitializerLSquare) \
30 TYPE(ArraySubscriptLSquare) \
31 TYPE(AttributeColon) \
32 TYPE(AttributeLParen) \
33 TYPE(AttributeMacro) \
34 TYPE(AttributeRParen) \
35 TYPE(AttributeSquare) \
36 TYPE(BinaryOperator) \
37 TYPE(BitFieldColon) \
38 TYPE(BlockComment) \
39 /* l_brace of a block that is not the body of a (e.g. loop) statement. */ \
40 TYPE(BlockLBrace) \
41 TYPE(BracedListLBrace) \
42 TYPE(CaseLabelArrow) \
43 /* The colon at the end of a case label. */ \
44 TYPE(CaseLabelColon) \
45 TYPE(CastRParen) \
46 TYPE(ClassLBrace) \
47 /* Name of class/struct/union/interface definition. */ \
48 TYPE(ClassHeadName) \
49 TYPE(ClassRBrace) \
50 TYPE(CompoundRequirementLBrace) \
51 /* ternary ?: expression */ \
52 TYPE(ConditionalExpr) \
53 /* the condition in an if statement */ \
54 TYPE(ConditionLParen) \
55 TYPE(ConflictAlternative) \
56 TYPE(ConflictEnd) \
57 TYPE(ConflictStart) \
58 /* l_brace of if/for/while */ \
59 TYPE(ControlStatementLBrace) \
60 TYPE(ControlStatementRBrace) \
61 TYPE(CppCastLParen) \
62 TYPE(CSharpGenericTypeConstraint) \
63 TYPE(CSharpGenericTypeConstraintColon) \
64 TYPE(CSharpGenericTypeConstraintComma) \
65 TYPE(CSharpNamedArgumentColon) \
66 TYPE(CSharpNullable) \
67 TYPE(CSharpNullConditionalLSquare) \
68 TYPE(CSharpStringLiteral) \
69 TYPE(CtorInitializerColon) \
70 TYPE(CtorInitializerComma) \
71 TYPE(CtorDtorDeclName) \
72 TYPE(DesignatedInitializerLSquare) \
73 TYPE(DesignatedInitializerPeriod) \
74 TYPE(DictLiteral) \
75 TYPE(DoWhile) \
76 TYPE(ElseLBrace) \
77 TYPE(ElseRBrace) \
78 TYPE(EnumLBrace) \
79 TYPE(EnumRBrace) \
80 TYPE(FatArrow) \
81 TYPE(ForEachMacro) \
82 TYPE(FunctionAnnotationRParen) \
83 TYPE(FunctionDeclarationName) \
84 TYPE(FunctionDeclarationLParen) \
85 TYPE(FunctionLBrace) \
86 TYPE(FunctionLikeOrFreestandingMacro) \
87 TYPE(FunctionTypeLParen) \
88 /* The colons as part of a C11 _Generic selection */ \
89 TYPE(GenericSelectionColon) \
90 /* The colon at the end of a goto label. */ \
91 TYPE(GotoLabelColon) \
92 TYPE(IfMacro) \
93 TYPE(ImplicitStringLiteral) \
94 TYPE(InheritanceColon) \
95 TYPE(InheritanceComma) \
96 TYPE(InlineASMBrace) \
97 TYPE(InlineASMColon) \
98 TYPE(InlineASMSymbolicNameLSquare) \
99 TYPE(JavaAnnotation) \
100 TYPE(JsAndAndEqual) \
101 TYPE(JsComputedPropertyName) \
102 TYPE(JsExponentiation) \
103 TYPE(JsExponentiationEqual) \
104 TYPE(JsPipePipeEqual) \
105 TYPE(JsPrivateIdentifier) \
106 TYPE(JsTypeColon) \
107 TYPE(JsTypeOperator) \
108 TYPE(JsTypeOptionalQuestion) \
109 TYPE(LambdaArrow) \
110 TYPE(LambdaDefinitionLParen) \
111 TYPE(LambdaLBrace) \
112 TYPE(LambdaLSquare) \
113 TYPE(LeadingJavaAnnotation) \
114 TYPE(LineComment) \
115 TYPE(MacroBlockBegin) \
116 TYPE(MacroBlockEnd) \
117 TYPE(ModulePartitionColon) \
118 TYPE(NamespaceLBrace) \
119 TYPE(NamespaceMacro) \
120 TYPE(NamespaceRBrace) \
121 TYPE(NonNullAssertion) \
122 TYPE(NullCoalescingEqual) \
123 TYPE(NullCoalescingOperator) \
124 TYPE(NullPropagatingOperator) \
125 TYPE(ObjCBlockLBrace) \
126 TYPE(ObjCBlockLParen) \
127 TYPE(ObjCDecl) \
128 TYPE(ObjCForIn) \
129 TYPE(ObjCMethodExpr) \
130 TYPE(ObjCMethodSpecifier) \
131 TYPE(ObjCProperty) \
132 TYPE(ObjCStringLiteral) \
133 TYPE(OverloadedOperator) \
134 TYPE(OverloadedOperatorLParen) \
135 TYPE(PointerOrReference) \
136 TYPE(ProtoExtensionLSquare) \
137 TYPE(PureVirtualSpecifier) \
138 TYPE(RangeBasedForLoopColon) \
139 TYPE(RecordLBrace) \
140 TYPE(RecordRBrace) \
141 TYPE(RegexLiteral) \
142 TYPE(RequiresClause) \
143 TYPE(RequiresClauseInARequiresExpression) \
144 TYPE(RequiresExpression) \
145 TYPE(RequiresExpressionLBrace) \
146 TYPE(RequiresExpressionLParen) \
147 TYPE(SelectorName) \
148 TYPE(StartOfName) \
149 TYPE(StatementAttributeLikeMacro) \
150 TYPE(StatementMacro) \
151 /* A string that is part of a string concatenation. For C#, JavaScript, and \
152 * Java, it is used for marking whether a string needs parentheses around it \
153 * if it is to be split into parts joined by `+`. For Verilog, whether \
154 * braces need to be added to split it. Not used for other languages. */ \
155 TYPE(StringInConcatenation) \
156 TYPE(StructLBrace) \
157 TYPE(StructRBrace) \
158 TYPE(StructuredBindingLSquare) \
159 TYPE(SwitchExpressionLabel) \
160 TYPE(SwitchExpressionLBrace) \
161 TYPE(TableGenBangOperator) \
162 TYPE(TableGenCondOperator) \
163 TYPE(TableGenCondOperatorColon) \
164 TYPE(TableGenCondOperatorComma) \
165 TYPE(TableGenDAGArgCloser) \
166 TYPE(TableGenDAGArgListColon) \
167 TYPE(TableGenDAGArgListColonToAlign) \
168 TYPE(TableGenDAGArgListComma) \
169 TYPE(TableGenDAGArgListCommaToBreak) \
170 TYPE(TableGenDAGArgOpener) \
171 TYPE(TableGenDAGArgOpenerToBreak) \
172 TYPE(TableGenDAGArgOperatorID) \
173 TYPE(TableGenDAGArgOperatorToBreak) \
174 TYPE(TableGenListCloser) \
175 TYPE(TableGenListOpener) \
176 TYPE(TableGenMultiLineString) \
177 TYPE(TableGenTrailingPasteOperator) \
178 TYPE(TableGenValueSuffix) \
179 TYPE(TemplateCloser) \
180 TYPE(TemplateOpener) \
181 TYPE(TemplateString) \
182 TYPE(TrailingAnnotation) \
183 TYPE(TrailingReturnArrow) \
184 TYPE(TrailingUnaryOperator) \
185 TYPE(TypeDeclarationParen) \
186 TYPE(TemplateName) \
187 TYPE(TypeName) \
188 TYPE(TypenameMacro) \
189 TYPE(UnaryOperator) \
190 TYPE(UnionLBrace) \
191 TYPE(UnionRBrace) \
192 TYPE(UntouchableMacroFunc) \
193 TYPE(VariableTemplate) \
194 /* Like in 'assign x = 0, y = 1;' . */ \
195 TYPE(VerilogAssignComma) \
196 /* like in begin : block */ \
197 TYPE(VerilogBlockLabelColon) \
198 /* The square bracket for the dimension part of the type name. \
199 * In 'logic [1:0] x[1:0]', only the first '['. This way we can have space \
200 * before the first bracket but not the second. */ \
201 TYPE(VerilogDimensionedTypeName) \
202 /* list of port connections or parameters in a module instantiation */ \
203 TYPE(VerilogInstancePortComma) \
204 TYPE(VerilogInstancePortLParen) \
205 /* A parenthesized list within which line breaks are inserted by the \
206 * formatter, for example the list of ports in a module header. */ \
207 TYPE(VerilogMultiLineListLParen) \
208 /* for the base in a number literal, not including the quote */ \
209 TYPE(VerilogNumberBase) \
210 /* like `(strong1, pull0)` */ \
211 TYPE(VerilogStrength) \
212 /* Things inside the table in user-defined primitives. */ \
213 TYPE(VerilogTableItem) \
214 /* those that separate ports of different types */ \
215 TYPE(VerilogTypeComma) \
216 TYPE(Unknown)
217
218/// Determines the semantic type of a syntactic token, e.g. whether "<" is a
219/// template opener or binary operator.
220enum TokenType : uint8_t {
221#define TYPE(X) TT_##X,
223#undef TYPE
226
227/// Determines the name of a token type.
229
230// Represents what type of block a set of braces open.
232
233// The packing kind of a function's parameters.
235
237
238/// Roles a token can take in a configured macro expansion.
240 /// The token was expanded from a macro argument when formatting the expanded
241 /// token sequence.
243 /// The token is part of a macro argument that was previously formatted as
244 /// expansion when formatting the unexpanded macro call.
246 /// The token was expanded from a macro definition, and is not visible as part
247 /// of the macro call.
248 MR_Hidden,
249};
250
251struct FormatToken;
252
253/// Contains information on the token's role in a macro expansion.
254///
255/// Given the following definitions:
256/// A(X) = [ X ]
257/// B(X) = < X >
258/// C(X) = X
259///
260/// Consider the macro call:
261/// A({B(C(C(x)))}) -> [{<x>}]
262///
263/// In this case, the tokens of the unexpanded macro call will have the
264/// following relevant entries in their macro context (note that formatting
265/// the unexpanded macro call happens *after* formatting the expanded macro
266/// call):
267/// A( { B( C( C(x) ) ) } )
268/// Role: NN U NN NN NNUN N N U N (N=None, U=UnexpandedArg)
269///
270/// [ { < x > } ]
271/// Role: H E H E H E H (H=Hidden, E=ExpandedArg)
272/// ExpandedFrom[0]: A A A A A A A
273/// ExpandedFrom[1]: B B B
274/// ExpandedFrom[2]: C
275/// ExpandedFrom[3]: C
276/// StartOfExpansion: 1 0 1 2 0 0 0
277/// EndOfExpansion: 0 0 0 2 1 0 1
278struct MacroExpansion {
280
281 /// The token's role in the macro expansion.
282 /// When formatting an expanded macro, all tokens that are part of macro
283 /// arguments will be MR_ExpandedArg, while all tokens that are not visible in
284 /// the macro call will be MR_Hidden.
285 /// When formatting an unexpanded macro call, all tokens that are part of
286 /// macro arguments will be MR_UnexpandedArg.
288
289 /// The stack of macro call identifier tokens this token was expanded from.
292 /// The number of expansions of which this macro is the first entry.
293 unsigned StartOfExpansion = 0;
294
295 /// The number of currently open expansions in \c ExpandedFrom this macro is
296 /// the last token in.
297 unsigned EndOfExpansion = 0;
298};
301class AnnotatedLine;
302
303/// A wrapper around a \c Token storing information about the
304/// whitespace characters preceding it.
305struct FormatToken {
314 BlockKind(BK_Unknown), Decision(FD_Unformatted),
315 PackingKind(PPK_Inconclusive), TypeIsFinalized(false),
316 Type(TT_Unknown) {}
317
318 /// The \c Token.
320
321 /// The raw text of the token.
322 ///
323 /// Contains the raw token text without leading whitespace and without leading
324 /// escaped newlines.
325 StringRef TokenText;
326
327 /// A token can have a special role that can carry extra information
328 /// about the token's formatting.
329 /// FIXME: Make FormatToken for parsing and AnnotatedToken two different
330 /// classes and make this a unique_ptr in the AnnotatedToken class.
331 std::shared_ptr<TokenRole> Role;
333 /// The range of the whitespace immediately preceding the \c Token.
336 /// Whether there is at least one unescaped newline before the \c
337 /// Token.
339
340 /// Whether the token text contains newlines (escaped or not).
341 unsigned IsMultiline : 1;
342
343 /// Indicates that this is the first token of the file.
344 unsigned IsFirst : 1;
345
346 /// Whether there must be a line break before this token.
347 ///
348 /// This happens for example when a preprocessor directive ended directly
349 /// before the token.
350 unsigned MustBreakBefore : 1;
352 /// Whether MustBreakBefore is finalized during parsing and must not
353 /// be reset between runs.
355
356 /// Set to \c true if this token is an unterminated literal.
358
359 /// \c true if it is allowed to break before this token.
360 unsigned CanBreakBefore : 1;
362 /// \c true if this is the ">" of "template<..>".
364
365 /// \c true if this token starts a binary expression, i.e. has at least
366 /// one fake l_paren with a precedence greater than prec::Unknown.
367 unsigned StartsBinaryExpression : 1;
368 /// \c true if this token ends a binary expression.
369 unsigned EndsBinaryExpression : 1;
370
371 /// Is this token part of a \c DeclStmt defining multiple variables?
372 ///
373 /// Only set if \c Type == \c TT_StartOfName.
374 unsigned PartOfMultiVariableDeclStmt : 1;
375
376 /// Does this line comment continue a line comment section?
377 ///
378 /// Only set to true if \c Type == \c TT_LineComment.
379 unsigned ContinuesLineCommentSection : 1;
380
381 /// If \c true, this token has been fully formatted (indented and
382 /// potentially re-formatted inside), and we do not allow further formatting
383 /// changes.
384 unsigned Finalized : 1;
385
386 /// \c true if this is the last token within requires clause.
387 unsigned ClosesRequiresClause : 1;
388
389 /// \c true if this token ends a group of C++ attributes.
390 unsigned EndsCppAttributeGroup : 1;
392private:
393 /// Contains the kind of block if this token is a brace.
394 unsigned BlockKind : 2;
395
396public:
398 return static_cast<BraceBlockKind>(BlockKind);
399 }
400 void setBlockKind(BraceBlockKind BBK) {
401 BlockKind = BBK;
402 assert(getBlockKind() == BBK && "BraceBlockKind overflow!");
403 }
405private:
406 /// Stores the formatting decision for the token once it was made.
407 unsigned Decision : 2;
408
409public:
411 return static_cast<FormatDecision>(Decision);
412 }
414 Decision = D;
415 assert(getDecision() == D && "FormatDecision overflow!");
416 }
418private:
419 /// If this is an opening parenthesis, how are the parameters packed?
420 unsigned PackingKind : 2;
421
422public:
424 return static_cast<ParameterPackingKind>(PackingKind);
425 }
427 PackingKind = K;
428 assert(getPackingKind() == K && "ParameterPackingKind overflow!");
429 }
430
431private:
432 unsigned TypeIsFinalized : 1;
434
435public:
436 /// Returns the token's type, e.g. whether "<" is a template opener or
437 /// binary operator.
438 TokenType getType() const { return Type; }
439 void setType(TokenType T) {
440 // If this token is a macro argument while formatting an unexpanded macro
441 // call, we do not change its type any more - the type was deduced from
442 // formatting the expanded macro stream already.
443 if (MacroCtx && MacroCtx->Role == MR_UnexpandedArg)
444 return;
445 assert((!TypeIsFinalized || T == Type) &&
446 "Please use overwriteFixedType to change a fixed type.");
448 }
449 /// Sets the type and also the finalized flag. This prevents the type to be
450 /// reset in TokenAnnotator::resetTokenMetadata(). If the type needs to be set
451 /// to another one please use overwriteFixedType, or even better remove the
452 /// need to reassign the type.
454 if (MacroCtx && MacroCtx->Role == MR_UnexpandedArg)
455 return;
456 Type = T;
457 TypeIsFinalized = true;
458 }
460 if (MacroCtx && MacroCtx->Role == MR_UnexpandedArg)
461 return;
462 TypeIsFinalized = false;
463 setType(T);
464 }
465 bool isTypeFinalized() const { return TypeIsFinalized; }
466
467 /// Used to set an operator precedence explicitly.
469
470 /// The number of newlines immediately before the \c Token.
471 ///
472 /// This can be used to determine what the user wrote in the original code
473 /// and thereby e.g. leave an empty line between two function definitions.
474 unsigned NewlinesBefore = 0;
475
476 /// The number of newlines immediately before the \c Token after formatting.
477 ///
478 /// This is used to avoid overlapping whitespace replacements when \c Newlines
479 /// is recomputed for a finalized preprocessor branching directive.
480 int Newlines = -1;
481
482 /// The offset just past the last '\n' in this token's leading
483 /// whitespace (relative to \c WhiteSpaceStart). 0 if there is no '\n'.
484 unsigned LastNewlineOffset = 0;
485
486 /// The width of the non-whitespace parts of the token (or its first
487 /// line for multi-line tokens) in columns.
488 /// We need this to correctly measure number of columns a token spans.
489 unsigned ColumnWidth = 0;
491 /// Contains the width in columns of the last line of a multi-line
492 /// token.
494
495 /// The number of spaces that should be inserted before this token.
496 unsigned SpacesRequiredBefore = 0;
498 /// Number of parameters, if this is "(", "[" or "<".
499 unsigned ParameterCount = 0;
500
501 /// Number of parameters that are nested blocks,
502 /// if this is "(", "[" or "<".
503 unsigned BlockParameterCount = 0;
504
505 /// If this is a bracket ("<", "(", "[" or "{"), contains the kind of
506 /// the surrounding bracket.
507 tok::TokenKind ParentBracket = tok::unknown;
508
509 /// The total length of the unwrapped line up to and including this
510 /// token.
511 unsigned TotalLength = 0;
512
513 /// The original 0-based column of this token, including expanded tabs.
514 /// The configured TabWidth is used as tab width.
515 unsigned OriginalColumn = 0;
516
517 /// The length of following tokens until the next natural split point,
518 /// or the next token that can be broken.
519 unsigned UnbreakableTailLength = 0;
520
521 // FIXME: Come up with a 'cleaner' concept.
522 /// The binding strength of a token. This is a combined value of
523 /// operator precedence, parenthesis nesting, etc.
524 unsigned BindingStrength = 0;
526 /// The nesting level of this token, i.e. the number of surrounding (),
527 /// [], {} or <>.
528 unsigned NestingLevel = 0;
529
530 /// The indent level of this token. Copied from the surrounding line.
531 unsigned IndentLevel = 0;
532
533 /// Penalty for inserting a line break before this token.
534 unsigned SplitPenalty = 0;
536 /// If this is the first ObjC selector name in an ObjC method
537 /// definition or call, this contains the length of the longest name.
538 ///
539 /// This being set to 0 means that the selectors should not be colon-aligned,
540 /// e.g. because several of them are block-type.
541 unsigned LongestObjCSelectorName = 0;
542
543 /// If this is the first ObjC selector name in an ObjC method
544 /// definition or call, this contains the number of parts that the whole
545 /// selector consist of.
546 unsigned ObjCSelectorNameParts = 0;
547
548 /// The 0-based index of the parameter/argument. For ObjC it is set
549 /// for the selector name token.
550 /// For now calculated only for ObjC.
551 unsigned ParameterIndex = 0;
553 /// Stores the number of required fake parentheses and the
554 /// corresponding operator precedence.
555 ///
556 /// If multiple fake parentheses start at a token, this vector stores them in
557 /// reverse order, i.e. inner fake parenthesis first.
559 /// Insert this many fake ) after this token for correct indentation.
560 unsigned FakeRParens = 0;
561
562 /// If this is an operator (or "."/"->") in a sequence of operators
563 /// with the same precedence, contains the 0-based operator index.
564 unsigned OperatorIndex = 0;
566 /// If this is an operator (or "."/"->") in a sequence of operators
567 /// with the same precedence, points to the next operator.
569
570 /// If this is a bracket, this points to the matching one.
572
573 /// The previous token in the unwrapped line.
575
576 /// The next token in the unwrapped line.
577 FormatToken *Next = nullptr;
578
579 /// The first token in set of column elements.
580 bool StartsColumn = false;
581
582 /// This notes the start of the line of an array initializer.
584
585 /// This starts an array initializer.
586 bool IsArrayInitializer = false;
587
588 /// Is optional and can be removed.
589 bool Optional = false;
590
591 /// Might be function declaration open/closing paren.
592 bool MightBeFunctionDeclParen = false;
593
594 /// Has "\n\f\n" or "\n\f\r\n" before TokenText.
595 bool HasFormFeedBefore = false;
596
597 /// Number of optional braces to be inserted after this token:
598 /// -1: a single left brace
599 /// 0: no braces
600 /// >0: number of right braces
601 int8_t BraceCount = 0;
602
603 /// If this token starts a block, this contains all the unwrapped lines
604 /// in it.
606
607 // Contains all attributes related to how this token takes part
608 // in a configured macro expansion.
609 std::optional<MacroExpansion> MacroCtx;
610
611 /// When macro expansion introduces nodes with children, those are marked as
612 /// \c MacroParent.
613 /// FIXME: The formatting code currently hard-codes the assumption that
614 /// child nodes are introduced by blocks following an opening brace.
615 /// This is deeply baked into the code and disentangling this will require
616 /// signficant refactorings. \c MacroParent allows us to special-case the
617 /// cases in which we treat parents as block-openers for now.
618 bool MacroParent = false;
620 bool is(tok::TokenKind Kind) const { return Tok.is(Kind); }
621 bool is(TokenType TT) const { return getType() == TT; }
622 bool is(const IdentifierInfo *II) const {
623 return II && II == Tok.getIdentifierInfo();
625 bool is(tok::PPKeywordKind Kind) const {
628 }
629 bool is(BraceBlockKind BBK) const { return getBlockKind() == BBK; }
630 bool is(ParameterPackingKind PPK) const { return getPackingKind() == PPK; }
631
632 template <typename A, typename B> bool isOneOf(A K1, B K2) const {
633 return is(K1) || is(K2);
634 }
635 template <typename A, typename B, typename... Ts>
636 bool isOneOf(A K1, B K2, Ts... Ks) const {
637 return is(K1) || isOneOf(K2, Ks...);
638 }
639 template <typename T> bool isNot(T Kind) const { return !is(Kind); }
641 bool isIf(bool AllowConstexprMacro = true) const {
642 return is(tok::kw_if) || endsSequence(tok::kw_constexpr, tok::kw_if) ||
643 (endsSequence(tok::identifier, tok::kw_if) && AllowConstexprMacro);
644 }
645
646 bool closesScopeAfterBlock() const {
647 if (getBlockKind() == BK_Block)
648 return true;
649 if (closesScope())
651 return false;
652 }
653
654 /// \c true if this token starts a sequence with the given tokens in order,
655 /// following the ``Next`` pointers, ignoring comments.
656 template <typename A, typename... Ts>
657 bool startsSequence(A K1, Ts... Tokens) const {
658 return startsSequenceInternal(K1, Tokens...);
659 }
660
661 /// \c true if this token ends a sequence with the given tokens in order,
662 /// following the ``Previous`` pointers, ignoring comments.
663 /// For example, given tokens [T1, T2, T3], the function returns true if
664 /// 3 tokens ending at this (ignoring comments) are [T3, T2, T1]. In other
665 /// words, the tokens passed to this function need to the reverse of the
666 /// order the tokens appear in code.
667 template <typename A, typename... Ts>
668 bool endsSequence(A K1, Ts... Tokens) const {
669 return endsSequenceInternal(K1, Tokens...);
670 }
671
673
674 bool isAttribute() const {
675 return isOneOf(tok::kw___attribute, tok::kw___declspec, TT_AttributeMacro);
677
679 return Tok.isObjCAtKeyword(Kind);
681
682 bool isAccessSpecifierKeyword() const {
683 return isOneOf(tok::kw_public, tok::kw_protected, tok::kw_private);
684 }
685
686 bool isAccessSpecifier(bool ColonRequired = true) const {
688 return false;
689 if (!ColonRequired)
690 return true;
691 const auto *NextNonComment = getNextNonComment();
692 return NextNonComment && NextNonComment->is(tok::colon);
693 }
694
696 return isOneOf(tok::kw_const, tok::kw_restrict, tok::kw_volatile,
697 tok::kw__Nonnull, tok::kw__Nullable,
698 tok::kw__Null_unspecified, tok::kw___ptr32, tok::kw___ptr64,
699 tok::kw___funcref) ||
701 }
702
703 [[nodiscard]] bool isTypeName(const LangOptions &LangOpts) const;
704 [[nodiscard]] bool isTypeOrIdentifier(const LangOptions &LangOpts) const;
705
706 bool isObjCAccessSpecifier() const {
707 return is(tok::at) && Next &&
708 (Next->isObjCAtKeyword(tok::objc_public) ||
709 Next->isObjCAtKeyword(tok::objc_protected) ||
710 Next->isObjCAtKeyword(tok::objc_package) ||
711 Next->isObjCAtKeyword(tok::objc_private));
712 }
713
714 /// Returns whether \p Tok is ([{ or an opening < of a template or in
715 /// protos.
716 bool opensScope() const {
717 if (is(TT_TemplateString) && TokenText.ends_with("${"))
718 return true;
719 if (is(TT_DictLiteral) && is(tok::less))
720 return true;
721 return isOneOf(tok::l_paren, tok::l_brace, tok::l_square,
722 TT_TemplateOpener);
723 }
724 /// Returns whether \p Tok is )]} or a closing > of a template or in
725 /// protos.
726 bool closesScope() const {
727 if (is(TT_TemplateString) && TokenText.starts_with("}"))
728 return true;
729 if (is(TT_DictLiteral) && is(tok::greater))
730 return true;
731 return isOneOf(tok::r_paren, tok::r_brace, tok::r_square,
732 TT_TemplateCloser);
733 }
734
735 /// Returns \c true if this is a "." or "->" accessing a member.
736 bool isMemberAccess() const {
737 return isOneOf(tok::arrow, tok::period, tok::arrowstar) &&
738 !isOneOf(TT_DesignatedInitializerPeriod, TT_TrailingReturnArrow,
739 TT_LambdaArrow, TT_LeadingJavaAnnotation);
741
742 bool isPointerOrReference() const {
743 return isOneOf(tok::star, tok::amp, tok::ampamp);
744 }
745
747 assert(!TokenText.empty());
748 if (!isalpha(TokenText[0]))
749 return false;
750
751 switch (Tok.getKind()) {
752 case tok::ampamp:
753 case tok::ampequal:
754 case tok::amp:
755 case tok::pipe:
756 case tok::tilde:
757 case tok::exclaim:
758 case tok::exclaimequal:
759 case tok::pipepipe:
760 case tok::pipeequal:
761 case tok::caret:
762 case tok::caretequal:
763 return true;
764 default:
765 return false;
766 }
767 }
768
769 bool isUnaryOperator() const {
770 switch (Tok.getKind()) {
771 case tok::plus:
772 case tok::plusplus:
773 case tok::minus:
774 case tok::minusminus:
775 case tok::exclaim:
776 case tok::tilde:
777 case tok::kw_sizeof:
778 case tok::kw_alignof:
779 return true;
780 default:
781 return false;
782 }
783 }
785 bool isBinaryOperator() const {
786 // Comma is a binary operator, but does not behave as such wrt. formatting.
787 return getPrecedence() > prec::Comma;
788 }
789
790 bool isTrailingComment() const {
791 return is(tok::comment) &&
792 (is(TT_LineComment) || !Next || Next->NewlinesBefore > 0);
793 }
794
795 /// Returns \c true if this is a keyword that can be used
796 /// like a function call (e.g. sizeof, typeid, ...).
797 bool isFunctionLikeKeyword() const {
798 if (isAttribute())
799 return true;
800
801 return isOneOf(tok::kw_throw, tok::kw_typeid, tok::kw_return,
802 tok::kw_sizeof, tok::kw_alignof, tok::kw_alignas,
803 tok::kw_decltype, tok::kw_noexcept, tok::kw_static_assert,
804 tok::kw__Atomic,
805#define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) tok::kw___##Trait,
806#include "clang/Basic/TransformTypeTraits.def"
807 tok::kw_requires);
808 }
809
810 /// Returns \c true if this is a string literal that's like a label,
811 /// e.g. ends with "=" or ":".
812 bool isLabelString() const {
813 if (isNot(tok::string_literal))
814 return false;
815 StringRef Content = TokenText;
816 if (Content.starts_with("\"") || Content.starts_with("'"))
817 Content = Content.drop_front(1);
818 if (Content.ends_with("\"") || Content.ends_with("'"))
819 Content = Content.drop_back(1);
820 Content = Content.trim();
821 return Content.size() > 1 &&
822 (Content.back() == ':' || Content.back() == '=');
823 }
825 /// Returns actual token start location without leading escaped
826 /// newlines and whitespace.
827 ///
828 /// This can be different to Tok.getLocation(), which includes leading escaped
829 /// newlines.
831 return WhitespaceRange.getEnd();
832 }
833
834 /// Returns \c true if the range of whitespace immediately preceding the \c
835 /// Token is not empty.
836 bool hasWhitespaceBefore() const {
838 }
839
840 prec::Level getPrecedence() const {
843 return getBinOpPrecedence(Tok.getKind(), /*GreaterThanIsOperator=*/true,
844 /*CPlusPlus11=*/true);
845 }
846
847 /// Returns the previous token ignoring comments.
848 [[nodiscard]] FormatToken *getPreviousNonComment() const {
850 while (Tok && Tok->is(tok::comment))
851 Tok = Tok->Previous;
852 return Tok;
853 }
854
855 /// Returns the next token ignoring comments.
856 [[nodiscard]] FormatToken *getNextNonComment() const {
858 while (Tok && Tok->is(tok::comment))
859 Tok = Tok->Next;
860 return Tok;
861 }
862
863 /// Returns \c true if this token ends a block indented initializer list.
864 [[nodiscard]] bool isBlockIndentedInitRBrace(const FormatStyle &Style) const;
865
866 /// Returns \c true if this tokens starts a block-type list, i.e. a
867 /// list that should be indented with a block indent.
868 [[nodiscard]] bool opensBlockOrBlockTypeList(const FormatStyle &Style) const;
869
870 /// Returns whether the token is the left square bracket of a C++
871 /// structured binding declaration.
872 bool isCppStructuredBinding(bool IsCpp) const {
873 if (!IsCpp || isNot(tok::l_square))
874 return false;
875 const FormatToken *T = this;
876 do {
877 T = T->getPreviousNonComment();
878 } while (T && T->isOneOf(tok::kw_const, tok::kw_volatile, tok::amp,
879 tok::ampamp));
880 return T && T->is(tok::kw_auto);
881 }
882
883 /// Same as opensBlockOrBlockTypeList, but for the closing token.
884 bool closesBlockOrBlockTypeList(const FormatStyle &Style) const {
885 if (is(TT_TemplateString) && closesScope())
886 return true;
888 }
889
890 /// Return the actual namespace token, if this token starts a namespace
891 /// block.
892 const FormatToken *getNamespaceToken() const {
893 const FormatToken *NamespaceTok = this;
894 if (is(tok::comment))
895 NamespaceTok = NamespaceTok->getNextNonComment();
896 // Detect "(inline|export)? namespace" in the beginning of a line.
897 if (NamespaceTok && NamespaceTok->isOneOf(tok::kw_inline, tok::kw_export))
898 NamespaceTok = NamespaceTok->getNextNonComment();
899 return NamespaceTok &&
900 NamespaceTok->isOneOf(tok::kw_namespace, TT_NamespaceMacro)
901 ? NamespaceTok
902 : nullptr;
903 }
904
905 void copyFrom(const FormatToken &Tok) { *this = Tok; }
906
907private:
908 // Only allow copying via the explicit copyFrom method.
909 FormatToken(const FormatToken &) = delete;
910 FormatToken &operator=(const FormatToken &) = default;
911
912 template <typename A, typename... Ts>
913 bool startsSequenceInternal(A K1, Ts... Tokens) const {
914 if (is(tok::comment) && Next)
915 return Next->startsSequenceInternal(K1, Tokens...);
916 return is(K1) && Next && Next->startsSequenceInternal(Tokens...);
917 }
918
919 template <typename A> bool startsSequenceInternal(A K1) const {
920 if (is(tok::comment) && Next)
921 return Next->startsSequenceInternal(K1);
922 return is(K1);
923 }
924
925 template <typename A, typename... Ts> bool endsSequenceInternal(A K1) const {
926 if (is(tok::comment) && Previous)
927 return Previous->endsSequenceInternal(K1);
928 return is(K1);
929 }
930
931 template <typename A, typename... Ts>
932 bool endsSequenceInternal(A K1, Ts... Tokens) const {
933 if (is(tok::comment) && Previous)
934 return Previous->endsSequenceInternal(K1, Tokens...);
935 return is(K1) && Previous && Previous->endsSequenceInternal(Tokens...);
937};
940struct LineState;
941
942class TokenRole {
943public:
945 virtual ~TokenRole();
946
947 /// After the \c TokenAnnotator has finished annotating all the tokens,
948 /// this function precomputes required information for formatting.
949 virtual void precomputeFormattingInfos(const FormatToken *Token);
950
951 /// Apply the special formatting that the given role demands.
952 ///
953 /// Assumes that the token having this role is already formatted.
954 ///
955 /// Continues formatting from \p State leaving indentation to \p Indenter and
956 /// returns the total penalty that this formatting incurs.
957 virtual unsigned formatFromToken(LineState &State,
959 bool DryRun) {
960 return 0;
961 }
962
963 /// Same as \c formatFromToken, but assumes that the first token has
964 /// already been set thereby deciding on the first line break.
965 virtual unsigned formatAfterToken(LineState &State,
967 bool DryRun) {
968 return 0;
969 }
970
971 /// Notifies the \c Role that a comma was found.
972 virtual void CommaFound(const FormatToken *Token) {}
973
974 virtual const FormatToken *lastComma() { return nullptr; }
975
976protected:
977 const FormatStyle &Style;
978};
979
980class CommaSeparatedList : public TokenRole {
981public:
983 : TokenRole(Style), HasNestedBracedList(false) {}
984
985 void precomputeFormattingInfos(const FormatToken *Token) override;
986
987 unsigned formatAfterToken(LineState &State, ContinuationIndenter *Indenter,
988 bool DryRun) override;
989
991 bool DryRun) override;
993 /// Adds \p Token as the next comma to the \c CommaSeparated list.
994 void CommaFound(const FormatToken *Token) override {
995 Commas.push_back(Token);
996 }
997
998 const FormatToken *lastComma() override {
999 if (Commas.empty())
1000 return nullptr;
1001 return Commas.back();
1002 }
1003
1004private:
1005 /// A struct that holds information on how to format a given list with
1006 /// a specific number of columns.
1007 struct ColumnFormat {
1008 /// The number of columns to use.
1009 unsigned Columns;
1010
1011 /// The total width in characters.
1012 unsigned TotalWidth;
1013
1014 /// The number of lines required for this format.
1015 unsigned LineCount;
1016
1017 /// The size of each column in characters.
1018 SmallVector<unsigned, 8> ColumnSizes;
1019 };
1020
1021 /// Calculate which \c ColumnFormat fits best into
1022 /// \p RemainingCharacters.
1023 const ColumnFormat *getColumnFormat(unsigned RemainingCharacters) const;
1024
1025 /// The ordered \c FormatTokens making up the commas of this list.
1026 SmallVector<const FormatToken *, 8> Commas;
1027
1028 /// The length of each of the list's items in characters including the
1029 /// trailing comma.
1030 SmallVector<unsigned, 8> ItemLengths;
1031
1032 /// Precomputed formats that can be used for this list.
1033 SmallVector<ColumnFormat, 4> Formats;
1035 bool HasNestedBracedList;
1036};
1037
1038/// Encapsulates keywords that are context sensitive or for languages not
1039/// properly supported by Clang's lexer.
1040struct AdditionalKeywords {
1041 AdditionalKeywords(IdentifierTable &IdentTable) {
1042 kw_final = &IdentTable.get("final");
1043 kw_override = &IdentTable.get("override");
1044 kw_in = &IdentTable.get("in");
1045 kw_of = &IdentTable.get("of");
1046 kw_CF_CLOSED_ENUM = &IdentTable.get("CF_CLOSED_ENUM");
1047 kw_CF_ENUM = &IdentTable.get("CF_ENUM");
1048 kw_CF_OPTIONS = &IdentTable.get("CF_OPTIONS");
1049 kw_NS_CLOSED_ENUM = &IdentTable.get("NS_CLOSED_ENUM");
1050 kw_NS_ENUM = &IdentTable.get("NS_ENUM");
1051 kw_NS_ERROR_ENUM = &IdentTable.get("NS_ERROR_ENUM");
1052 kw_NS_OPTIONS = &IdentTable.get("NS_OPTIONS");
1053
1054 kw_as = &IdentTable.get("as");
1055 kw_async = &IdentTable.get("async");
1056 kw_await = &IdentTable.get("await");
1057 kw_declare = &IdentTable.get("declare");
1058 kw_finally = &IdentTable.get("finally");
1059 kw_from = &IdentTable.get("from");
1060 kw_function = &IdentTable.get("function");
1061 kw_get = &IdentTable.get("get");
1062 kw_import = &IdentTable.get("import");
1063 kw_infer = &IdentTable.get("infer");
1064 kw_is = &IdentTable.get("is");
1065 kw_let = &IdentTable.get("let");
1066 kw_module = &IdentTable.get("module");
1067 kw_readonly = &IdentTable.get("readonly");
1068 kw_set = &IdentTable.get("set");
1069 kw_type = &IdentTable.get("type");
1070 kw_typeof = &IdentTable.get("typeof");
1071 kw_var = &IdentTable.get("var");
1072 kw_yield = &IdentTable.get("yield");
1073
1074 kw_abstract = &IdentTable.get("abstract");
1075 kw_assert = &IdentTable.get("assert");
1076 kw_extends = &IdentTable.get("extends");
1077 kw_implements = &IdentTable.get("implements");
1078 kw_instanceof = &IdentTable.get("instanceof");
1079 kw_interface = &IdentTable.get("interface");
1080 kw_native = &IdentTable.get("native");
1081 kw_package = &IdentTable.get("package");
1082 kw_synchronized = &IdentTable.get("synchronized");
1083 kw_throws = &IdentTable.get("throws");
1084 kw___except = &IdentTable.get("__except");
1085 kw___has_include = &IdentTable.get("__has_include");
1086 kw___has_include_next = &IdentTable.get("__has_include_next");
1087
1088 kw_mark = &IdentTable.get("mark");
1089 kw_region = &IdentTable.get("region");
1090
1091 kw_extend = &IdentTable.get("extend");
1092 kw_option = &IdentTable.get("option");
1093 kw_optional = &IdentTable.get("optional");
1094 kw_repeated = &IdentTable.get("repeated");
1095 kw_required = &IdentTable.get("required");
1096 kw_returns = &IdentTable.get("returns");
1097
1098 kw_signals = &IdentTable.get("signals");
1099 kw_qsignals = &IdentTable.get("Q_SIGNALS");
1100 kw_slots = &IdentTable.get("slots");
1101 kw_qslots = &IdentTable.get("Q_SLOTS");
1102
1103 // For internal clang-format use.
1105 &IdentTable.get("__CLANG_FORMAT_INTERNAL_IDENT_AFTER_DEFINE__");
1106
1107 // C# keywords
1108 kw_dollar = &IdentTable.get("dollar");
1109 kw_base = &IdentTable.get("base");
1110 kw_byte = &IdentTable.get("byte");
1111 kw_checked = &IdentTable.get("checked");
1112 kw_decimal = &IdentTable.get("decimal");
1113 kw_delegate = &IdentTable.get("delegate");
1114 kw_event = &IdentTable.get("event");
1115 kw_fixed = &IdentTable.get("fixed");
1116 kw_foreach = &IdentTable.get("foreach");
1117 kw_init = &IdentTable.get("init");
1118 kw_implicit = &IdentTable.get("implicit");
1119 kw_internal = &IdentTable.get("internal");
1120 kw_lock = &IdentTable.get("lock");
1121 kw_null = &IdentTable.get("null");
1122 kw_object = &IdentTable.get("object");
1123 kw_out = &IdentTable.get("out");
1124 kw_params = &IdentTable.get("params");
1125 kw_ref = &IdentTable.get("ref");
1126 kw_string = &IdentTable.get("string");
1127 kw_stackalloc = &IdentTable.get("stackalloc");
1128 kw_sbyte = &IdentTable.get("sbyte");
1129 kw_sealed = &IdentTable.get("sealed");
1130 kw_uint = &IdentTable.get("uint");
1131 kw_ulong = &IdentTable.get("ulong");
1132 kw_unchecked = &IdentTable.get("unchecked");
1133 kw_unsafe = &IdentTable.get("unsafe");
1134 kw_ushort = &IdentTable.get("ushort");
1135 kw_when = &IdentTable.get("when");
1136 kw_where = &IdentTable.get("where");
1137
1138 // Verilog keywords
1139 kw_always = &IdentTable.get("always");
1140 kw_always_comb = &IdentTable.get("always_comb");
1141 kw_always_ff = &IdentTable.get("always_ff");
1142 kw_always_latch = &IdentTable.get("always_latch");
1143 kw_assign = &IdentTable.get("assign");
1144 kw_assume = &IdentTable.get("assume");
1145 kw_automatic = &IdentTable.get("automatic");
1146 kw_before = &IdentTable.get("before");
1147 kw_begin = &IdentTable.get("begin");
1148 kw_begin_keywords = &IdentTable.get("begin_keywords");
1149 kw_bins = &IdentTable.get("bins");
1150 kw_binsof = &IdentTable.get("binsof");
1151 kw_casex = &IdentTable.get("casex");
1152 kw_casez = &IdentTable.get("casez");
1153 kw_celldefine = &IdentTable.get("celldefine");
1154 kw_checker = &IdentTable.get("checker");
1155 kw_clocking = &IdentTable.get("clocking");
1156 kw_constraint = &IdentTable.get("constraint");
1157 kw_cover = &IdentTable.get("cover");
1158 kw_covergroup = &IdentTable.get("covergroup");
1159 kw_coverpoint = &IdentTable.get("coverpoint");
1160 kw_default_decay_time = &IdentTable.get("default_decay_time");
1161 kw_default_nettype = &IdentTable.get("default_nettype");
1162 kw_default_trireg_strength = &IdentTable.get("default_trireg_strength");
1163 kw_delay_mode_distributed = &IdentTable.get("delay_mode_distributed");
1164 kw_delay_mode_path = &IdentTable.get("delay_mode_path");
1165 kw_delay_mode_unit = &IdentTable.get("delay_mode_unit");
1166 kw_delay_mode_zero = &IdentTable.get("delay_mode_zero");
1167 kw_disable = &IdentTable.get("disable");
1168 kw_dist = &IdentTable.get("dist");
1169 kw_edge = &IdentTable.get("edge");
1170 kw_elsif = &IdentTable.get("elsif");
1171 kw_end = &IdentTable.get("end");
1172 kw_end_keywords = &IdentTable.get("end_keywords");
1173 kw_endcase = &IdentTable.get("endcase");
1174 kw_endcelldefine = &IdentTable.get("endcelldefine");
1175 kw_endchecker = &IdentTable.get("endchecker");
1176 kw_endclass = &IdentTable.get("endclass");
1177 kw_endclocking = &IdentTable.get("endclocking");
1178 kw_endfunction = &IdentTable.get("endfunction");
1179 kw_endgenerate = &IdentTable.get("endgenerate");
1180 kw_endgroup = &IdentTable.get("endgroup");
1181 kw_endinterface = &IdentTable.get("endinterface");
1182 kw_endmodule = &IdentTable.get("endmodule");
1183 kw_endpackage = &IdentTable.get("endpackage");
1184 kw_endprimitive = &IdentTable.get("endprimitive");
1185 kw_endprogram = &IdentTable.get("endprogram");
1186 kw_endproperty = &IdentTable.get("endproperty");
1187 kw_endsequence = &IdentTable.get("endsequence");
1188 kw_endspecify = &IdentTable.get("endspecify");
1189 kw_endtable = &IdentTable.get("endtable");
1190 kw_endtask = &IdentTable.get("endtask");
1191 kw_forever = &IdentTable.get("forever");
1192 kw_fork = &IdentTable.get("fork");
1193 kw_generate = &IdentTable.get("generate");
1194 kw_highz0 = &IdentTable.get("highz0");
1195 kw_highz1 = &IdentTable.get("highz1");
1196 kw_iff = &IdentTable.get("iff");
1197 kw_ifnone = &IdentTable.get("ifnone");
1198 kw_ignore_bins = &IdentTable.get("ignore_bins");
1199 kw_illegal_bins = &IdentTable.get("illegal_bins");
1200 kw_initial = &IdentTable.get("initial");
1201 kw_inout = &IdentTable.get("inout");
1202 kw_input = &IdentTable.get("input");
1203 kw_inside = &IdentTable.get("inside");
1204 kw_interconnect = &IdentTable.get("interconnect");
1205 kw_intersect = &IdentTable.get("intersect");
1206 kw_join = &IdentTable.get("join");
1207 kw_join_any = &IdentTable.get("join_any");
1208 kw_join_none = &IdentTable.get("join_none");
1209 kw_large = &IdentTable.get("large");
1210 kw_local = &IdentTable.get("local");
1211 kw_localparam = &IdentTable.get("localparam");
1212 kw_macromodule = &IdentTable.get("macromodule");
1213 kw_matches = &IdentTable.get("matches");
1214 kw_medium = &IdentTable.get("medium");
1215 kw_negedge = &IdentTable.get("negedge");
1216 kw_nounconnected_drive = &IdentTable.get("nounconnected_drive");
1217 kw_output = &IdentTable.get("output");
1218 kw_packed = &IdentTable.get("packed");
1219 kw_parameter = &IdentTable.get("parameter");
1220 kw_posedge = &IdentTable.get("posedge");
1221 kw_primitive = &IdentTable.get("primitive");
1222 kw_priority = &IdentTable.get("priority");
1223 kw_program = &IdentTable.get("program");
1224 kw_property = &IdentTable.get("property");
1225 kw_pull0 = &IdentTable.get("pull0");
1226 kw_pull1 = &IdentTable.get("pull1");
1227 kw_pure = &IdentTable.get("pure");
1228 kw_rand = &IdentTable.get("rand");
1229 kw_randc = &IdentTable.get("randc");
1230 kw_randcase = &IdentTable.get("randcase");
1231 kw_randsequence = &IdentTable.get("randsequence");
1232 kw_repeat = &IdentTable.get("repeat");
1233 kw_resetall = &IdentTable.get("resetall");
1234 kw_sample = &IdentTable.get("sample");
1235 kw_scalared = &IdentTable.get("scalared");
1236 kw_sequence = &IdentTable.get("sequence");
1237 kw_small = &IdentTable.get("small");
1238 kw_soft = &IdentTable.get("soft");
1239 kw_solve = &IdentTable.get("solve");
1240 kw_specify = &IdentTable.get("specify");
1241 kw_specparam = &IdentTable.get("specparam");
1242 kw_strong0 = &IdentTable.get("strong0");
1243 kw_strong1 = &IdentTable.get("strong1");
1244 kw_supply0 = &IdentTable.get("supply0");
1245 kw_supply1 = &IdentTable.get("supply1");
1246 kw_table = &IdentTable.get("table");
1247 kw_tagged = &IdentTable.get("tagged");
1248 kw_task = &IdentTable.get("task");
1249 kw_timescale = &IdentTable.get("timescale");
1250 kw_tri = &IdentTable.get("tri");
1251 kw_tri0 = &IdentTable.get("tri0");
1252 kw_tri1 = &IdentTable.get("tri1");
1253 kw_triand = &IdentTable.get("triand");
1254 kw_trior = &IdentTable.get("trior");
1255 kw_trireg = &IdentTable.get("trireg");
1256 kw_unconnected_drive = &IdentTable.get("unconnected_drive");
1257 kw_undefineall = &IdentTable.get("undefineall");
1258 kw_unique = &IdentTable.get("unique");
1259 kw_unique0 = &IdentTable.get("unique0");
1260 kw_uwire = &IdentTable.get("uwire");
1261 kw_vectored = &IdentTable.get("vectored");
1262 kw_wand = &IdentTable.get("wand");
1263 kw_weak0 = &IdentTable.get("weak0");
1264 kw_weak1 = &IdentTable.get("weak1");
1265 kw_wildcard = &IdentTable.get("wildcard");
1266 kw_wire = &IdentTable.get("wire");
1267 kw_with = &IdentTable.get("with");
1268 kw_wor = &IdentTable.get("wor");
1269
1270 // Symbols that are treated as keywords.
1271 kw_verilogHash = &IdentTable.get("#");
1272 kw_verilogHashHash = &IdentTable.get("##");
1273 kw_apostrophe = &IdentTable.get("\'");
1274
1275 // TableGen keywords
1276 kw_bit = &IdentTable.get("bit");
1277 kw_bits = &IdentTable.get("bits");
1278 kw_code = &IdentTable.get("code");
1279 kw_dag = &IdentTable.get("dag");
1280 kw_def = &IdentTable.get("def");
1281 kw_defm = &IdentTable.get("defm");
1282 kw_defset = &IdentTable.get("defset");
1283 kw_defvar = &IdentTable.get("defvar");
1284 kw_dump = &IdentTable.get("dump");
1285 kw_include = &IdentTable.get("include");
1286 kw_list = &IdentTable.get("list");
1287 kw_multiclass = &IdentTable.get("multiclass");
1288 kw_then = &IdentTable.get("then");
1289
1290 // Keep this at the end of the constructor to make sure everything here
1291 // is
1292 // already initialized.
1293 JsExtraKeywords = std::unordered_set<IdentifierInfo *>(
1297 // Keywords from the Java section.
1299
1300 CSharpExtraKeywords = std::unordered_set<IdentifierInfo *>(
1307 // Keywords from the JavaScript section.
1311 // Keywords from the Java section.
1313
1314 // Some keywords are not included here because they don't need special
1315 // treatment like `showcancelled` or they should be treated as identifiers
1316 // like `int` and `logic`.
1317 VerilogExtraKeywords = std::unordered_set<IdentifierInfo *>(
1372 kw_tri, kw_tri0,
1380 kw_with, kw_wor,
1382
1383 TableGenExtraKeywords = std::unordered_set<IdentifierInfo *>({
1384 kw_assert,
1385 kw_bit,
1386 kw_bits,
1387 kw_code,
1388 kw_dag,
1389 kw_def,
1390 kw_defm,
1391 kw_defset,
1392 kw_defvar,
1393 kw_dump,
1394 kw_foreach,
1395 kw_in,
1396 kw_include,
1397 kw_let,
1398 kw_list,
1402 });
1405 // Context sensitive keywords.
1421 // JavaScript keywords.
1442 // Java keywords.
1454 // Pragma keywords.
1458 // Proto keywords.
1465
1466 // QT keywords.
1472 // For internal use by clang-format.
1475 // C# keywords
1509 // Verilog keywords
1641 // Workaround for hashes and backticks in Verilog.
1645 // Symbols in Verilog that don't exist in C++.
1648 // TableGen keywords
1662
1663 /// Returns \c true if \p Tok is a keyword or an identifier.
1664 bool isWordLike(const FormatToken &Tok, bool IsVerilog = true) const {
1665 // getIdentifierinfo returns non-null for keywords as well as identifiers.
1666 return Tok.Tok.getIdentifierInfo() &&
1667 (!IsVerilog || !isVerilogKeywordSymbol(Tok));
1668 }
1670 /// Returns \c true if \p Tok is a true JavaScript identifier, returns
1671 /// \c false if it is a keyword or a pseudo keyword.
1672 /// If \c AcceptIdentifierName is true, returns true not only for keywords,
1673 // but also for IdentifierName tokens (aka pseudo-keywords), such as
1674 // ``yield``.
1675 bool isJavaScriptIdentifier(const FormatToken &Tok,
1676 bool AcceptIdentifierName = true) const {
1677 // Based on the list of JavaScript & TypeScript keywords here:
1678 // https://github.com/microsoft/TypeScript/blob/main/src/compiler/scanner.ts#L74
1679 if (Tok.isAccessSpecifierKeyword())
1680 return false;
1681 switch (Tok.Tok.getKind()) {
1682 case tok::kw_break:
1683 case tok::kw_case:
1684 case tok::kw_catch:
1685 case tok::kw_class:
1686 case tok::kw_continue:
1687 case tok::kw_const:
1688 case tok::kw_default:
1689 case tok::kw_delete:
1690 case tok::kw_do:
1691 case tok::kw_else:
1692 case tok::kw_enum:
1693 case tok::kw_export:
1694 case tok::kw_false:
1695 case tok::kw_for:
1696 case tok::kw_if:
1697 case tok::kw_import:
1698 case tok::kw_module:
1699 case tok::kw_new:
1700 case tok::kw_return:
1701 case tok::kw_static:
1702 case tok::kw_switch:
1703 case tok::kw_this:
1704 case tok::kw_throw:
1705 case tok::kw_true:
1706 case tok::kw_try:
1707 case tok::kw_typeof:
1708 case tok::kw_void:
1709 case tok::kw_while:
1710 // These are JS keywords that are lexed by LLVM/clang as keywords.
1711 return false;
1712 case tok::identifier: {
1713 // For identifiers, make sure they are true identifiers, excluding the
1714 // JavaScript pseudo-keywords (not lexed by LLVM/clang as keywords).
1715 bool IsPseudoKeyword =
1716 JsExtraKeywords.find(Tok.Tok.getIdentifierInfo()) !=
1717 JsExtraKeywords.end();
1718 return AcceptIdentifierName || !IsPseudoKeyword;
1719 }
1720 default:
1721 // Other keywords are handled in the switch below, to avoid problems due
1722 // to duplicate case labels when using the #include trick.
1723 break;
1724 }
1725
1726 switch (Tok.Tok.getKind()) {
1727 // Handle C++ keywords not included above: these are all JS identifiers.
1728#define KEYWORD(X, Y) case tok::kw_##X:
1729#include "clang/Basic/TokenKinds.def"
1730 // #undef KEYWORD is not needed -- it's #undef-ed at the end of
1731 // TokenKinds.def
1732 return true;
1733 default:
1734 // All other tokens (punctuation etc) are not JS identifiers.
1735 return false;
1736 }
1737 }
1738
1739 /// Returns \c true if \p Tok is a C# keyword, returns
1740 /// \c false if it is a anything else.
1741 bool isCSharpKeyword(const FormatToken &Tok) const {
1742 if (Tok.isAccessSpecifierKeyword())
1743 return true;
1744 switch (Tok.Tok.getKind()) {
1745 case tok::kw_bool:
1746 case tok::kw_break:
1747 case tok::kw_case:
1748 case tok::kw_catch:
1749 case tok::kw_char:
1750 case tok::kw_class:
1751 case tok::kw_const:
1752 case tok::kw_continue:
1753 case tok::kw_default:
1754 case tok::kw_do:
1755 case tok::kw_double:
1756 case tok::kw_else:
1757 case tok::kw_enum:
1758 case tok::kw_explicit:
1759 case tok::kw_extern:
1760 case tok::kw_false:
1761 case tok::kw_float:
1762 case tok::kw_for:
1763 case tok::kw_goto:
1764 case tok::kw_if:
1765 case tok::kw_int:
1766 case tok::kw_long:
1767 case tok::kw_namespace:
1768 case tok::kw_new:
1769 case tok::kw_operator:
1770 case tok::kw_return:
1771 case tok::kw_short:
1772 case tok::kw_sizeof:
1773 case tok::kw_static:
1774 case tok::kw_struct:
1775 case tok::kw_switch:
1776 case tok::kw_this:
1777 case tok::kw_throw:
1778 case tok::kw_true:
1779 case tok::kw_try:
1780 case tok::kw_typeof:
1781 case tok::kw_using:
1782 case tok::kw_virtual:
1783 case tok::kw_void:
1784 case tok::kw_volatile:
1785 case tok::kw_while:
1786 return true;
1787 default:
1788 return Tok.is(tok::identifier) &&
1789 CSharpExtraKeywords.find(Tok.Tok.getIdentifierInfo()) ==
1790 CSharpExtraKeywords.end();
1791 }
1793
1794 bool isVerilogKeywordSymbol(const FormatToken &Tok) const {
1796 }
1798 bool isVerilogWordOperator(const FormatToken &Tok) const {
1800 kw_with);
1801 }
1802
1803 bool isVerilogIdentifier(const FormatToken &Tok) const {
1804 switch (Tok.Tok.getKind()) {
1805 case tok::kw_case:
1806 case tok::kw_class:
1807 case tok::kw_const:
1808 case tok::kw_continue:
1809 case tok::kw_default:
1810 case tok::kw_do:
1811 case tok::kw_extern:
1812 case tok::kw_else:
1813 case tok::kw_enum:
1814 case tok::kw_for:
1815 case tok::kw_if:
1816 case tok::kw_restrict:
1817 case tok::kw_signed:
1818 case tok::kw_static:
1819 case tok::kw_struct:
1820 case tok::kw_typedef:
1821 case tok::kw_union:
1822 case tok::kw_unsigned:
1823 case tok::kw_virtual:
1824 case tok::kw_while:
1825 return false;
1826 case tok::identifier:
1827 return isWordLike(Tok) &&
1828 VerilogExtraKeywords.find(Tok.Tok.getIdentifierInfo()) ==
1829 VerilogExtraKeywords.end();
1830 default:
1831 // getIdentifierInfo returns non-null for both identifiers and keywords.
1832 return Tok.Tok.getIdentifierInfo();
1834 }
1835
1836 /// Returns whether \p Tok is a Verilog preprocessor directive. This is
1837 /// needed because macro expansions start with a backtick as well and they
1838 /// need to be treated differently.
1839 bool isVerilogPPDirective(const FormatToken &Tok) const {
1840 auto Info = Tok.Tok.getIdentifierInfo();
1841 if (!Info)
1842 return false;
1843 switch (Info->getPPKeywordID()) {
1844 case tok::pp_define:
1845 case tok::pp_else:
1846 case tok::pp_endif:
1847 case tok::pp_ifdef:
1848 case tok::pp_ifndef:
1849 case tok::pp_include:
1850 case tok::pp_line:
1851 case tok::pp_pragma:
1852 case tok::pp_undef:
1853 return true;
1854 default:
1855 return Tok.isOneOf(kw_begin_keywords, kw_celldefine,
1862 }
1863 }
1864
1865 /// Returns whether \p Tok is a Verilog keyword that opens a block.
1866 bool isVerilogBegin(const FormatToken &Tok) const {
1867 // `table` is not included since it needs to be treated specially.
1868 return !Tok.endsSequence(kw_fork, kw_disable) &&
1869 Tok.isOneOf(kw_begin, kw_fork, kw_generate, kw_specify);
1870 }
1871
1872 /// Returns whether \p Tok is a Verilog keyword that closes a block.
1873 bool isVerilogEnd(const FormatToken &Tok) const {
1874 return !Tok.endsSequence(kw_join, kw_rand) &&
1875 Tok.isOneOf(TT_MacroBlockEnd, kw_end, kw_endcase, kw_endclass,
1882 }
1883
1884 /// Returns whether \p Tok is a Verilog keyword that opens a module, etc.
1885 bool isVerilogHierarchy(const FormatToken &Tok) const {
1887 return false;
1888 if (Tok.is(kw_property)) {
1889 const FormatToken *Prev = Tok.getPreviousNonComment();
1890 return !(Prev &&
1891 Prev->isOneOf(tok::kw_restrict, kw_assert, kw_assume, kw_cover));
1892 }
1893 return Tok.isOneOf(tok::kw_case, tok::kw_class, kw_function, kw_module,
1897 kw_task);
1898 }
1899
1900 bool isVerilogEndOfLabel(const FormatToken &Tok) const {
1901 const FormatToken *Next = Tok.getNextNonComment();
1902 // In Verilog the colon in a default label is optional.
1903 return Tok.is(TT_CaseLabelColon) ||
1904 (Tok.is(tok::kw_default) &&
1905 !(Next && Next->isOneOf(tok::colon, tok::semi, kw_clocking, kw_iff,
1907 }
1908
1909 /// Returns whether \p Tok is a Verilog keyword that starts a
1910 /// structured procedure like 'always'.
1911 bool isVerilogStructuredProcedure(const FormatToken &Tok) const {
1914 }
1915
1916 bool isVerilogQualifier(const FormatToken &Tok) const {
1917 switch (Tok.Tok.getKind()) {
1918 case tok::kw_extern:
1919 case tok::kw_signed:
1920 case tok::kw_static:
1921 case tok::kw_unsigned:
1922 case tok::kw_virtual:
1923 return true;
1924 case tok::identifier:
1925 return Tok.isOneOf(
1932 default:
1933 return false;
1934 }
1935 }
1937 bool isTableGenDefinition(const FormatToken &Tok) const {
1939 kw_let, tok::kw_class);
1940 }
1941
1942 bool isTableGenKeyword(const FormatToken &Tok) const {
1943 switch (Tok.Tok.getKind()) {
1944 case tok::kw_class:
1945 case tok::kw_else:
1946 case tok::kw_false:
1947 case tok::kw_if:
1948 case tok::kw_int:
1949 case tok::kw_true:
1950 return true;
1951 default:
1952 return Tok.is(tok::identifier) &&
1953 TableGenExtraKeywords.find(Tok.Tok.getIdentifierInfo()) !=
1954 TableGenExtraKeywords.end();
1955 }
1956 }
1957
1958private:
1959 /// The JavaScript keywords beyond the C++ keyword set.
1960 std::unordered_set<IdentifierInfo *> JsExtraKeywords;
1961
1962 /// The C# keywords beyond the C++ keyword set
1963 std::unordered_set<IdentifierInfo *> CSharpExtraKeywords;
1964
1965 /// The Verilog keywords beyond the C++ keyword set.
1966 std::unordered_set<IdentifierInfo *> VerilogExtraKeywords;
1967
1968 /// The TableGen keywords beyond the C++ keyword set.
1969 std::unordered_set<IdentifierInfo *> TableGenExtraKeywords;
1970};
1971
1972inline bool isLineComment(const FormatToken &FormatTok) {
1973 return FormatTok.is(tok::comment) && !FormatTok.TokenText.starts_with("/*");
1974}
1975
1976// Checks if \p FormatTok is a line comment that continues the line comment
1977// \p Previous. The original column of \p MinColumnToken is used to determine
1978// whether \p FormatTok is indented enough to the right to continue \p Previous.
1979inline bool continuesLineComment(const FormatToken &FormatTok,
1980 const FormatToken *Previous,
1981 const FormatToken *MinColumnToken) {
1982 if (!Previous || !MinColumnToken)
1983 return false;
1984 unsigned MinContinueColumn =
1985 MinColumnToken->OriginalColumn + (isLineComment(*MinColumnToken) ? 0 : 1);
1986 return isLineComment(FormatTok) && FormatTok.NewlinesBefore == 1 &&
1988 FormatTok.OriginalColumn >= MinContinueColumn;
1989}
1990
1991// Returns \c true if \c Current starts a new parameter.
1992bool startsNextParameter(const FormatToken &Current, const FormatStyle &Style);
1993
1994} // namespace format
1995} // namespace clang
1996
1997#endif
enum clang::sema::@1704::IndirectLocalPathEntry::EntryKind Kind
const Decl * D
#define LIST_TOKEN_TYPES
Definition: FormatToken.h:27
Various functions to configurably format source code.
Defines the clang::IdentifierInfo, clang::IdentifierTable, and clang::Selector interfaces.
Defines and computes precedence levels for binary/ternary operators.
static constexpr bool isOneOf()
#define TRANSFORM_TYPE_TRAIT_DEF(Enum, _)
Definition: Type.h:5998
StateNode * Previous
ContinuationIndenter * Indenter
One of these records is kept for each identifier that is lexed.
tok::PPKeywordKind getPPKeywordID() const
Return the preprocessor keyword ID for this identifier.
Implements an efficient mapping from strings to IdentifierInfo nodes.
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:502
Encodes a location in the source.
A trivial tuple used to represent a source range.
SourceLocation getEnd() const
SourceLocation getBegin() const
Token - This structure provides full information about a lexed token.
Definition: Token.h:36
IdentifierInfo * getIdentifierInfo() const
Definition: Token.h:187
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:99
tok::TokenKind getKind() const
Definition: Token.h:94
bool isObjCAtKeyword(tok::ObjCKeywordKind objcKey) const
Return true if we have an ObjC keyword identifier.
Definition: Lexer.cpp:60
The base class of the type hierarchy.
Definition: Type.h:1828
unsigned formatFromToken(LineState &State, ContinuationIndenter *Indenter, bool DryRun) override
Apply the special formatting that the given role demands.
void CommaFound(const FormatToken *Token) override
Adds Token as the next comma to the CommaSeparated list.
Definition: FormatToken.h:988
const FormatToken * lastComma() override
Definition: FormatToken.h:992
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...
Definition: FormatToken.cpp:89
void precomputeFormattingInfos(const FormatToken *Token) override
After the TokenAnnotator has finished annotating all the tokens, this function precomputes required i...
virtual unsigned formatAfterToken(LineState &State, ContinuationIndenter *Indenter, bool DryRun)
Same as formatFromToken, but assumes that the first token has already been set thereby deciding on th...
Definition: FormatToken.h:959
virtual void precomputeFormattingInfos(const FormatToken *Token)
After the TokenAnnotator has finished annotating all the tokens, this function precomputes required i...
Definition: FormatToken.cpp:87
const FormatStyle & Style
Definition: FormatToken.h:971
virtual void CommaFound(const FormatToken *Token)
Notifies the Role that a comma was found.
Definition: FormatToken.h:966
virtual const FormatToken * lastComma()
Definition: FormatToken.h:968
virtual unsigned formatFromToken(LineState &State, ContinuationIndenter *Indenter, bool DryRun)
Apply the special formatting that the given role demands.
Definition: FormatToken.h:951
const char * getTokenTypeName(TokenType Type)
Determines the name of a token type.
Definition: FormatToken.cpp:24
MacroRole
Roles a token can take in a configured macro expansion.
Definition: FormatToken.h:233
@ MR_UnexpandedArg
The token is part of a macro argument that was previously formatted as expansion when formatting the ...
Definition: FormatToken.h:239
@ MR_Hidden
The token was expanded from a macro definition, and is not visible as part of the macro call.
Definition: FormatToken.h:242
@ MR_ExpandedArg
The token was expanded from a macro argument when formatting the expanded token sequence.
Definition: FormatToken.h:236
bool continuesLineComment(const FormatToken &FormatTok, const FormatToken *Previous, const FormatToken *MinColumnToken)
Definition: FormatToken.h:1973
bool isLineComment(const FormatToken &FormatTok)
Definition: FormatToken.h:1966
TokenType
Determines the semantic type of a syntactic token, e.g.
Definition: FormatToken.h:214
bool startsNextParameter(const FormatToken &Current, const FormatStyle &Style)
bool isStringLiteral(TokenKind K)
Return true if this is a C or C++ string-literal (or C++11 user-defined-string-literal) token.
Definition: TokenKinds.h:89
ObjCKeywordKind
Provides a namespace for Objective-C keywords which start with an '@'.
Definition: TokenKinds.h:41
TokenKind
Provides a simple uniform namespace for tokens from all C languages.
Definition: TokenKinds.h:25
PPKeywordKind
Provides a namespace for preprocessor keywords which start with a '#' at the beginning of the line.
Definition: TokenKinds.h:33
The JSON file list parser is used to communicate input to InstallAPI.
prec::Level getBinOpPrecedence(tok::TokenKind Kind, bool GreaterThanIsOperator, bool CPlusPlus11)
Return the precedence of the specified binary operator token.
const FunctionProtoType * T
#define false
Definition: stdbool.h:26
Encapsulates keywords that are context sensitive or for languages not properly supported by Clang's l...
Definition: FormatToken.h:1034
bool isVerilogEnd(const FormatToken &Tok) const
Returns whether Tok is a Verilog keyword that closes a block.
Definition: FormatToken.h:1867
IdentifierInfo * kw_nounconnected_drive
Definition: FormatToken.h:1581
bool isWordLike(const FormatToken &Tok, bool IsVerilog=true) const
Returns true if Tok is a keyword or an identifier.
Definition: FormatToken.h:1658
bool isVerilogBegin(const FormatToken &Tok) const
Returns whether Tok is a Verilog keyword that opens a block.
Definition: FormatToken.h:1860
bool isJavaScriptIdentifier(const FormatToken &Tok, bool AcceptIdentifierName=true) const
Returns true if Tok is a true JavaScript identifier, returns false if it is a keyword or a pseudo key...
Definition: FormatToken.h:1669
bool isVerilogQualifier(const FormatToken &Tok) const
Definition: FormatToken.h:1910
IdentifierInfo * kw_default_trireg_strength
Definition: FormatToken.h:1527
bool isVerilogStructuredProcedure(const FormatToken &Tok) const
Returns whether Tok is a Verilog keyword that starts a structured procedure like 'always'.
Definition: FormatToken.h:1905
bool isVerilogEndOfLabel(const FormatToken &Tok) const
Definition: FormatToken.h:1894
bool isVerilogWordOperator(const FormatToken &Tok) const
Definition: FormatToken.h:1792
IdentifierInfo * kw_delay_mode_distributed
Definition: FormatToken.h:1528
bool isTableGenKeyword(const FormatToken &Tok) const
Definition: FormatToken.h:1936
bool isVerilogKeywordSymbol(const FormatToken &Tok) const
Definition: FormatToken.h:1788
IdentifierInfo * kw_default_decay_time
Definition: FormatToken.h:1525
bool isCSharpKeyword(const FormatToken &Tok) const
Returns true if Tok is a C# keyword, returns false if it is a anything else.
Definition: FormatToken.h:1735
IdentifierInfo * kw___has_include_next
Definition: FormatToken.h:1413
bool isVerilogHierarchy(const FormatToken &Tok) const
Returns whether Tok is a Verilog keyword that opens a module, etc.
Definition: FormatToken.h:1879
bool isVerilogPPDirective(const FormatToken &Tok) const
Returns whether Tok is a Verilog preprocessor directive.
Definition: FormatToken.h:1833
IdentifierInfo * kw_unconnected_drive
Definition: FormatToken.h:1621
IdentifierInfo * kw_internal_ident_after_define
Definition: FormatToken.h:1467
bool isTableGenDefinition(const FormatToken &Tok) const
Definition: FormatToken.h:1931
bool isVerilogIdentifier(const FormatToken &Tok) const
Definition: FormatToken.h:1797
The FormatStyle is used to configure the formatting to follow specific guidelines.
Definition: Format.h:55
A wrapper around a Token storing information about the whitespace characters preceding it.
Definition: FormatToken.h:299
unsigned NestingLevel
The nesting level of this token, i.e.
Definition: FormatToken.h:522
unsigned MustBreakBeforeFinalized
Whether MustBreakBefore is finalized during parsing and must not be reset between runs.
Definition: FormatToken.h:348
bool isMemberAccess() const
Returns true if this is a "." or "->" accessing a member.
Definition: FormatToken.h:730
unsigned FakeRParens
Insert this many fake ) after this token for correct indentation.
Definition: FormatToken.h:554
bool ArrayInitializerLineStart
This notes the start of the line of an array initializer.
Definition: FormatToken.h:577
bool isTypeFinalized() const
Definition: FormatToken.h:459
bool Optional
Is optional and can be removed.
Definition: FormatToken.h:583
bool MacroParent
When macro expansion introduces nodes with children, those are marked as MacroParent.
Definition: FormatToken.h:612
int Newlines
The number of newlines immediately before the Token after formatting.
Definition: FormatToken.h:474
SmallVector< AnnotatedLine *, 1 > Children
If this token starts a block, this contains all the unwrapped lines in it.
Definition: FormatToken.h:599
bool closesScopeAfterBlock() const
Definition: FormatToken.h:640
bool isObjCAtKeyword(tok::ObjCKeywordKind Kind) const
Definition: FormatToken.h:672
prec::Level ForcedPrecedence
Used to set an operator precedence explicitly.
Definition: FormatToken.h:462
bool closesBlockOrBlockTypeList(const FormatStyle &Style) const
Same as opensBlockOrBlockTypeList, but for the closing token.
Definition: FormatToken.h:878
unsigned BindingStrength
The binding strength of a token.
Definition: FormatToken.h:518
bool isObjCAccessSpecifier() const
Definition: FormatToken.h:700
const FormatToken * getNamespaceToken() const
Return the actual namespace token, if this token starts a namespace block.
Definition: FormatToken.h:886
bool isTypeName(const LangOptions &LangOpts) const
Definition: FormatToken.cpp:44
unsigned StartsBinaryExpression
true if this token starts a binary expression, i.e.
Definition: FormatToken.h:361
void setPackingKind(ParameterPackingKind K)
Definition: FormatToken.h:420
unsigned ClosesTemplateDeclaration
true if this is the ">" of "template<..>".
Definition: FormatToken.h:357
unsigned OperatorIndex
If this is an operator (or "."/"->") in a sequence of operators with the same precedence,...
Definition: FormatToken.h:558
bool MightBeFunctionDeclParen
Might be function declaration open/closing paren.
Definition: FormatToken.h:586
unsigned OriginalColumn
The original 0-based column of this token, including expanded tabs.
Definition: FormatToken.h:509
unsigned ContinuesLineCommentSection
Does this line comment continue a line comment section?
Definition: FormatToken.h:373
unsigned CanBreakBefore
true if it is allowed to break before this token.
Definition: FormatToken.h:354
bool isCppAlternativeOperatorKeyword() const
Definition: FormatToken.h:740
bool isNot(T Kind) const
Definition: FormatToken.h:633
StringRef TokenText
The raw text of the token.
Definition: FormatToken.h:319
unsigned LongestObjCSelectorName
If this is the first ObjC selector name in an ObjC method definition or call, this contains the lengt...
Definition: FormatToken.h:535
ParameterPackingKind getPackingKind() const
Definition: FormatToken.h:417
SourceLocation getStartOfNonWhitespace() const
Returns actual token start location without leading escaped newlines and whitespace.
Definition: FormatToken.h:824
bool startsSequence(A K1, Ts... Tokens) const
true if this token starts a sequence with the given tokens in order, following the Next pointers,...
Definition: FormatToken.h:651
tok::TokenKind ParentBracket
If this is a bracket ("<", "(", "[" or "{"), contains the kind of the surrounding bracket.
Definition: FormatToken.h:501
unsigned LastNewlineOffset
The offset just past the last ' ' in this token's leading whitespace (relative to WhiteSpaceStart).
Definition: FormatToken.h:478
unsigned SplitPenalty
Penalty for inserting a line break before this token.
Definition: FormatToken.h:528
bool opensScope() const
Returns whether Tok is ([{ or an opening < of a template or in protos.
Definition: FormatToken.h:710
bool isPointerOrReference() const
Definition: FormatToken.h:736
FormatToken * getNextNonComment() const
Returns the next token ignoring comments.
Definition: FormatToken.h:850
void setDecision(FormatDecision D)
Definition: FormatToken.h:407
FormatToken * getPreviousNonComment() const
Returns the previous token ignoring comments.
Definition: FormatToken.h:842
SmallVector< prec::Level, 4 > FakeLParens
Stores the number of required fake parentheses and the corresponding operator precedence.
Definition: FormatToken.h:552
unsigned Finalized
If true, this token has been fully formatted (indented and potentially re-formatted inside),...
Definition: FormatToken.h:378
std::optional< MacroExpansion > MacroCtx
Definition: FormatToken.h:603
BraceBlockKind getBlockKind() const
Definition: FormatToken.h:391
FormatToken * Next
The next token in the unwrapped line.
Definition: FormatToken.h:571
unsigned IsMultiline
Whether the token text contains newlines (escaped or not).
Definition: FormatToken.h:335
unsigned EndsCppAttributeGroup
true if this token ends a group of C++ attributes.
Definition: FormatToken.h:384
unsigned NewlinesBefore
The number of newlines immediately before the Token.
Definition: FormatToken.h:468
void setBlockKind(BraceBlockKind BBK)
Definition: FormatToken.h:394
bool isIf(bool AllowConstexprMacro=true) const
Definition: FormatToken.h:635
unsigned SpacesRequiredBefore
The number of spaces that should be inserted before this token.
Definition: FormatToken.h:490
std::shared_ptr< TokenRole > Role
A token can have a special role that can carry extra information about the token's formatting.
Definition: FormatToken.h:325
unsigned MustBreakBefore
Whether there must be a line break before this token.
Definition: FormatToken.h:344
unsigned HasUnescapedNewline
Whether there is at least one unescaped newline before the Token.
Definition: FormatToken.h:332
unsigned PartOfMultiVariableDeclStmt
Is this token part of a DeclStmt defining multiple variables?
Definition: FormatToken.h:368
unsigned ColumnWidth
The width of the non-whitespace parts of the token (or its first line for multi-line tokens) in colum...
Definition: FormatToken.h:483
unsigned ObjCSelectorNameParts
If this is the first ObjC selector name in an ObjC method definition or call, this contains the numbe...
Definition: FormatToken.h:540
void setType(TokenType T)
Definition: FormatToken.h:433
bool HasFormFeedBefore
Has "\n\f\n" or "\n\f\r\n" before TokenText.
Definition: FormatToken.h:589
bool isFunctionLikeKeyword() const
Returns true if this is a keyword that can be used like a function call (e.g.
Definition: FormatToken.h:791
bool isStringLiteral() const
Definition: FormatToken.h:666
bool IsArrayInitializer
This starts an array initializer.
Definition: FormatToken.h:580
bool isBlockIndentedInitRBrace(const FormatStyle &Style) const
Returns true if this token ends a block indented initializer list.
Definition: FormatToken.cpp:57
bool closesScope() const
Returns whether Tok is )]} or a closing > of a template or in protos.
Definition: FormatToken.h:720
unsigned EndsBinaryExpression
true if this token ends a binary expression.
Definition: FormatToken.h:363
bool isBinaryOperator() const
Definition: FormatToken.h:779
bool isCppStructuredBinding(bool IsCpp) const
Returns whether the token is the left square bracket of a C++ structured binding declaration.
Definition: FormatToken.h:866
unsigned UnbreakableTailLength
The length of following tokens until the next natural split point, or the next token that can be brok...
Definition: FormatToken.h:513
prec::Level getPrecedence() const
Definition: FormatToken.h:834
FormatDecision getDecision() const
Definition: FormatToken.h:404
bool is(tok::TokenKind Kind) const
Definition: FormatToken.h:614
unsigned LastLineColumnWidth
Contains the width in columns of the last line of a multi-line token.
Definition: FormatToken.h:487
unsigned IndentLevel
The indent level of this token. Copied from the surrounding line.
Definition: FormatToken.h:525
bool opensBlockOrBlockTypeList(const FormatStyle &Style) const
Returns true if this tokens starts a block-type list, i.e.
Definition: FormatToken.cpp:72
unsigned BlockParameterCount
Number of parameters that are nested blocks, if this is "(", "[" or "<".
Definition: FormatToken.h:497
unsigned TotalLength
The total length of the unwrapped line up to and including this token.
Definition: FormatToken.h:505
bool hasWhitespaceBefore() const
Returns true if the range of whitespace immediately preceding the Token is not empty.
Definition: FormatToken.h:830
bool isOneOf(A K1, B K2) const
Definition: FormatToken.h:626
TokenType getType() const
Returns the token's type, e.g.
Definition: FormatToken.h:432
unsigned IsFirst
Indicates that this is the first token of the file.
Definition: FormatToken.h:338
bool isUnaryOperator() const
Definition: FormatToken.h:763
unsigned IsUnterminatedLiteral
Set to true if this token is an unterminated literal.
Definition: FormatToken.h:351
bool isTrailingComment() const
Definition: FormatToken.h:784
unsigned ClosesRequiresClause
true if this is the last token within requires clause.
Definition: FormatToken.h:381
unsigned ParameterIndex
The 0-based index of the parameter/argument.
Definition: FormatToken.h:545
int8_t BraceCount
Number of optional braces to be inserted after this token: -1: a single left brace 0: no braces >0: n...
Definition: FormatToken.h:595
bool isAccessSpecifierKeyword() const
Definition: FormatToken.h:676
bool canBePointerOrReferenceQualifier() const
Definition: FormatToken.h:689
unsigned ParameterCount
Number of parameters, if this is "(", "[" or "<".
Definition: FormatToken.h:493
bool isAccessSpecifier(bool ColonRequired=true) const
Definition: FormatToken.h:680
bool StartsColumn
The first token in set of column elements.
Definition: FormatToken.h:574
bool isTypeOrIdentifier(const LangOptions &LangOpts) const
Definition: FormatToken.cpp:53
SourceRange WhitespaceRange
The range of the whitespace immediately preceding the Token.
Definition: FormatToken.h:328
FormatToken * NextOperator
If this is an operator (or "."/"->") in a sequence of operators with the same precedence,...
Definition: FormatToken.h:562
FormatToken * MatchingParen
If this is a bracket, this points to the matching one.
Definition: FormatToken.h:565
void copyFrom(const FormatToken &Tok)
Definition: FormatToken.h:899
void overwriteFixedType(TokenType T)
Definition: FormatToken.h:453
FormatToken * Previous
The previous token in the unwrapped line.
Definition: FormatToken.h:568
bool isLabelString() const
Returns true if this is a string literal that's like a label, e.g.
Definition: FormatToken.h:806
bool endsSequence(A K1, Ts... Tokens) const
true if this token ends a sequence with the given tokens in order, following the Previous pointers,...
Definition: FormatToken.h:662
void setFinalizedType(TokenType T)
Sets the type and also the finalized flag.
Definition: FormatToken.h:447
The current state when indenting a unwrapped line.
Contains information on the token's role in a macro expansion.
Definition: FormatToken.h:272
llvm::SmallVector< FormatToken *, 1 > ExpandedFrom
The stack of macro call identifier tokens this token was expanded from.
Definition: FormatToken.h:284
unsigned StartOfExpansion
The number of expansions of which this macro is the first entry.
Definition: FormatToken.h:287
MacroRole Role
The token's role in the macro expansion.
Definition: FormatToken.h:281
unsigned EndOfExpansion
The number of currently open expansions in ExpandedFrom this macro is the last token in.
Definition: FormatToken.h:291