1 //===--- FormatToken.h - Format C++ code ------------------------*- C++ -*-===//
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
7 //===----------------------------------------------------------------------===//
10 /// This file contains the declaration of the FormatToken, a wrapper
11 /// around Token with additional information related to formatting.
13 //===----------------------------------------------------------------------===//
15 #ifndef LLVM_CLANG_LIB_FORMAT_FORMATTOKEN_H
16 #define LLVM_CLANG_LIB_FORMAT_FORMATTOKEN_H
18 #include "clang/Basic/IdentifierTable.h"
19 #include "clang/Basic/OperatorPrecedence.h"
20 #include "clang/Format/Format.h"
21 #include "clang/Lex/Lexer.h"
24 #include <unordered_set>
29 #define LIST_TOKEN_TYPES \
30 TYPE(ArrayInitializerLSquare) \
31 TYPE(ArraySubscriptLSquare) \
32 TYPE(AttributeColon) \
33 TYPE(AttributeMacro) \
34 TYPE(AttributeParen) \
35 TYPE(AttributeSquare) \
36 TYPE(BinaryOperator) \
39 TYPE(BracedListLBrace) \
40 /* The colon at the end of a case label. */ \
41 TYPE(CaseLabelColon) \
44 TYPE(CompoundRequirementLBrace) \
45 /* ternary ?: expression */ \
46 TYPE(ConditionalExpr) \
47 /* the condition in an if statement */ \
48 TYPE(ConditionLParen) \
49 TYPE(ConflictAlternative) \
52 /* l_brace of if/for/while */ \
53 TYPE(ControlStatementLBrace) \
55 TYPE(CSharpGenericTypeConstraint) \
56 TYPE(CSharpGenericTypeConstraintColon) \
57 TYPE(CSharpGenericTypeConstraintComma) \
58 TYPE(CSharpNamedArgumentColon) \
59 TYPE(CSharpNullable) \
60 TYPE(CSharpNullConditionalLSquare) \
61 TYPE(CSharpStringLiteral) \
62 TYPE(CtorInitializerColon) \
63 TYPE(CtorInitializerComma) \
64 TYPE(DesignatedInitializerLSquare) \
65 TYPE(DesignatedInitializerPeriod) \
71 TYPE(FunctionAnnotationRParen) \
72 TYPE(FunctionDeclarationName) \
73 TYPE(FunctionLBrace) \
74 TYPE(FunctionLikeOrFreestandingMacro) \
75 TYPE(FunctionTypeLParen) \
76 /* The colons as part of a C11 _Generic selection */ \
77 TYPE(GenericSelectionColon) \
78 /* The colon at the end of a goto label. */ \
79 TYPE(GotoLabelColon) \
81 TYPE(ImplicitStringLiteral) \
82 TYPE(InheritanceColon) \
83 TYPE(InheritanceComma) \
84 TYPE(InlineASMBrace) \
85 TYPE(InlineASMColon) \
86 TYPE(InlineASMSymbolicNameLSquare) \
87 TYPE(JavaAnnotation) \
89 TYPE(JsComputedPropertyName) \
90 TYPE(JsExponentiation) \
91 TYPE(JsExponentiationEqual) \
92 TYPE(JsPipePipeEqual) \
93 TYPE(JsPrivateIdentifier) \
95 TYPE(JsTypeOperator) \
96 TYPE(JsTypeOptionalQuestion) \
100 TYPE(LeadingJavaAnnotation) \
102 TYPE(MacroBlockBegin) \
103 TYPE(MacroBlockEnd) \
104 TYPE(ModulePartitionColon) \
105 TYPE(NamespaceMacro) \
106 TYPE(NonNullAssertion) \
107 TYPE(NullCoalescingEqual) \
108 TYPE(NullCoalescingOperator) \
109 TYPE(NullPropagatingOperator) \
110 TYPE(ObjCBlockLBrace) \
111 TYPE(ObjCBlockLParen) \
114 TYPE(ObjCMethodExpr) \
115 TYPE(ObjCMethodSpecifier) \
117 TYPE(ObjCStringLiteral) \
118 TYPE(OverloadedOperator) \
119 TYPE(OverloadedOperatorLParen) \
120 TYPE(PointerOrReference) \
121 TYPE(ProtoExtensionLSquare) \
122 TYPE(PureVirtualSpecifier) \
123 TYPE(RangeBasedForLoopColon) \
126 TYPE(RequiresClause) \
127 TYPE(RequiresClauseInARequiresExpression) \
128 TYPE(RequiresExpression) \
129 TYPE(RequiresExpressionLBrace) \
130 TYPE(RequiresExpressionLParen) \
133 TYPE(StatementAttributeLikeMacro) \
134 TYPE(StatementMacro) \
136 TYPE(StructuredBindingLSquare) \
137 TYPE(TemplateCloser) \
138 TYPE(TemplateOpener) \
139 TYPE(TemplateString) \
140 TYPE(TrailingAnnotation) \
141 TYPE(TrailingReturnArrow) \
142 TYPE(TrailingUnaryOperator) \
143 TYPE(TypeDeclarationParen) \
144 TYPE(TypenameMacro) \
145 TYPE(UnaryOperator) \
147 TYPE(UntouchableMacroFunc) \
148 /* Like in 'assign x = 0, y = 1;' . */ \
149 TYPE(VerilogAssignComma) \
150 /* like in begin : block */ \
151 TYPE(VerilogBlockLabelColon) \
152 /* The square bracket for the dimension part of the type name. \
153 * In 'logic [1:0] x[1:0]', only the first '['. This way we can have space \
154 * before the first bracket but not the second. */ \
155 TYPE(VerilogDimensionedTypeName) \
156 /* list of port connections or parameters in a module instantiation */ \
157 TYPE(VerilogInstancePortComma) \
158 TYPE(VerilogInstancePortLParen) \
159 /* A parenthesized list within which line breaks are inserted by the \
160 * formatter, for example the list of ports in a module header. */ \
161 TYPE(VerilogMultiLineListLParen) \
162 /* for the base in a number literal, not including the quote */ \
163 TYPE(VerilogNumberBase) \
164 /* like `(strong1, pull0)` */ \
165 TYPE(VerilogStrength) \
166 /* Things inside the table in user-defined primitives. */ \
167 TYPE(VerilogTableItem) \
168 /* those that separate ports of different types */ \
169 TYPE(VerilogTypeComma) \
172 /// Determines the semantic type of a syntactic token, e.g. whether "<" is a
173 /// template opener or binary operator.
174 enum TokenType
: uint8_t {
175 #define TYPE(X) TT_##X,
181 /// Determines the name of a token type.
182 const char *getTokenTypeName(TokenType Type
);
184 // Represents what type of block a set of braces open.
185 enum BraceBlockKind
{ BK_Unknown
, BK_Block
, BK_BracedInit
};
187 // The packing kind of a function's parameters.
188 enum ParameterPackingKind
{ PPK_BinPacked
, PPK_OnePerLine
, PPK_Inconclusive
};
190 enum FormatDecision
{ FD_Unformatted
, FD_Continue
, FD_Break
};
192 /// Roles a token can take in a configured macro expansion.
194 /// The token was expanded from a macro argument when formatting the expanded
197 /// The token is part of a macro argument that was previously formatted as
198 /// expansion when formatting the unexpanded macro call.
200 /// The token was expanded from a macro definition, and is not visible as part
201 /// of the macro call.
207 /// Contains information on the token's role in a macro expansion.
209 /// Given the following definitions:
214 /// Consider the macro call:
215 /// A({B(C(C(x)))}) -> [{<x>}]
217 /// In this case, the tokens of the unexpanded macro call will have the
218 /// following relevant entries in their macro context (note that formatting
219 /// the unexpanded macro call happens *after* formatting the expanded macro
221 /// A( { B( C( C(x) ) ) } )
222 /// Role: NN U NN NN NNUN N N U N (N=None, U=UnexpandedArg)
225 /// Role: H E H E H E H (H=Hidden, E=ExpandedArg)
226 /// ExpandedFrom[0]: A A A A A A A
227 /// ExpandedFrom[1]: B B B
228 /// ExpandedFrom[2]: C
229 /// ExpandedFrom[3]: C
230 /// StartOfExpansion: 1 0 1 2 0 0 0
231 /// EndOfExpansion: 0 0 0 2 1 0 1
232 struct MacroExpansion
{
233 MacroExpansion(MacroRole Role
) : Role(Role
) {}
235 /// The token's role in the macro expansion.
236 /// When formatting an expanded macro, all tokens that are part of macro
237 /// arguments will be MR_ExpandedArg, while all tokens that are not visible in
238 /// the macro call will be MR_Hidden.
239 /// When formatting an unexpanded macro call, all tokens that are part of
240 /// macro arguments will be MR_UnexpandedArg.
243 /// The stack of macro call identifier tokens this token was expanded from.
244 llvm::SmallVector
<FormatToken
*, 1> ExpandedFrom
;
246 /// The number of expansions of which this macro is the first entry.
247 unsigned StartOfExpansion
= 0;
249 /// The number of currently open expansions in \c ExpandedFrom this macro is
250 /// the last token in.
251 unsigned EndOfExpansion
= 0;
257 /// A wrapper around a \c Token storing information about the
258 /// whitespace characters preceding it.
261 : HasUnescapedNewline(false), IsMultiline(false), IsFirst(false),
262 MustBreakBefore(false), IsUnterminatedLiteral(false),
263 CanBreakBefore(false), ClosesTemplateDeclaration(false),
264 StartsBinaryExpression(false), EndsBinaryExpression(false),
265 PartOfMultiVariableDeclStmt(false), ContinuesLineCommentSection(false),
266 Finalized(false), ClosesRequiresClause(false),
267 EndsCppAttributeGroup(false), BlockKind(BK_Unknown
),
268 Decision(FD_Unformatted
), PackingKind(PPK_Inconclusive
),
269 TypeIsFinalized(false), Type(TT_Unknown
) {}
274 /// The raw text of the token.
276 /// Contains the raw token text without leading whitespace and without leading
277 /// escaped newlines.
280 /// A token can have a special role that can carry extra information
281 /// about the token's formatting.
282 /// FIXME: Make FormatToken for parsing and AnnotatedToken two different
283 /// classes and make this a unique_ptr in the AnnotatedToken class.
284 std::shared_ptr
<TokenRole
> Role
;
286 /// The range of the whitespace immediately preceding the \c Token.
287 SourceRange WhitespaceRange
;
289 /// Whether there is at least one unescaped newline before the \c
291 unsigned HasUnescapedNewline
: 1;
293 /// Whether the token text contains newlines (escaped or not).
294 unsigned IsMultiline
: 1;
296 /// Indicates that this is the first token of the file.
297 unsigned IsFirst
: 1;
299 /// Whether there must be a line break before this token.
301 /// This happens for example when a preprocessor directive ended directly
302 /// before the token.
303 unsigned MustBreakBefore
: 1;
305 /// Set to \c true if this token is an unterminated literal.
306 unsigned IsUnterminatedLiteral
: 1;
308 /// \c true if it is allowed to break before this token.
309 unsigned CanBreakBefore
: 1;
311 /// \c true if this is the ">" of "template<..>".
312 unsigned ClosesTemplateDeclaration
: 1;
314 /// \c true if this token starts a binary expression, i.e. has at least
315 /// one fake l_paren with a precedence greater than prec::Unknown.
316 unsigned StartsBinaryExpression
: 1;
317 /// \c true if this token ends a binary expression.
318 unsigned EndsBinaryExpression
: 1;
320 /// Is this token part of a \c DeclStmt defining multiple variables?
322 /// Only set if \c Type == \c TT_StartOfName.
323 unsigned PartOfMultiVariableDeclStmt
: 1;
325 /// Does this line comment continue a line comment section?
327 /// Only set to true if \c Type == \c TT_LineComment.
328 unsigned ContinuesLineCommentSection
: 1;
330 /// If \c true, this token has been fully formatted (indented and
331 /// potentially re-formatted inside), and we do not allow further formatting
333 unsigned Finalized
: 1;
335 /// \c true if this is the last token within requires clause.
336 unsigned ClosesRequiresClause
: 1;
338 /// \c true if this token ends a group of C++ attributes.
339 unsigned EndsCppAttributeGroup
: 1;
342 /// Contains the kind of block if this token is a brace.
343 unsigned BlockKind
: 2;
346 BraceBlockKind
getBlockKind() const {
347 return static_cast<BraceBlockKind
>(BlockKind
);
349 void setBlockKind(BraceBlockKind BBK
) {
351 assert(getBlockKind() == BBK
&& "BraceBlockKind overflow!");
355 /// Stores the formatting decision for the token once it was made.
356 unsigned Decision
: 2;
359 FormatDecision
getDecision() const {
360 return static_cast<FormatDecision
>(Decision
);
362 void setDecision(FormatDecision D
) {
364 assert(getDecision() == D
&& "FormatDecision overflow!");
368 /// If this is an opening parenthesis, how are the parameters packed?
369 unsigned PackingKind
: 2;
372 ParameterPackingKind
getPackingKind() const {
373 return static_cast<ParameterPackingKind
>(PackingKind
);
375 void setPackingKind(ParameterPackingKind K
) {
377 assert(getPackingKind() == K
&& "ParameterPackingKind overflow!");
381 unsigned TypeIsFinalized
: 1;
385 /// Returns the token's type, e.g. whether "<" is a template opener or
387 TokenType
getType() const { return Type
; }
388 void setType(TokenType T
) {
389 // If this token is a macro argument while formatting an unexpanded macro
390 // call, we do not change its type any more - the type was deduced from
391 // formatting the expanded macro stream already.
392 if (MacroCtx
&& MacroCtx
->Role
== MR_UnexpandedArg
)
394 assert((!TypeIsFinalized
|| T
== Type
) &&
395 "Please use overwriteFixedType to change a fixed type.");
398 /// Sets the type and also the finalized flag. This prevents the type to be
399 /// reset in TokenAnnotator::resetTokenMetadata(). If the type needs to be set
400 /// to another one please use overwriteFixedType, or even better remove the
401 /// need to reassign the type.
402 void setFinalizedType(TokenType T
) {
404 TypeIsFinalized
= true;
406 void overwriteFixedType(TokenType T
) {
407 TypeIsFinalized
= false;
410 bool isTypeFinalized() const { return TypeIsFinalized
; }
412 /// Used to set an operator precedence explicitly.
413 prec::Level ForcedPrecedence
= prec::Unknown
;
415 /// The number of newlines immediately before the \c Token.
417 /// This can be used to determine what the user wrote in the original code
418 /// and thereby e.g. leave an empty line between two function definitions.
419 unsigned NewlinesBefore
= 0;
421 /// The offset just past the last '\n' in this token's leading
422 /// whitespace (relative to \c WhiteSpaceStart). 0 if there is no '\n'.
423 unsigned LastNewlineOffset
= 0;
425 /// The width of the non-whitespace parts of the token (or its first
426 /// line for multi-line tokens) in columns.
427 /// We need this to correctly measure number of columns a token spans.
428 unsigned ColumnWidth
= 0;
430 /// Contains the width in columns of the last line of a multi-line
432 unsigned LastLineColumnWidth
= 0;
434 /// The number of spaces that should be inserted before this token.
435 unsigned SpacesRequiredBefore
= 0;
437 /// Number of parameters, if this is "(", "[" or "<".
438 unsigned ParameterCount
= 0;
440 /// Number of parameters that are nested blocks,
441 /// if this is "(", "[" or "<".
442 unsigned BlockParameterCount
= 0;
444 /// If this is a bracket ("<", "(", "[" or "{"), contains the kind of
445 /// the surrounding bracket.
446 tok::TokenKind ParentBracket
= tok::unknown
;
448 /// The total length of the unwrapped line up to and including this
450 unsigned TotalLength
= 0;
452 /// The original 0-based column of this token, including expanded tabs.
453 /// The configured TabWidth is used as tab width.
454 unsigned OriginalColumn
= 0;
456 /// The length of following tokens until the next natural split point,
457 /// or the next token that can be broken.
458 unsigned UnbreakableTailLength
= 0;
460 // FIXME: Come up with a 'cleaner' concept.
461 /// The binding strength of a token. This is a combined value of
462 /// operator precedence, parenthesis nesting, etc.
463 unsigned BindingStrength
= 0;
465 /// The nesting level of this token, i.e. the number of surrounding (),
467 unsigned NestingLevel
= 0;
469 /// The indent level of this token. Copied from the surrounding line.
470 unsigned IndentLevel
= 0;
472 /// Penalty for inserting a line break before this token.
473 unsigned SplitPenalty
= 0;
475 /// If this is the first ObjC selector name in an ObjC method
476 /// definition or call, this contains the length of the longest name.
478 /// This being set to 0 means that the selectors should not be colon-aligned,
479 /// e.g. because several of them are block-type.
480 unsigned LongestObjCSelectorName
= 0;
482 /// If this is the first ObjC selector name in an ObjC method
483 /// definition or call, this contains the number of parts that the whole
484 /// selector consist of.
485 unsigned ObjCSelectorNameParts
= 0;
487 /// The 0-based index of the parameter/argument. For ObjC it is set
488 /// for the selector name token.
489 /// For now calculated only for ObjC.
490 unsigned ParameterIndex
= 0;
492 /// Stores the number of required fake parentheses and the
493 /// corresponding operator precedence.
495 /// If multiple fake parentheses start at a token, this vector stores them in
496 /// reverse order, i.e. inner fake parenthesis first.
497 SmallVector
<prec::Level
, 4> FakeLParens
;
498 /// Insert this many fake ) after this token for correct indentation.
499 unsigned FakeRParens
= 0;
501 /// If this is an operator (or "."/"->") in a sequence of operators
502 /// with the same precedence, contains the 0-based operator index.
503 unsigned OperatorIndex
= 0;
505 /// If this is an operator (or "."/"->") in a sequence of operators
506 /// with the same precedence, points to the next operator.
507 FormatToken
*NextOperator
= nullptr;
509 /// If this is a bracket, this points to the matching one.
510 FormatToken
*MatchingParen
= nullptr;
512 /// The previous token in the unwrapped line.
513 FormatToken
*Previous
= nullptr;
515 /// The next token in the unwrapped line.
516 FormatToken
*Next
= nullptr;
518 /// The first token in set of column elements.
519 bool StartsColumn
= false;
521 /// This notes the start of the line of an array initializer.
522 bool ArrayInitializerLineStart
= false;
524 /// This starts an array initializer.
525 bool IsArrayInitializer
= false;
527 /// Is optional and can be removed.
528 bool Optional
= false;
530 /// Number of optional braces to be inserted after this token:
531 /// -1: a single left brace
533 /// >0: number of right braces
534 int8_t BraceCount
= 0;
536 /// If this token starts a block, this contains all the unwrapped lines
538 SmallVector
<AnnotatedLine
*, 1> Children
;
540 // Contains all attributes related to how this token takes part
541 // in a configured macro expansion.
542 std::optional
<MacroExpansion
> MacroCtx
;
544 /// When macro expansion introduces nodes with children, those are marked as
546 /// FIXME: The formatting code currently hard-codes the assumption that
547 /// child nodes are introduced by blocks following an opening brace.
548 /// This is deeply baked into the code and disentangling this will require
549 /// signficant refactorings. \c MacroParent allows us to special-case the
550 /// cases in which we treat parents as block-openers for now.
551 bool MacroParent
= false;
553 bool is(tok::TokenKind Kind
) const { return Tok
.is(Kind
); }
554 bool is(TokenType TT
) const { return getType() == TT
; }
555 bool is(const IdentifierInfo
*II
) const {
556 return II
&& II
== Tok
.getIdentifierInfo();
558 bool is(tok::PPKeywordKind Kind
) const {
559 return Tok
.getIdentifierInfo() &&
560 Tok
.getIdentifierInfo()->getPPKeywordID() == Kind
;
562 bool is(BraceBlockKind BBK
) const { return getBlockKind() == BBK
; }
563 bool is(ParameterPackingKind PPK
) const { return getPackingKind() == PPK
; }
565 template <typename A
, typename B
> bool isOneOf(A K1
, B K2
) const {
566 return is(K1
) || is(K2
);
568 template <typename A
, typename B
, typename
... Ts
>
569 bool isOneOf(A K1
, B K2
, Ts
... Ks
) const {
570 return is(K1
) || isOneOf(K2
, Ks
...);
572 template <typename T
> bool isNot(T Kind
) const { return !is(Kind
); }
574 bool isIf(bool AllowConstexprMacro
= true) const {
575 return is(tok::kw_if
) || endsSequence(tok::kw_constexpr
, tok::kw_if
) ||
576 (endsSequence(tok::identifier
, tok::kw_if
) && AllowConstexprMacro
);
579 bool closesScopeAfterBlock() const {
580 if (getBlockKind() == BK_Block
)
583 return Previous
->closesScopeAfterBlock();
587 /// \c true if this token starts a sequence with the given tokens in order,
588 /// following the ``Next`` pointers, ignoring comments.
589 template <typename A
, typename
... Ts
>
590 bool startsSequence(A K1
, Ts
... Tokens
) const {
591 return startsSequenceInternal(K1
, Tokens
...);
594 /// \c true if this token ends a sequence with the given tokens in order,
595 /// following the ``Previous`` pointers, ignoring comments.
596 /// For example, given tokens [T1, T2, T3], the function returns true if
597 /// 3 tokens ending at this (ignoring comments) are [T3, T2, T1]. In other
598 /// words, the tokens passed to this function need to the reverse of the
599 /// order the tokens appear in code.
600 template <typename A
, typename
... Ts
>
601 bool endsSequence(A K1
, Ts
... Tokens
) const {
602 return endsSequenceInternal(K1
, Tokens
...);
605 bool isStringLiteral() const { return tok::isStringLiteral(Tok
.getKind()); }
607 bool isObjCAtKeyword(tok::ObjCKeywordKind Kind
) const {
608 return Tok
.isObjCAtKeyword(Kind
);
611 bool isAccessSpecifier(bool ColonRequired
= true) const {
612 if (!isOneOf(tok::kw_public
, tok::kw_protected
, tok::kw_private
))
616 const auto NextNonComment
= getNextNonComment();
617 return NextNonComment
&& NextNonComment
->is(tok::colon
);
620 bool canBePointerOrReferenceQualifier() const {
621 return isOneOf(tok::kw_const
, tok::kw_restrict
, tok::kw_volatile
,
622 tok::kw___attribute
, tok::kw__Nonnull
, tok::kw__Nullable
,
623 tok::kw__Null_unspecified
, tok::kw___ptr32
, tok::kw___ptr64
,
624 tok::kw___funcref
, TT_AttributeMacro
);
627 /// Determine whether the token is a simple-type-specifier.
628 [[nodiscard
]] bool isSimpleTypeSpecifier() const;
630 [[nodiscard
]] bool isTypeOrIdentifier() const;
632 bool isObjCAccessSpecifier() const {
633 return is(tok::at
) && Next
&&
634 (Next
->isObjCAtKeyword(tok::objc_public
) ||
635 Next
->isObjCAtKeyword(tok::objc_protected
) ||
636 Next
->isObjCAtKeyword(tok::objc_package
) ||
637 Next
->isObjCAtKeyword(tok::objc_private
));
640 /// Returns whether \p Tok is ([{ or an opening < of a template or in
642 bool opensScope() const {
643 if (is(TT_TemplateString
) && TokenText
.endswith("${"))
645 if (is(TT_DictLiteral
) && is(tok::less
))
647 return isOneOf(tok::l_paren
, tok::l_brace
, tok::l_square
,
650 /// Returns whether \p Tok is )]} or a closing > of a template or in
652 bool closesScope() const {
653 if (is(TT_TemplateString
) && TokenText
.startswith("}"))
655 if (is(TT_DictLiteral
) && is(tok::greater
))
657 return isOneOf(tok::r_paren
, tok::r_brace
, tok::r_square
,
661 /// Returns \c true if this is a "." or "->" accessing a member.
662 bool isMemberAccess() const {
663 return isOneOf(tok::arrow
, tok::period
, tok::arrowstar
) &&
664 !isOneOf(TT_DesignatedInitializerPeriod
, TT_TrailingReturnArrow
,
665 TT_LambdaArrow
, TT_LeadingJavaAnnotation
);
668 bool isUnaryOperator() const {
669 switch (Tok
.getKind()) {
673 case tok::minusminus
:
677 case tok::kw_alignof
:
684 bool isBinaryOperator() const {
685 // Comma is a binary operator, but does not behave as such wrt. formatting.
686 return getPrecedence() > prec::Comma
;
689 bool isTrailingComment() const {
690 return is(tok::comment
) &&
691 (is(TT_LineComment
) || !Next
|| Next
->NewlinesBefore
> 0);
694 /// Returns \c true if this is a keyword that can be used
695 /// like a function call (e.g. sizeof, typeid, ...).
696 bool isFunctionLikeKeyword() const {
697 switch (Tok
.getKind()) {
702 case tok::kw_alignof
:
703 case tok::kw_alignas
:
704 case tok::kw_decltype
:
705 case tok::kw_noexcept
:
706 case tok::kw_static_assert
:
707 case tok::kw__Atomic
:
708 case tok::kw___attribute
:
709 #define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case tok::kw___##Trait:
710 #include "clang/Basic/TransformTypeTraits.def"
711 case tok::kw_requires
:
718 /// Returns \c true if this is a string literal that's like a label,
719 /// e.g. ends with "=" or ":".
720 bool isLabelString() const {
721 if (!is(tok::string_literal
))
723 StringRef Content
= TokenText
;
724 if (Content
.startswith("\"") || Content
.startswith("'"))
725 Content
= Content
.drop_front(1);
726 if (Content
.endswith("\"") || Content
.endswith("'"))
727 Content
= Content
.drop_back(1);
728 Content
= Content
.trim();
729 return Content
.size() > 1 &&
730 (Content
.back() == ':' || Content
.back() == '=');
733 /// Returns actual token start location without leading escaped
734 /// newlines and whitespace.
736 /// This can be different to Tok.getLocation(), which includes leading escaped
738 SourceLocation
getStartOfNonWhitespace() const {
739 return WhitespaceRange
.getEnd();
742 /// Returns \c true if the range of whitespace immediately preceding the \c
743 /// Token is not empty.
744 bool hasWhitespaceBefore() const {
745 return WhitespaceRange
.getBegin() != WhitespaceRange
.getEnd();
748 prec::Level
getPrecedence() const {
749 if (ForcedPrecedence
!= prec::Unknown
)
750 return ForcedPrecedence
;
751 return getBinOpPrecedence(Tok
.getKind(), /*GreaterThanIsOperator=*/true,
752 /*CPlusPlus11=*/true);
755 /// Returns the previous token ignoring comments.
756 [[nodiscard
]] FormatToken
*getPreviousNonComment() const {
757 FormatToken
*Tok
= Previous
;
758 while (Tok
&& Tok
->is(tok::comment
))
763 /// Returns the next token ignoring comments.
764 [[nodiscard
]] FormatToken
*getNextNonComment() const {
765 FormatToken
*Tok
= Next
;
766 while (Tok
&& Tok
->is(tok::comment
))
771 /// Returns \c true if this tokens starts a block-type list, i.e. a
772 /// list that should be indented with a block indent.
773 [[nodiscard
]] bool opensBlockOrBlockTypeList(const FormatStyle
&Style
) const;
775 /// Returns whether the token is the left square bracket of a C++
776 /// structured binding declaration.
777 bool isCppStructuredBinding(const FormatStyle
&Style
) const {
778 if (!Style
.isCpp() || isNot(tok::l_square
))
780 const FormatToken
*T
= this;
782 T
= T
->getPreviousNonComment();
783 } while (T
&& T
->isOneOf(tok::kw_const
, tok::kw_volatile
, tok::amp
,
785 return T
&& T
->is(tok::kw_auto
);
788 /// Same as opensBlockOrBlockTypeList, but for the closing token.
789 bool closesBlockOrBlockTypeList(const FormatStyle
&Style
) const {
790 if (is(TT_TemplateString
) && closesScope())
792 return MatchingParen
&& MatchingParen
->opensBlockOrBlockTypeList(Style
);
795 /// Return the actual namespace token, if this token starts a namespace
797 const FormatToken
*getNamespaceToken() const {
798 const FormatToken
*NamespaceTok
= this;
799 if (is(tok::comment
))
800 NamespaceTok
= NamespaceTok
->getNextNonComment();
801 // Detect "(inline|export)? namespace" in the beginning of a line.
802 if (NamespaceTok
&& NamespaceTok
->isOneOf(tok::kw_inline
, tok::kw_export
))
803 NamespaceTok
= NamespaceTok
->getNextNonComment();
804 return NamespaceTok
&&
805 NamespaceTok
->isOneOf(tok::kw_namespace
, TT_NamespaceMacro
)
810 void copyFrom(const FormatToken
&Tok
) { *this = Tok
; }
813 // Only allow copying via the explicit copyFrom method.
814 FormatToken(const FormatToken
&) = delete;
815 FormatToken
&operator=(const FormatToken
&) = default;
817 template <typename A
, typename
... Ts
>
818 bool startsSequenceInternal(A K1
, Ts
... Tokens
) const {
819 if (is(tok::comment
) && Next
)
820 return Next
->startsSequenceInternal(K1
, Tokens
...);
821 return is(K1
) && Next
&& Next
->startsSequenceInternal(Tokens
...);
824 template <typename A
> bool startsSequenceInternal(A K1
) const {
825 if (is(tok::comment
) && Next
)
826 return Next
->startsSequenceInternal(K1
);
830 template <typename A
, typename
... Ts
> bool endsSequenceInternal(A K1
) const {
831 if (is(tok::comment
) && Previous
)
832 return Previous
->endsSequenceInternal(K1
);
836 template <typename A
, typename
... Ts
>
837 bool endsSequenceInternal(A K1
, Ts
... Tokens
) const {
838 if (is(tok::comment
) && Previous
)
839 return Previous
->endsSequenceInternal(K1
, Tokens
...);
840 return is(K1
) && Previous
&& Previous
->endsSequenceInternal(Tokens
...);
844 class ContinuationIndenter
;
849 TokenRole(const FormatStyle
&Style
) : Style(Style
) {}
850 virtual ~TokenRole();
852 /// After the \c TokenAnnotator has finished annotating all the tokens,
853 /// this function precomputes required information for formatting.
854 virtual void precomputeFormattingInfos(const FormatToken
*Token
);
856 /// Apply the special formatting that the given role demands.
858 /// Assumes that the token having this role is already formatted.
860 /// Continues formatting from \p State leaving indentation to \p Indenter and
861 /// returns the total penalty that this formatting incurs.
862 virtual unsigned formatFromToken(LineState
&State
,
863 ContinuationIndenter
*Indenter
,
868 /// Same as \c formatFromToken, but assumes that the first token has
869 /// already been set thereby deciding on the first line break.
870 virtual unsigned formatAfterToken(LineState
&State
,
871 ContinuationIndenter
*Indenter
,
876 /// Notifies the \c Role that a comma was found.
877 virtual void CommaFound(const FormatToken
*Token
) {}
879 virtual const FormatToken
*lastComma() { return nullptr; }
882 const FormatStyle
&Style
;
885 class CommaSeparatedList
: public TokenRole
{
887 CommaSeparatedList(const FormatStyle
&Style
)
888 : TokenRole(Style
), HasNestedBracedList(false) {}
890 void precomputeFormattingInfos(const FormatToken
*Token
) override
;
892 unsigned formatAfterToken(LineState
&State
, ContinuationIndenter
*Indenter
,
893 bool DryRun
) override
;
895 unsigned formatFromToken(LineState
&State
, ContinuationIndenter
*Indenter
,
896 bool DryRun
) override
;
898 /// Adds \p Token as the next comma to the \c CommaSeparated list.
899 void CommaFound(const FormatToken
*Token
) override
{
900 Commas
.push_back(Token
);
903 const FormatToken
*lastComma() override
{
906 return Commas
.back();
910 /// A struct that holds information on how to format a given list with
911 /// a specific number of columns.
912 struct ColumnFormat
{
913 /// The number of columns to use.
916 /// The total width in characters.
919 /// The number of lines required for this format.
922 /// The size of each column in characters.
923 SmallVector
<unsigned, 8> ColumnSizes
;
926 /// Calculate which \c ColumnFormat fits best into
927 /// \p RemainingCharacters.
928 const ColumnFormat
*getColumnFormat(unsigned RemainingCharacters
) const;
930 /// The ordered \c FormatTokens making up the commas of this list.
931 SmallVector
<const FormatToken
*, 8> Commas
;
933 /// The length of each of the list's items in characters including the
935 SmallVector
<unsigned, 8> ItemLengths
;
937 /// Precomputed formats that can be used for this list.
938 SmallVector
<ColumnFormat
, 4> Formats
;
940 bool HasNestedBracedList
;
943 /// Encapsulates keywords that are context sensitive or for languages not
944 /// properly supported by Clang's lexer.
945 struct AdditionalKeywords
{
946 AdditionalKeywords(IdentifierTable
&IdentTable
) {
947 kw_final
= &IdentTable
.get("final");
948 kw_override
= &IdentTable
.get("override");
949 kw_in
= &IdentTable
.get("in");
950 kw_of
= &IdentTable
.get("of");
951 kw_CF_CLOSED_ENUM
= &IdentTable
.get("CF_CLOSED_ENUM");
952 kw_CF_ENUM
= &IdentTable
.get("CF_ENUM");
953 kw_CF_OPTIONS
= &IdentTable
.get("CF_OPTIONS");
954 kw_NS_CLOSED_ENUM
= &IdentTable
.get("NS_CLOSED_ENUM");
955 kw_NS_ENUM
= &IdentTable
.get("NS_ENUM");
956 kw_NS_ERROR_ENUM
= &IdentTable
.get("NS_ERROR_ENUM");
957 kw_NS_OPTIONS
= &IdentTable
.get("NS_OPTIONS");
959 kw_as
= &IdentTable
.get("as");
960 kw_async
= &IdentTable
.get("async");
961 kw_await
= &IdentTable
.get("await");
962 kw_declare
= &IdentTable
.get("declare");
963 kw_finally
= &IdentTable
.get("finally");
964 kw_from
= &IdentTable
.get("from");
965 kw_function
= &IdentTable
.get("function");
966 kw_get
= &IdentTable
.get("get");
967 kw_import
= &IdentTable
.get("import");
968 kw_infer
= &IdentTable
.get("infer");
969 kw_is
= &IdentTable
.get("is");
970 kw_let
= &IdentTable
.get("let");
971 kw_module
= &IdentTable
.get("module");
972 kw_readonly
= &IdentTable
.get("readonly");
973 kw_set
= &IdentTable
.get("set");
974 kw_type
= &IdentTable
.get("type");
975 kw_typeof
= &IdentTable
.get("typeof");
976 kw_var
= &IdentTable
.get("var");
977 kw_yield
= &IdentTable
.get("yield");
979 kw_abstract
= &IdentTable
.get("abstract");
980 kw_assert
= &IdentTable
.get("assert");
981 kw_extends
= &IdentTable
.get("extends");
982 kw_implements
= &IdentTable
.get("implements");
983 kw_instanceof
= &IdentTable
.get("instanceof");
984 kw_interface
= &IdentTable
.get("interface");
985 kw_native
= &IdentTable
.get("native");
986 kw_package
= &IdentTable
.get("package");
987 kw_synchronized
= &IdentTable
.get("synchronized");
988 kw_throws
= &IdentTable
.get("throws");
989 kw___except
= &IdentTable
.get("__except");
990 kw___has_include
= &IdentTable
.get("__has_include");
991 kw___has_include_next
= &IdentTable
.get("__has_include_next");
993 kw_mark
= &IdentTable
.get("mark");
994 kw_region
= &IdentTable
.get("region");
996 kw_extend
= &IdentTable
.get("extend");
997 kw_option
= &IdentTable
.get("option");
998 kw_optional
= &IdentTable
.get("optional");
999 kw_repeated
= &IdentTable
.get("repeated");
1000 kw_required
= &IdentTable
.get("required");
1001 kw_returns
= &IdentTable
.get("returns");
1003 kw_signals
= &IdentTable
.get("signals");
1004 kw_qsignals
= &IdentTable
.get("Q_SIGNALS");
1005 kw_slots
= &IdentTable
.get("slots");
1006 kw_qslots
= &IdentTable
.get("Q_SLOTS");
1008 // For internal clang-format use.
1009 kw_internal_ident_after_define
=
1010 &IdentTable
.get("__CLANG_FORMAT_INTERNAL_IDENT_AFTER_DEFINE__");
1013 kw_dollar
= &IdentTable
.get("dollar");
1014 kw_base
= &IdentTable
.get("base");
1015 kw_byte
= &IdentTable
.get("byte");
1016 kw_checked
= &IdentTable
.get("checked");
1017 kw_decimal
= &IdentTable
.get("decimal");
1018 kw_delegate
= &IdentTable
.get("delegate");
1019 kw_event
= &IdentTable
.get("event");
1020 kw_fixed
= &IdentTable
.get("fixed");
1021 kw_foreach
= &IdentTable
.get("foreach");
1022 kw_init
= &IdentTable
.get("init");
1023 kw_implicit
= &IdentTable
.get("implicit");
1024 kw_internal
= &IdentTable
.get("internal");
1025 kw_lock
= &IdentTable
.get("lock");
1026 kw_null
= &IdentTable
.get("null");
1027 kw_object
= &IdentTable
.get("object");
1028 kw_out
= &IdentTable
.get("out");
1029 kw_params
= &IdentTable
.get("params");
1030 kw_ref
= &IdentTable
.get("ref");
1031 kw_string
= &IdentTable
.get("string");
1032 kw_stackalloc
= &IdentTable
.get("stackalloc");
1033 kw_sbyte
= &IdentTable
.get("sbyte");
1034 kw_sealed
= &IdentTable
.get("sealed");
1035 kw_uint
= &IdentTable
.get("uint");
1036 kw_ulong
= &IdentTable
.get("ulong");
1037 kw_unchecked
= &IdentTable
.get("unchecked");
1038 kw_unsafe
= &IdentTable
.get("unsafe");
1039 kw_ushort
= &IdentTable
.get("ushort");
1040 kw_when
= &IdentTable
.get("when");
1041 kw_where
= &IdentTable
.get("where");
1044 kw_always
= &IdentTable
.get("always");
1045 kw_always_comb
= &IdentTable
.get("always_comb");
1046 kw_always_ff
= &IdentTable
.get("always_ff");
1047 kw_always_latch
= &IdentTable
.get("always_latch");
1048 kw_assign
= &IdentTable
.get("assign");
1049 kw_assume
= &IdentTable
.get("assume");
1050 kw_automatic
= &IdentTable
.get("automatic");
1051 kw_before
= &IdentTable
.get("before");
1052 kw_begin
= &IdentTable
.get("begin");
1053 kw_begin_keywords
= &IdentTable
.get("begin_keywords");
1054 kw_bins
= &IdentTable
.get("bins");
1055 kw_binsof
= &IdentTable
.get("binsof");
1056 kw_casex
= &IdentTable
.get("casex");
1057 kw_casez
= &IdentTable
.get("casez");
1058 kw_celldefine
= &IdentTable
.get("celldefine");
1059 kw_checker
= &IdentTable
.get("checker");
1060 kw_clocking
= &IdentTable
.get("clocking");
1061 kw_constraint
= &IdentTable
.get("constraint");
1062 kw_cover
= &IdentTable
.get("cover");
1063 kw_covergroup
= &IdentTable
.get("covergroup");
1064 kw_coverpoint
= &IdentTable
.get("coverpoint");
1065 kw_default_decay_time
= &IdentTable
.get("default_decay_time");
1066 kw_default_nettype
= &IdentTable
.get("default_nettype");
1067 kw_default_trireg_strength
= &IdentTable
.get("default_trireg_strength");
1068 kw_delay_mode_distributed
= &IdentTable
.get("delay_mode_distributed");
1069 kw_delay_mode_path
= &IdentTable
.get("delay_mode_path");
1070 kw_delay_mode_unit
= &IdentTable
.get("delay_mode_unit");
1071 kw_delay_mode_zero
= &IdentTable
.get("delay_mode_zero");
1072 kw_disable
= &IdentTable
.get("disable");
1073 kw_dist
= &IdentTable
.get("dist");
1074 kw_edge
= &IdentTable
.get("edge");
1075 kw_elsif
= &IdentTable
.get("elsif");
1076 kw_end
= &IdentTable
.get("end");
1077 kw_end_keywords
= &IdentTable
.get("end_keywords");
1078 kw_endcase
= &IdentTable
.get("endcase");
1079 kw_endcelldefine
= &IdentTable
.get("endcelldefine");
1080 kw_endchecker
= &IdentTable
.get("endchecker");
1081 kw_endclass
= &IdentTable
.get("endclass");
1082 kw_endclocking
= &IdentTable
.get("endclocking");
1083 kw_endfunction
= &IdentTable
.get("endfunction");
1084 kw_endgenerate
= &IdentTable
.get("endgenerate");
1085 kw_endgroup
= &IdentTable
.get("endgroup");
1086 kw_endinterface
= &IdentTable
.get("endinterface");
1087 kw_endmodule
= &IdentTable
.get("endmodule");
1088 kw_endpackage
= &IdentTable
.get("endpackage");
1089 kw_endprimitive
= &IdentTable
.get("endprimitive");
1090 kw_endprogram
= &IdentTable
.get("endprogram");
1091 kw_endproperty
= &IdentTable
.get("endproperty");
1092 kw_endsequence
= &IdentTable
.get("endsequence");
1093 kw_endspecify
= &IdentTable
.get("endspecify");
1094 kw_endtable
= &IdentTable
.get("endtable");
1095 kw_endtask
= &IdentTable
.get("endtask");
1096 kw_forever
= &IdentTable
.get("forever");
1097 kw_fork
= &IdentTable
.get("fork");
1098 kw_generate
= &IdentTable
.get("generate");
1099 kw_highz0
= &IdentTable
.get("highz0");
1100 kw_highz1
= &IdentTable
.get("highz1");
1101 kw_iff
= &IdentTable
.get("iff");
1102 kw_ifnone
= &IdentTable
.get("ifnone");
1103 kw_ignore_bins
= &IdentTable
.get("ignore_bins");
1104 kw_illegal_bins
= &IdentTable
.get("illegal_bins");
1105 kw_initial
= &IdentTable
.get("initial");
1106 kw_inout
= &IdentTable
.get("inout");
1107 kw_input
= &IdentTable
.get("input");
1108 kw_inside
= &IdentTable
.get("inside");
1109 kw_interconnect
= &IdentTable
.get("interconnect");
1110 kw_intersect
= &IdentTable
.get("intersect");
1111 kw_join
= &IdentTable
.get("join");
1112 kw_join_any
= &IdentTable
.get("join_any");
1113 kw_join_none
= &IdentTable
.get("join_none");
1114 kw_large
= &IdentTable
.get("large");
1115 kw_local
= &IdentTable
.get("local");
1116 kw_localparam
= &IdentTable
.get("localparam");
1117 kw_macromodule
= &IdentTable
.get("macromodule");
1118 kw_matches
= &IdentTable
.get("matches");
1119 kw_medium
= &IdentTable
.get("medium");
1120 kw_negedge
= &IdentTable
.get("negedge");
1121 kw_nounconnected_drive
= &IdentTable
.get("nounconnected_drive");
1122 kw_output
= &IdentTable
.get("output");
1123 kw_packed
= &IdentTable
.get("packed");
1124 kw_parameter
= &IdentTable
.get("parameter");
1125 kw_posedge
= &IdentTable
.get("posedge");
1126 kw_primitive
= &IdentTable
.get("primitive");
1127 kw_priority
= &IdentTable
.get("priority");
1128 kw_program
= &IdentTable
.get("program");
1129 kw_property
= &IdentTable
.get("property");
1130 kw_pull0
= &IdentTable
.get("pull0");
1131 kw_pull1
= &IdentTable
.get("pull1");
1132 kw_pure
= &IdentTable
.get("pure");
1133 kw_rand
= &IdentTable
.get("rand");
1134 kw_randc
= &IdentTable
.get("randc");
1135 kw_randcase
= &IdentTable
.get("randcase");
1136 kw_randsequence
= &IdentTable
.get("randsequence");
1137 kw_repeat
= &IdentTable
.get("repeat");
1138 kw_resetall
= &IdentTable
.get("resetall");
1139 kw_sample
= &IdentTable
.get("sample");
1140 kw_scalared
= &IdentTable
.get("scalared");
1141 kw_sequence
= &IdentTable
.get("sequence");
1142 kw_small
= &IdentTable
.get("small");
1143 kw_soft
= &IdentTable
.get("soft");
1144 kw_solve
= &IdentTable
.get("solve");
1145 kw_specify
= &IdentTable
.get("specify");
1146 kw_specparam
= &IdentTable
.get("specparam");
1147 kw_strong0
= &IdentTable
.get("strong0");
1148 kw_strong1
= &IdentTable
.get("strong1");
1149 kw_supply0
= &IdentTable
.get("supply0");
1150 kw_supply1
= &IdentTable
.get("supply1");
1151 kw_table
= &IdentTable
.get("table");
1152 kw_tagged
= &IdentTable
.get("tagged");
1153 kw_task
= &IdentTable
.get("task");
1154 kw_timescale
= &IdentTable
.get("timescale");
1155 kw_tri
= &IdentTable
.get("tri");
1156 kw_tri0
= &IdentTable
.get("tri0");
1157 kw_tri1
= &IdentTable
.get("tri1");
1158 kw_triand
= &IdentTable
.get("triand");
1159 kw_trior
= &IdentTable
.get("trior");
1160 kw_trireg
= &IdentTable
.get("trireg");
1161 kw_unconnected_drive
= &IdentTable
.get("unconnected_drive");
1162 kw_undefineall
= &IdentTable
.get("undefineall");
1163 kw_unique
= &IdentTable
.get("unique");
1164 kw_unique0
= &IdentTable
.get("unique0");
1165 kw_uwire
= &IdentTable
.get("uwire");
1166 kw_vectored
= &IdentTable
.get("vectored");
1167 kw_wand
= &IdentTable
.get("wand");
1168 kw_weak0
= &IdentTable
.get("weak0");
1169 kw_weak1
= &IdentTable
.get("weak1");
1170 kw_wildcard
= &IdentTable
.get("wildcard");
1171 kw_wire
= &IdentTable
.get("wire");
1172 kw_with
= &IdentTable
.get("with");
1173 kw_wor
= &IdentTable
.get("wor");
1175 // Symbols that are treated as keywords.
1176 kw_verilogHash
= &IdentTable
.get("#");
1177 kw_verilogHashHash
= &IdentTable
.get("##");
1178 kw_apostrophe
= &IdentTable
.get("\'");
1180 // Keep this at the end of the constructor to make sure everything here
1182 // already initialized.
1183 JsExtraKeywords
= std::unordered_set
<IdentifierInfo
*>(
1184 {kw_as
, kw_async
, kw_await
, kw_declare
, kw_finally
, kw_from
,
1185 kw_function
, kw_get
, kw_import
, kw_is
, kw_let
, kw_module
, kw_override
,
1186 kw_readonly
, kw_set
, kw_type
, kw_typeof
, kw_var
, kw_yield
,
1187 // Keywords from the Java section.
1188 kw_abstract
, kw_extends
, kw_implements
, kw_instanceof
, kw_interface
});
1190 CSharpExtraKeywords
= std::unordered_set
<IdentifierInfo
*>(
1191 {kw_base
, kw_byte
, kw_checked
, kw_decimal
, kw_delegate
, kw_event
,
1192 kw_fixed
, kw_foreach
, kw_implicit
, kw_in
, kw_init
, kw_interface
,
1193 kw_internal
, kw_is
, kw_lock
, kw_null
, kw_object
, kw_out
, kw_override
,
1194 kw_params
, kw_readonly
, kw_ref
, kw_string
, kw_stackalloc
, kw_sbyte
,
1195 kw_sealed
, kw_uint
, kw_ulong
, kw_unchecked
, kw_unsafe
, kw_ushort
,
1197 // Keywords from the JavaScript section.
1198 kw_as
, kw_async
, kw_await
, kw_declare
, kw_finally
, kw_from
,
1199 kw_function
, kw_get
, kw_import
, kw_is
, kw_let
, kw_module
, kw_readonly
,
1200 kw_set
, kw_type
, kw_typeof
, kw_var
, kw_yield
,
1201 // Keywords from the Java section.
1202 kw_abstract
, kw_extends
, kw_implements
, kw_instanceof
, kw_interface
});
1204 // Some keywords are not included here because they don't need special
1205 // treatment like `showcancelled` or they should be treated as identifiers
1206 // like `int` and `logic`.
1207 VerilogExtraKeywords
= std::unordered_set
<IdentifierInfo
*>(
1208 {kw_always
, kw_always_comb
,
1209 kw_always_ff
, kw_always_latch
,
1210 kw_assert
, kw_assign
,
1211 kw_assume
, kw_automatic
,
1212 kw_before
, kw_begin
,
1215 kw_celldefine
, kw_checker
,
1216 kw_clocking
, kw_constraint
,
1217 kw_cover
, kw_covergroup
,
1218 kw_coverpoint
, kw_disable
,
1221 kw_endchecker
, kw_endclass
,
1222 kw_endclocking
, kw_endfunction
,
1223 kw_endgenerate
, kw_endgroup
,
1224 kw_endinterface
, kw_endmodule
,
1225 kw_endpackage
, kw_endprimitive
,
1226 kw_endprogram
, kw_endproperty
,
1227 kw_endsequence
, kw_endspecify
,
1228 kw_endtable
, kw_endtask
,
1229 kw_extends
, kw_final
,
1230 kw_foreach
, kw_forever
,
1231 kw_fork
, kw_function
,
1232 kw_generate
, kw_highz0
,
1234 kw_ifnone
, kw_ignore_bins
,
1235 kw_illegal_bins
, kw_implements
,
1236 kw_import
, kw_initial
,
1238 kw_inside
, kw_interconnect
,
1239 kw_interface
, kw_intersect
,
1240 kw_join
, kw_join_any
,
1241 kw_join_none
, kw_large
,
1243 kw_localparam
, kw_macromodule
,
1244 kw_matches
, kw_medium
,
1245 kw_negedge
, kw_output
,
1246 kw_package
, kw_packed
,
1247 kw_parameter
, kw_posedge
,
1248 kw_primitive
, kw_priority
,
1249 kw_program
, kw_property
,
1252 kw_randc
, kw_randcase
,
1253 kw_randsequence
, kw_ref
,
1254 kw_repeat
, kw_sample
,
1255 kw_scalared
, kw_sequence
,
1257 kw_solve
, kw_specify
,
1258 kw_specparam
, kw_strong0
,
1259 kw_strong1
, kw_supply0
,
1260 kw_supply1
, kw_table
,
1264 kw_trior
, kw_trireg
,
1265 kw_unique
, kw_unique0
,
1267 kw_vectored
, kw_wand
,
1269 kw_wildcard
, kw_wire
,
1271 kw_verilogHash
, kw_verilogHashHash
});
1274 // Context sensitive keywords.
1275 IdentifierInfo
*kw_final
;
1276 IdentifierInfo
*kw_override
;
1277 IdentifierInfo
*kw_in
;
1278 IdentifierInfo
*kw_of
;
1279 IdentifierInfo
*kw_CF_CLOSED_ENUM
;
1280 IdentifierInfo
*kw_CF_ENUM
;
1281 IdentifierInfo
*kw_CF_OPTIONS
;
1282 IdentifierInfo
*kw_NS_CLOSED_ENUM
;
1283 IdentifierInfo
*kw_NS_ENUM
;
1284 IdentifierInfo
*kw_NS_ERROR_ENUM
;
1285 IdentifierInfo
*kw_NS_OPTIONS
;
1286 IdentifierInfo
*kw___except
;
1287 IdentifierInfo
*kw___has_include
;
1288 IdentifierInfo
*kw___has_include_next
;
1290 // JavaScript keywords.
1291 IdentifierInfo
*kw_as
;
1292 IdentifierInfo
*kw_async
;
1293 IdentifierInfo
*kw_await
;
1294 IdentifierInfo
*kw_declare
;
1295 IdentifierInfo
*kw_finally
;
1296 IdentifierInfo
*kw_from
;
1297 IdentifierInfo
*kw_function
;
1298 IdentifierInfo
*kw_get
;
1299 IdentifierInfo
*kw_import
;
1300 IdentifierInfo
*kw_infer
;
1301 IdentifierInfo
*kw_is
;
1302 IdentifierInfo
*kw_let
;
1303 IdentifierInfo
*kw_module
;
1304 IdentifierInfo
*kw_readonly
;
1305 IdentifierInfo
*kw_set
;
1306 IdentifierInfo
*kw_type
;
1307 IdentifierInfo
*kw_typeof
;
1308 IdentifierInfo
*kw_var
;
1309 IdentifierInfo
*kw_yield
;
1312 IdentifierInfo
*kw_abstract
;
1313 IdentifierInfo
*kw_assert
;
1314 IdentifierInfo
*kw_extends
;
1315 IdentifierInfo
*kw_implements
;
1316 IdentifierInfo
*kw_instanceof
;
1317 IdentifierInfo
*kw_interface
;
1318 IdentifierInfo
*kw_native
;
1319 IdentifierInfo
*kw_package
;
1320 IdentifierInfo
*kw_synchronized
;
1321 IdentifierInfo
*kw_throws
;
1324 IdentifierInfo
*kw_mark
;
1325 IdentifierInfo
*kw_region
;
1328 IdentifierInfo
*kw_extend
;
1329 IdentifierInfo
*kw_option
;
1330 IdentifierInfo
*kw_optional
;
1331 IdentifierInfo
*kw_repeated
;
1332 IdentifierInfo
*kw_required
;
1333 IdentifierInfo
*kw_returns
;
1336 IdentifierInfo
*kw_signals
;
1337 IdentifierInfo
*kw_qsignals
;
1338 IdentifierInfo
*kw_slots
;
1339 IdentifierInfo
*kw_qslots
;
1341 // For internal use by clang-format.
1342 IdentifierInfo
*kw_internal_ident_after_define
;
1345 IdentifierInfo
*kw_dollar
;
1346 IdentifierInfo
*kw_base
;
1347 IdentifierInfo
*kw_byte
;
1348 IdentifierInfo
*kw_checked
;
1349 IdentifierInfo
*kw_decimal
;
1350 IdentifierInfo
*kw_delegate
;
1351 IdentifierInfo
*kw_event
;
1352 IdentifierInfo
*kw_fixed
;
1353 IdentifierInfo
*kw_foreach
;
1354 IdentifierInfo
*kw_implicit
;
1355 IdentifierInfo
*kw_init
;
1356 IdentifierInfo
*kw_internal
;
1358 IdentifierInfo
*kw_lock
;
1359 IdentifierInfo
*kw_null
;
1360 IdentifierInfo
*kw_object
;
1361 IdentifierInfo
*kw_out
;
1363 IdentifierInfo
*kw_params
;
1365 IdentifierInfo
*kw_ref
;
1366 IdentifierInfo
*kw_string
;
1367 IdentifierInfo
*kw_stackalloc
;
1368 IdentifierInfo
*kw_sbyte
;
1369 IdentifierInfo
*kw_sealed
;
1370 IdentifierInfo
*kw_uint
;
1371 IdentifierInfo
*kw_ulong
;
1372 IdentifierInfo
*kw_unchecked
;
1373 IdentifierInfo
*kw_unsafe
;
1374 IdentifierInfo
*kw_ushort
;
1375 IdentifierInfo
*kw_when
;
1376 IdentifierInfo
*kw_where
;
1379 IdentifierInfo
*kw_always
;
1380 IdentifierInfo
*kw_always_comb
;
1381 IdentifierInfo
*kw_always_ff
;
1382 IdentifierInfo
*kw_always_latch
;
1383 IdentifierInfo
*kw_assign
;
1384 IdentifierInfo
*kw_assume
;
1385 IdentifierInfo
*kw_automatic
;
1386 IdentifierInfo
*kw_before
;
1387 IdentifierInfo
*kw_begin
;
1388 IdentifierInfo
*kw_begin_keywords
;
1389 IdentifierInfo
*kw_bins
;
1390 IdentifierInfo
*kw_binsof
;
1391 IdentifierInfo
*kw_casex
;
1392 IdentifierInfo
*kw_casez
;
1393 IdentifierInfo
*kw_celldefine
;
1394 IdentifierInfo
*kw_checker
;
1395 IdentifierInfo
*kw_clocking
;
1396 IdentifierInfo
*kw_constraint
;
1397 IdentifierInfo
*kw_cover
;
1398 IdentifierInfo
*kw_covergroup
;
1399 IdentifierInfo
*kw_coverpoint
;
1400 IdentifierInfo
*kw_default_decay_time
;
1401 IdentifierInfo
*kw_default_nettype
;
1402 IdentifierInfo
*kw_default_trireg_strength
;
1403 IdentifierInfo
*kw_delay_mode_distributed
;
1404 IdentifierInfo
*kw_delay_mode_path
;
1405 IdentifierInfo
*kw_delay_mode_unit
;
1406 IdentifierInfo
*kw_delay_mode_zero
;
1407 IdentifierInfo
*kw_disable
;
1408 IdentifierInfo
*kw_dist
;
1409 IdentifierInfo
*kw_elsif
;
1410 IdentifierInfo
*kw_edge
;
1411 IdentifierInfo
*kw_end
;
1412 IdentifierInfo
*kw_end_keywords
;
1413 IdentifierInfo
*kw_endcase
;
1414 IdentifierInfo
*kw_endcelldefine
;
1415 IdentifierInfo
*kw_endchecker
;
1416 IdentifierInfo
*kw_endclass
;
1417 IdentifierInfo
*kw_endclocking
;
1418 IdentifierInfo
*kw_endfunction
;
1419 IdentifierInfo
*kw_endgenerate
;
1420 IdentifierInfo
*kw_endgroup
;
1421 IdentifierInfo
*kw_endinterface
;
1422 IdentifierInfo
*kw_endmodule
;
1423 IdentifierInfo
*kw_endpackage
;
1424 IdentifierInfo
*kw_endprimitive
;
1425 IdentifierInfo
*kw_endprogram
;
1426 IdentifierInfo
*kw_endproperty
;
1427 IdentifierInfo
*kw_endsequence
;
1428 IdentifierInfo
*kw_endspecify
;
1429 IdentifierInfo
*kw_endtable
;
1430 IdentifierInfo
*kw_endtask
;
1431 IdentifierInfo
*kw_forever
;
1432 IdentifierInfo
*kw_fork
;
1433 IdentifierInfo
*kw_generate
;
1434 IdentifierInfo
*kw_highz0
;
1435 IdentifierInfo
*kw_highz1
;
1436 IdentifierInfo
*kw_iff
;
1437 IdentifierInfo
*kw_ifnone
;
1438 IdentifierInfo
*kw_ignore_bins
;
1439 IdentifierInfo
*kw_illegal_bins
;
1440 IdentifierInfo
*kw_initial
;
1441 IdentifierInfo
*kw_inout
;
1442 IdentifierInfo
*kw_input
;
1443 IdentifierInfo
*kw_inside
;
1444 IdentifierInfo
*kw_interconnect
;
1445 IdentifierInfo
*kw_intersect
;
1446 IdentifierInfo
*kw_join
;
1447 IdentifierInfo
*kw_join_any
;
1448 IdentifierInfo
*kw_join_none
;
1449 IdentifierInfo
*kw_large
;
1450 IdentifierInfo
*kw_local
;
1451 IdentifierInfo
*kw_localparam
;
1452 IdentifierInfo
*kw_macromodule
;
1453 IdentifierInfo
*kw_matches
;
1454 IdentifierInfo
*kw_medium
;
1455 IdentifierInfo
*kw_negedge
;
1456 IdentifierInfo
*kw_nounconnected_drive
;
1457 IdentifierInfo
*kw_output
;
1458 IdentifierInfo
*kw_packed
;
1459 IdentifierInfo
*kw_parameter
;
1460 IdentifierInfo
*kw_posedge
;
1461 IdentifierInfo
*kw_primitive
;
1462 IdentifierInfo
*kw_priority
;
1463 IdentifierInfo
*kw_program
;
1464 IdentifierInfo
*kw_property
;
1465 IdentifierInfo
*kw_pull0
;
1466 IdentifierInfo
*kw_pull1
;
1467 IdentifierInfo
*kw_pure
;
1468 IdentifierInfo
*kw_rand
;
1469 IdentifierInfo
*kw_randc
;
1470 IdentifierInfo
*kw_randcase
;
1471 IdentifierInfo
*kw_randsequence
;
1472 IdentifierInfo
*kw_repeat
;
1473 IdentifierInfo
*kw_resetall
;
1474 IdentifierInfo
*kw_sample
;
1475 IdentifierInfo
*kw_scalared
;
1476 IdentifierInfo
*kw_sequence
;
1477 IdentifierInfo
*kw_small
;
1478 IdentifierInfo
*kw_soft
;
1479 IdentifierInfo
*kw_solve
;
1480 IdentifierInfo
*kw_specify
;
1481 IdentifierInfo
*kw_specparam
;
1482 IdentifierInfo
*kw_strong0
;
1483 IdentifierInfo
*kw_strong1
;
1484 IdentifierInfo
*kw_supply0
;
1485 IdentifierInfo
*kw_supply1
;
1486 IdentifierInfo
*kw_table
;
1487 IdentifierInfo
*kw_tagged
;
1488 IdentifierInfo
*kw_task
;
1489 IdentifierInfo
*kw_timescale
;
1490 IdentifierInfo
*kw_tri0
;
1491 IdentifierInfo
*kw_tri1
;
1492 IdentifierInfo
*kw_tri
;
1493 IdentifierInfo
*kw_triand
;
1494 IdentifierInfo
*kw_trior
;
1495 IdentifierInfo
*kw_trireg
;
1496 IdentifierInfo
*kw_unconnected_drive
;
1497 IdentifierInfo
*kw_undefineall
;
1498 IdentifierInfo
*kw_unique
;
1499 IdentifierInfo
*kw_unique0
;
1500 IdentifierInfo
*kw_uwire
;
1501 IdentifierInfo
*kw_vectored
;
1502 IdentifierInfo
*kw_wand
;
1503 IdentifierInfo
*kw_weak0
;
1504 IdentifierInfo
*kw_weak1
;
1505 IdentifierInfo
*kw_wildcard
;
1506 IdentifierInfo
*kw_wire
;
1507 IdentifierInfo
*kw_with
;
1508 IdentifierInfo
*kw_wor
;
1510 // Workaround for hashes and backticks in Verilog.
1511 IdentifierInfo
*kw_verilogHash
;
1512 IdentifierInfo
*kw_verilogHashHash
;
1514 // Symbols in Verilog that don't exist in C++.
1515 IdentifierInfo
*kw_apostrophe
;
1517 /// Returns \c true if \p Tok is a keyword or an identifier.
1518 bool isWordLike(const FormatToken
&Tok
) const {
1519 // getIdentifierinfo returns non-null for keywords as well as identifiers.
1520 return Tok
.Tok
.getIdentifierInfo() &&
1521 !Tok
.isOneOf(kw_verilogHash
, kw_verilogHashHash
, kw_apostrophe
);
1524 /// Returns \c true if \p Tok is a true JavaScript identifier, returns
1525 /// \c false if it is a keyword or a pseudo keyword.
1526 /// If \c AcceptIdentifierName is true, returns true not only for keywords,
1527 // but also for IdentifierName tokens (aka pseudo-keywords), such as
1529 bool IsJavaScriptIdentifier(const FormatToken
&Tok
,
1530 bool AcceptIdentifierName
= true) const {
1531 // Based on the list of JavaScript & TypeScript keywords here:
1532 // https://github.com/microsoft/TypeScript/blob/main/src/compiler/scanner.ts#L74
1533 switch (Tok
.Tok
.getKind()) {
1538 case tok::kw_continue
:
1540 case tok::kw_default
:
1541 case tok::kw_delete
:
1545 case tok::kw_export
:
1549 case tok::kw_import
:
1550 case tok::kw_module
:
1552 case tok::kw_private
:
1553 case tok::kw_protected
:
1554 case tok::kw_public
:
1555 case tok::kw_return
:
1556 case tok::kw_static
:
1557 case tok::kw_switch
:
1562 case tok::kw_typeof
:
1565 // These are JS keywords that are lexed by LLVM/clang as keywords.
1567 case tok::identifier
: {
1568 // For identifiers, make sure they are true identifiers, excluding the
1569 // JavaScript pseudo-keywords (not lexed by LLVM/clang as keywords).
1570 bool IsPseudoKeyword
=
1571 JsExtraKeywords
.find(Tok
.Tok
.getIdentifierInfo()) !=
1572 JsExtraKeywords
.end();
1573 return AcceptIdentifierName
|| !IsPseudoKeyword
;
1576 // Other keywords are handled in the switch below, to avoid problems due
1577 // to duplicate case labels when using the #include trick.
1581 switch (Tok
.Tok
.getKind()) {
1582 // Handle C++ keywords not included above: these are all JS identifiers.
1583 #define KEYWORD(X, Y) case tok::kw_##X:
1584 #include "clang/Basic/TokenKinds.def"
1585 // #undef KEYWORD is not needed -- it's #undef-ed at the end of
1589 // All other tokens (punctuation etc) are not JS identifiers.
1594 /// Returns \c true if \p Tok is a C# keyword, returns
1595 /// \c false if it is a anything else.
1596 bool isCSharpKeyword(const FormatToken
&Tok
) const {
1597 switch (Tok
.Tok
.getKind()) {
1605 case tok::kw_continue
:
1606 case tok::kw_default
:
1608 case tok::kw_double
:
1611 case tok::kw_explicit
:
1612 case tok::kw_extern
:
1620 case tok::kw_namespace
:
1622 case tok::kw_operator
:
1623 case tok::kw_private
:
1624 case tok::kw_protected
:
1625 case tok::kw_public
:
1626 case tok::kw_return
:
1628 case tok::kw_sizeof
:
1629 case tok::kw_static
:
1630 case tok::kw_struct
:
1631 case tok::kw_switch
:
1636 case tok::kw_typeof
:
1638 case tok::kw_virtual
:
1640 case tok::kw_volatile
:
1644 return Tok
.is(tok::identifier
) &&
1645 CSharpExtraKeywords
.find(Tok
.Tok
.getIdentifierInfo()) ==
1646 CSharpExtraKeywords
.end();
1650 bool isVerilogWordOperator(const FormatToken
&Tok
) const {
1651 return Tok
.isOneOf(kw_before
, kw_intersect
, kw_dist
, kw_iff
, kw_inside
,
1655 bool isVerilogIdentifier(const FormatToken
&Tok
) const {
1656 switch (Tok
.Tok
.getKind()) {
1660 case tok::kw_continue
:
1661 case tok::kw_default
:
1663 case tok::kw_extern
:
1668 case tok::kw_restrict
:
1669 case tok::kw_signed
:
1670 case tok::kw_static
:
1671 case tok::kw_struct
:
1672 case tok::kw_typedef
:
1674 case tok::kw_unsigned
:
1675 case tok::kw_virtual
:
1678 case tok::identifier
:
1679 return isWordLike(Tok
) &&
1680 VerilogExtraKeywords
.find(Tok
.Tok
.getIdentifierInfo()) ==
1681 VerilogExtraKeywords
.end();
1683 // getIdentifierInfo returns non-null for both identifiers and keywords.
1684 return Tok
.Tok
.getIdentifierInfo();
1688 /// Returns whether \p Tok is a Verilog preprocessor directive. This is
1689 /// needed because macro expansions start with a backtick as well and they
1690 /// need to be treated differently.
1691 bool isVerilogPPDirective(const FormatToken
&Tok
) const {
1692 auto Info
= Tok
.Tok
.getIdentifierInfo();
1695 switch (Info
->getPPKeywordID()) {
1696 case tok::pp_define
:
1700 case tok::pp_ifndef
:
1701 case tok::pp_include
:
1703 case tok::pp_pragma
:
1707 return Tok
.isOneOf(kw_begin_keywords
, kw_celldefine
,
1708 kw_default_decay_time
, kw_default_nettype
,
1709 kw_default_trireg_strength
, kw_delay_mode_distributed
,
1710 kw_delay_mode_path
, kw_delay_mode_unit
,
1711 kw_delay_mode_zero
, kw_elsif
, kw_end_keywords
,
1712 kw_endcelldefine
, kw_nounconnected_drive
, kw_resetall
,
1713 kw_timescale
, kw_unconnected_drive
, kw_undefineall
);
1717 /// Returns whether \p Tok is a Verilog keyword that opens a block.
1718 bool isVerilogBegin(const FormatToken
&Tok
) const {
1719 // `table` is not included since it needs to be treated specially.
1720 return !Tok
.endsSequence(kw_fork
, kw_disable
) &&
1721 Tok
.isOneOf(kw_begin
, kw_fork
, kw_generate
, kw_specify
);
1724 /// Returns whether \p Tok is a Verilog keyword that closes a block.
1725 bool isVerilogEnd(const FormatToken
&Tok
) const {
1726 return !Tok
.endsSequence(kw_join
, kw_rand
) &&
1727 Tok
.isOneOf(TT_MacroBlockEnd
, kw_end
, kw_endcase
, kw_endclass
,
1728 kw_endclocking
, kw_endchecker
, kw_endfunction
,
1729 kw_endgenerate
, kw_endgroup
, kw_endinterface
,
1730 kw_endmodule
, kw_endpackage
, kw_endprimitive
,
1731 kw_endprogram
, kw_endproperty
, kw_endsequence
,
1732 kw_endspecify
, kw_endtable
, kw_endtask
, kw_join
,
1733 kw_join_any
, kw_join_none
);
1736 /// Returns whether \p Tok is a Verilog keyword that opens a module, etc.
1737 bool isVerilogHierarchy(const FormatToken
&Tok
) const {
1738 if (Tok
.endsSequence(kw_function
, kw_with
))
1740 if (Tok
.is(kw_property
)) {
1741 const FormatToken
*Prev
= Tok
.getPreviousNonComment();
1743 Prev
->isOneOf(tok::kw_restrict
, kw_assert
, kw_assume
, kw_cover
));
1745 return Tok
.isOneOf(tok::kw_case
, tok::kw_class
, kw_function
, kw_module
,
1746 kw_interface
, kw_package
, kw_casex
, kw_casez
, kw_checker
,
1747 kw_clocking
, kw_covergroup
, kw_macromodule
, kw_primitive
,
1748 kw_program
, kw_property
, kw_randcase
, kw_randsequence
,
1752 bool isVerilogEndOfLabel(const FormatToken
&Tok
) const {
1753 const FormatToken
*Next
= Tok
.getNextNonComment();
1754 // In Verilog the colon in a default label is optional.
1755 return Tok
.is(TT_CaseLabelColon
) ||
1756 (Tok
.is(tok::kw_default
) &&
1757 !(Next
&& Next
->isOneOf(tok::colon
, tok::semi
, kw_clocking
, kw_iff
,
1758 kw_input
, kw_output
, kw_sequence
)));
1761 /// Returns whether \p Tok is a Verilog keyword that starts a
1762 /// structured procedure like 'always'.
1763 bool isVerilogStructuredProcedure(const FormatToken
&Tok
) const {
1764 return Tok
.isOneOf(kw_always
, kw_always_comb
, kw_always_ff
, kw_always_latch
,
1765 kw_final
, kw_forever
, kw_initial
);
1768 bool isVerilogQualifier(const FormatToken
&Tok
) const {
1769 switch (Tok
.Tok
.getKind()) {
1770 case tok::kw_extern
:
1771 case tok::kw_signed
:
1772 case tok::kw_static
:
1773 case tok::kw_unsigned
:
1774 case tok::kw_virtual
:
1776 case tok::identifier
:
1778 kw_let
, kw_var
, kw_ref
, kw_automatic
, kw_bins
, kw_coverpoint
,
1779 kw_ignore_bins
, kw_illegal_bins
, kw_inout
, kw_input
, kw_interconnect
,
1780 kw_local
, kw_localparam
, kw_output
, kw_parameter
, kw_pure
, kw_rand
,
1781 kw_randc
, kw_scalared
, kw_specparam
, kw_tri
, kw_tri0
, kw_tri1
,
1782 kw_triand
, kw_trior
, kw_trireg
, kw_uwire
, kw_vectored
, kw_wand
,
1783 kw_wildcard
, kw_wire
, kw_wor
);
1790 /// The JavaScript keywords beyond the C++ keyword set.
1791 std::unordered_set
<IdentifierInfo
*> JsExtraKeywords
;
1793 /// The C# keywords beyond the C++ keyword set
1794 std::unordered_set
<IdentifierInfo
*> CSharpExtraKeywords
;
1796 /// The Verilog keywords beyond the C++ keyword set.
1797 std::unordered_set
<IdentifierInfo
*> VerilogExtraKeywords
;
1800 inline bool isLineComment(const FormatToken
&FormatTok
) {
1801 return FormatTok
.is(tok::comment
) && !FormatTok
.TokenText
.startswith("/*");
1804 // Checks if \p FormatTok is a line comment that continues the line comment
1805 // \p Previous. The original column of \p MinColumnToken is used to determine
1806 // whether \p FormatTok is indented enough to the right to continue \p Previous.
1807 inline bool continuesLineComment(const FormatToken
&FormatTok
,
1808 const FormatToken
*Previous
,
1809 const FormatToken
*MinColumnToken
) {
1810 if (!Previous
|| !MinColumnToken
)
1812 unsigned MinContinueColumn
=
1813 MinColumnToken
->OriginalColumn
+ (isLineComment(*MinColumnToken
) ? 0 : 1);
1814 return isLineComment(FormatTok
) && FormatTok
.NewlinesBefore
== 1 &&
1815 isLineComment(*Previous
) &&
1816 FormatTok
.OriginalColumn
>= MinContinueColumn
;
1819 } // namespace format
1820 } // namespace clang