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) \
42 TYPE(CompoundRequirementLBrace) \
43 /* ternary ?: expression */ \
44 TYPE(ConditionalExpr) \
45 /* the condition in an if statement */ \
46 TYPE(ConditionLParen) \
47 TYPE(ConflictAlternative) \
50 /* l_brace of if/for/while */ \
51 TYPE(ControlStatementLBrace) \
53 TYPE(CSharpGenericTypeConstraint) \
54 TYPE(CSharpGenericTypeConstraintColon) \
55 TYPE(CSharpGenericTypeConstraintComma) \
56 TYPE(CSharpNamedArgumentColon) \
57 TYPE(CSharpNullable) \
58 TYPE(CSharpNullConditionalLSquare) \
59 TYPE(CSharpStringLiteral) \
60 TYPE(CtorInitializerColon) \
61 TYPE(CtorInitializerComma) \
62 TYPE(DesignatedInitializerLSquare) \
63 TYPE(DesignatedInitializerPeriod) \
69 TYPE(FunctionAnnotationRParen) \
70 TYPE(FunctionDeclarationName) \
71 TYPE(FunctionLBrace) \
72 TYPE(FunctionLikeOrFreestandingMacro) \
73 TYPE(FunctionTypeLParen) \
74 /* The colons as part of a C11 _Generic selection */ \
75 TYPE(GenericSelectionColon) \
76 /* The colon at the end of a goto label or a case label. Currently only used \
78 TYPE(GotoLabelColon) \
80 TYPE(ImplicitStringLiteral) \
81 TYPE(InheritanceColon) \
82 TYPE(InheritanceComma) \
83 TYPE(InlineASMBrace) \
84 TYPE(InlineASMColon) \
85 TYPE(InlineASMSymbolicNameLSquare) \
86 TYPE(JavaAnnotation) \
88 TYPE(JsComputedPropertyName) \
89 TYPE(JsExponentiation) \
90 TYPE(JsExponentiationEqual) \
91 TYPE(JsPipePipeEqual) \
92 TYPE(JsPrivateIdentifier) \
94 TYPE(JsTypeOperator) \
95 TYPE(JsTypeOptionalQuestion) \
99 TYPE(LeadingJavaAnnotation) \
101 TYPE(MacroBlockBegin) \
102 TYPE(MacroBlockEnd) \
103 TYPE(ModulePartitionColon) \
104 TYPE(NamespaceMacro) \
105 TYPE(NonNullAssertion) \
106 TYPE(NullCoalescingEqual) \
107 TYPE(NullCoalescingOperator) \
108 TYPE(NullPropagatingOperator) \
109 TYPE(ObjCBlockLBrace) \
110 TYPE(ObjCBlockLParen) \
113 TYPE(ObjCMethodExpr) \
114 TYPE(ObjCMethodSpecifier) \
116 TYPE(ObjCStringLiteral) \
117 TYPE(OverloadedOperator) \
118 TYPE(OverloadedOperatorLParen) \
119 TYPE(PointerOrReference) \
120 TYPE(ProtoExtensionLSquare) \
121 TYPE(PureVirtualSpecifier) \
122 TYPE(RangeBasedForLoopColon) \
125 TYPE(RequiresClause) \
126 TYPE(RequiresClauseInARequiresExpression) \
127 TYPE(RequiresExpression) \
128 TYPE(RequiresExpressionLBrace) \
129 TYPE(RequiresExpressionLParen) \
132 TYPE(StatementAttributeLikeMacro) \
133 TYPE(StatementMacro) \
135 TYPE(StructuredBindingLSquare) \
136 TYPE(TemplateCloser) \
137 TYPE(TemplateOpener) \
138 TYPE(TemplateString) \
139 TYPE(TrailingAnnotation) \
140 TYPE(TrailingReturnArrow) \
141 TYPE(TrailingUnaryOperator) \
142 TYPE(TypeDeclarationParen) \
143 TYPE(TypenameMacro) \
144 TYPE(UnaryOperator) \
146 TYPE(UntouchableMacroFunc) \
147 /* like in begin : block */ \
148 TYPE(VerilogBlockLabelColon) \
149 /* The square bracket for the dimension part of the type name. \
150 * In 'logic [1:0] x[1:0]', only the first '['. This way we can have space \
151 * before the first bracket but not the second. */ \
152 TYPE(VerilogDimensionedTypeName) \
153 /* for the base in a number literal, not including the quote */ \
154 TYPE(VerilogNumberBase) \
155 /* Things inside the table in user-defined primitives. */ \
156 TYPE(VerilogTableItem) \
159 /// Determines the semantic type of a syntactic token, e.g. whether "<" is a
160 /// template opener or binary operator.
161 enum TokenType
: uint8_t {
162 #define TYPE(X) TT_##X,
168 /// Determines the name of a token type.
169 const char *getTokenTypeName(TokenType Type
);
171 // Represents what type of block a set of braces open.
172 enum BraceBlockKind
{ BK_Unknown
, BK_Block
, BK_BracedInit
};
174 // The packing kind of a function's parameters.
175 enum ParameterPackingKind
{ PPK_BinPacked
, PPK_OnePerLine
, PPK_Inconclusive
};
177 enum FormatDecision
{ FD_Unformatted
, FD_Continue
, FD_Break
};
179 /// Roles a token can take in a configured macro expansion.
181 /// The token was expanded from a macro argument when formatting the expanded
184 /// The token is part of a macro argument that was previously formatted as
185 /// expansion when formatting the unexpanded macro call.
187 /// The token was expanded from a macro definition, and is not visible as part
188 /// of the macro call.
194 /// Contains information on the token's role in a macro expansion.
196 /// Given the following definitions:
201 /// Consider the macro call:
202 /// A({B(C(C(x)))}) -> [{<x>}]
204 /// In this case, the tokens of the unexpanded macro call will have the
205 /// following relevant entries in their macro context (note that formatting
206 /// the unexpanded macro call happens *after* formatting the expanded macro
208 /// A( { B( C( C(x) ) ) } )
209 /// Role: NN U NN NN NNUN N N U N (N=None, U=UnexpandedArg)
212 /// Role: H E H E H E H (H=Hidden, E=ExpandedArg)
213 /// ExpandedFrom[0]: A A A A A A A
214 /// ExpandedFrom[1]: B B B
215 /// ExpandedFrom[2]: C
216 /// ExpandedFrom[3]: C
217 /// StartOfExpansion: 1 0 1 2 0 0 0
218 /// EndOfExpansion: 0 0 0 2 1 0 1
219 struct MacroExpansion
{
220 MacroExpansion(MacroRole Role
) : Role(Role
) {}
222 /// The token's role in the macro expansion.
223 /// When formatting an expanded macro, all tokens that are part of macro
224 /// arguments will be MR_ExpandedArg, while all tokens that are not visible in
225 /// the macro call will be MR_Hidden.
226 /// When formatting an unexpanded macro call, all tokens that are part of
227 /// macro arguments will be MR_UnexpandedArg.
230 /// The stack of macro call identifier tokens this token was expanded from.
231 llvm::SmallVector
<FormatToken
*, 1> ExpandedFrom
;
233 /// The number of expansions of which this macro is the first entry.
234 unsigned StartOfExpansion
= 0;
236 /// The number of currently open expansions in \c ExpandedFrom this macro is
237 /// the last token in.
238 unsigned EndOfExpansion
= 0;
244 /// A wrapper around a \c Token storing information about the
245 /// whitespace characters preceding it.
248 : HasUnescapedNewline(false), IsMultiline(false), IsFirst(false),
249 MustBreakBefore(false), IsUnterminatedLiteral(false),
250 CanBreakBefore(false), ClosesTemplateDeclaration(false),
251 StartsBinaryExpression(false), EndsBinaryExpression(false),
252 PartOfMultiVariableDeclStmt(false), ContinuesLineCommentSection(false),
253 Finalized(false), ClosesRequiresClause(false),
254 EndsCppAttributeGroup(false), BlockKind(BK_Unknown
),
255 Decision(FD_Unformatted
), PackingKind(PPK_Inconclusive
),
256 TypeIsFinalized(false), Type(TT_Unknown
) {}
261 /// The raw text of the token.
263 /// Contains the raw token text without leading whitespace and without leading
264 /// escaped newlines.
267 /// A token can have a special role that can carry extra information
268 /// about the token's formatting.
269 /// FIXME: Make FormatToken for parsing and AnnotatedToken two different
270 /// classes and make this a unique_ptr in the AnnotatedToken class.
271 std::shared_ptr
<TokenRole
> Role
;
273 /// The range of the whitespace immediately preceding the \c Token.
274 SourceRange WhitespaceRange
;
276 /// Whether there is at least one unescaped newline before the \c
278 unsigned HasUnescapedNewline
: 1;
280 /// Whether the token text contains newlines (escaped or not).
281 unsigned IsMultiline
: 1;
283 /// Indicates that this is the first token of the file.
284 unsigned IsFirst
: 1;
286 /// Whether there must be a line break before this token.
288 /// This happens for example when a preprocessor directive ended directly
289 /// before the token.
290 unsigned MustBreakBefore
: 1;
292 /// Set to \c true if this token is an unterminated literal.
293 unsigned IsUnterminatedLiteral
: 1;
295 /// \c true if it is allowed to break before this token.
296 unsigned CanBreakBefore
: 1;
298 /// \c true if this is the ">" of "template<..>".
299 unsigned ClosesTemplateDeclaration
: 1;
301 /// \c true if this token starts a binary expression, i.e. has at least
302 /// one fake l_paren with a precedence greater than prec::Unknown.
303 unsigned StartsBinaryExpression
: 1;
304 /// \c true if this token ends a binary expression.
305 unsigned EndsBinaryExpression
: 1;
307 /// Is this token part of a \c DeclStmt defining multiple variables?
309 /// Only set if \c Type == \c TT_StartOfName.
310 unsigned PartOfMultiVariableDeclStmt
: 1;
312 /// Does this line comment continue a line comment section?
314 /// Only set to true if \c Type == \c TT_LineComment.
315 unsigned ContinuesLineCommentSection
: 1;
317 /// If \c true, this token has been fully formatted (indented and
318 /// potentially re-formatted inside), and we do not allow further formatting
320 unsigned Finalized
: 1;
322 /// \c true if this is the last token within requires clause.
323 unsigned ClosesRequiresClause
: 1;
325 /// \c true if this token ends a group of C++ attributes.
326 unsigned EndsCppAttributeGroup
: 1;
329 /// Contains the kind of block if this token is a brace.
330 unsigned BlockKind
: 2;
333 BraceBlockKind
getBlockKind() const {
334 return static_cast<BraceBlockKind
>(BlockKind
);
336 void setBlockKind(BraceBlockKind BBK
) {
338 assert(getBlockKind() == BBK
&& "BraceBlockKind overflow!");
342 /// Stores the formatting decision for the token once it was made.
343 unsigned Decision
: 2;
346 FormatDecision
getDecision() const {
347 return static_cast<FormatDecision
>(Decision
);
349 void setDecision(FormatDecision D
) {
351 assert(getDecision() == D
&& "FormatDecision overflow!");
355 /// If this is an opening parenthesis, how are the parameters packed?
356 unsigned PackingKind
: 2;
359 ParameterPackingKind
getPackingKind() const {
360 return static_cast<ParameterPackingKind
>(PackingKind
);
362 void setPackingKind(ParameterPackingKind K
) {
364 assert(getPackingKind() == K
&& "ParameterPackingKind overflow!");
368 unsigned TypeIsFinalized
: 1;
372 /// Returns the token's type, e.g. whether "<" is a template opener or
374 TokenType
getType() const { return Type
; }
375 void setType(TokenType T
) {
376 assert((!TypeIsFinalized
|| T
== Type
) &&
377 "Please use overwriteFixedType to change a fixed type.");
380 /// Sets the type and also the finalized flag. This prevents the type to be
381 /// reset in TokenAnnotator::resetTokenMetadata(). If the type needs to be set
382 /// to another one please use overwriteFixedType, or even better remove the
383 /// need to reassign the type.
384 void setFinalizedType(TokenType T
) {
386 TypeIsFinalized
= true;
388 void overwriteFixedType(TokenType T
) {
389 TypeIsFinalized
= false;
392 bool isTypeFinalized() const { return TypeIsFinalized
; }
394 /// Used to set an operator precedence explicitly.
395 prec::Level ForcedPrecedence
= prec::Unknown
;
397 /// The number of newlines immediately before the \c Token.
399 /// This can be used to determine what the user wrote in the original code
400 /// and thereby e.g. leave an empty line between two function definitions.
401 unsigned NewlinesBefore
= 0;
403 /// The offset just past the last '\n' in this token's leading
404 /// whitespace (relative to \c WhiteSpaceStart). 0 if there is no '\n'.
405 unsigned LastNewlineOffset
= 0;
407 /// The width of the non-whitespace parts of the token (or its first
408 /// line for multi-line tokens) in columns.
409 /// We need this to correctly measure number of columns a token spans.
410 unsigned ColumnWidth
= 0;
412 /// Contains the width in columns of the last line of a multi-line
414 unsigned LastLineColumnWidth
= 0;
416 /// The number of spaces that should be inserted before this token.
417 unsigned SpacesRequiredBefore
= 0;
419 /// Number of parameters, if this is "(", "[" or "<".
420 unsigned ParameterCount
= 0;
422 /// Number of parameters that are nested blocks,
423 /// if this is "(", "[" or "<".
424 unsigned BlockParameterCount
= 0;
426 /// If this is a bracket ("<", "(", "[" or "{"), contains the kind of
427 /// the surrounding bracket.
428 tok::TokenKind ParentBracket
= tok::unknown
;
430 /// The total length of the unwrapped line up to and including this
432 unsigned TotalLength
= 0;
434 /// The original 0-based column of this token, including expanded tabs.
435 /// The configured TabWidth is used as tab width.
436 unsigned OriginalColumn
= 0;
438 /// The length of following tokens until the next natural split point,
439 /// or the next token that can be broken.
440 unsigned UnbreakableTailLength
= 0;
442 // FIXME: Come up with a 'cleaner' concept.
443 /// The binding strength of a token. This is a combined value of
444 /// operator precedence, parenthesis nesting, etc.
445 unsigned BindingStrength
= 0;
447 /// The nesting level of this token, i.e. the number of surrounding (),
449 unsigned NestingLevel
= 0;
451 /// The indent level of this token. Copied from the surrounding line.
452 unsigned IndentLevel
= 0;
454 /// Penalty for inserting a line break before this token.
455 unsigned SplitPenalty
= 0;
457 /// If this is the first ObjC selector name in an ObjC method
458 /// definition or call, this contains the length of the longest name.
460 /// This being set to 0 means that the selectors should not be colon-aligned,
461 /// e.g. because several of them are block-type.
462 unsigned LongestObjCSelectorName
= 0;
464 /// If this is the first ObjC selector name in an ObjC method
465 /// definition or call, this contains the number of parts that the whole
466 /// selector consist of.
467 unsigned ObjCSelectorNameParts
= 0;
469 /// The 0-based index of the parameter/argument. For ObjC it is set
470 /// for the selector name token.
471 /// For now calculated only for ObjC.
472 unsigned ParameterIndex
= 0;
474 /// Stores the number of required fake parentheses and the
475 /// corresponding operator precedence.
477 /// If multiple fake parentheses start at a token, this vector stores them in
478 /// reverse order, i.e. inner fake parenthesis first.
479 SmallVector
<prec::Level
, 4> FakeLParens
;
480 /// Insert this many fake ) after this token for correct indentation.
481 unsigned FakeRParens
= 0;
483 /// If this is an operator (or "."/"->") in a sequence of operators
484 /// with the same precedence, contains the 0-based operator index.
485 unsigned OperatorIndex
= 0;
487 /// If this is an operator (or "."/"->") in a sequence of operators
488 /// with the same precedence, points to the next operator.
489 FormatToken
*NextOperator
= nullptr;
491 /// If this is a bracket, this points to the matching one.
492 FormatToken
*MatchingParen
= nullptr;
494 /// The previous token in the unwrapped line.
495 FormatToken
*Previous
= nullptr;
497 /// The next token in the unwrapped line.
498 FormatToken
*Next
= nullptr;
500 /// The first token in set of column elements.
501 bool StartsColumn
= false;
503 /// This notes the start of the line of an array initializer.
504 bool ArrayInitializerLineStart
= false;
506 /// This starts an array initializer.
507 bool IsArrayInitializer
= false;
509 /// Is optional and can be removed.
510 bool Optional
= false;
512 /// Number of optional braces to be inserted after this token:
513 /// -1: a single left brace
515 /// >0: number of right braces
516 int8_t BraceCount
= 0;
518 /// If this token starts a block, this contains all the unwrapped lines
520 SmallVector
<AnnotatedLine
*, 1> Children
;
522 // Contains all attributes related to how this token takes part
523 // in a configured macro expansion.
524 std::optional
<MacroExpansion
> MacroCtx
;
526 /// When macro expansion introduces nodes with children, those are marked as
528 /// FIXME: The formatting code currently hard-codes the assumption that
529 /// child nodes are introduced by blocks following an opening brace.
530 /// This is deeply baked into the code and disentangling this will require
531 /// signficant refactorings. \c MacroParent allows us to special-case the
532 /// cases in which we treat parents as block-openers for now.
533 bool MacroParent
= false;
535 bool is(tok::TokenKind Kind
) const { return Tok
.is(Kind
); }
536 bool is(TokenType TT
) const { return getType() == TT
; }
537 bool is(const IdentifierInfo
*II
) const {
538 return II
&& II
== Tok
.getIdentifierInfo();
540 bool is(tok::PPKeywordKind Kind
) const {
541 return Tok
.getIdentifierInfo() &&
542 Tok
.getIdentifierInfo()->getPPKeywordID() == Kind
;
544 bool is(BraceBlockKind BBK
) const { return getBlockKind() == BBK
; }
545 bool is(ParameterPackingKind PPK
) const { return getPackingKind() == PPK
; }
547 template <typename A
, typename B
> bool isOneOf(A K1
, B K2
) const {
548 return is(K1
) || is(K2
);
550 template <typename A
, typename B
, typename
... Ts
>
551 bool isOneOf(A K1
, B K2
, Ts
... Ks
) const {
552 return is(K1
) || isOneOf(K2
, Ks
...);
554 template <typename T
> bool isNot(T Kind
) const { return !is(Kind
); }
556 bool isIf(bool AllowConstexprMacro
= true) const {
557 return is(tok::kw_if
) || endsSequence(tok::kw_constexpr
, tok::kw_if
) ||
558 (endsSequence(tok::identifier
, tok::kw_if
) && AllowConstexprMacro
);
561 bool closesScopeAfterBlock() const {
562 if (getBlockKind() == BK_Block
)
565 return Previous
->closesScopeAfterBlock();
569 /// \c true if this token starts a sequence with the given tokens in order,
570 /// following the ``Next`` pointers, ignoring comments.
571 template <typename A
, typename
... Ts
>
572 bool startsSequence(A K1
, Ts
... Tokens
) const {
573 return startsSequenceInternal(K1
, Tokens
...);
576 /// \c true if this token ends a sequence with the given tokens in order,
577 /// following the ``Previous`` pointers, ignoring comments.
578 /// For example, given tokens [T1, T2, T3], the function returns true if
579 /// 3 tokens ending at this (ignoring comments) are [T3, T2, T1]. In other
580 /// words, the tokens passed to this function need to the reverse of the
581 /// order the tokens appear in code.
582 template <typename A
, typename
... Ts
>
583 bool endsSequence(A K1
, Ts
... Tokens
) const {
584 return endsSequenceInternal(K1
, Tokens
...);
587 bool isStringLiteral() const { return tok::isStringLiteral(Tok
.getKind()); }
589 bool isObjCAtKeyword(tok::ObjCKeywordKind Kind
) const {
590 return Tok
.isObjCAtKeyword(Kind
);
593 bool isAccessSpecifier(bool ColonRequired
= true) const {
594 if (!isOneOf(tok::kw_public
, tok::kw_protected
, tok::kw_private
))
598 const auto NextNonComment
= getNextNonComment();
599 return NextNonComment
&& NextNonComment
->is(tok::colon
);
602 bool canBePointerOrReferenceQualifier() const {
603 return isOneOf(tok::kw_const
, tok::kw_restrict
, tok::kw_volatile
,
604 tok::kw___attribute
, tok::kw__Nonnull
, tok::kw__Nullable
,
605 tok::kw__Null_unspecified
, tok::kw___ptr32
, tok::kw___ptr64
,
609 /// Determine whether the token is a simple-type-specifier.
610 [[nodiscard
]] bool isSimpleTypeSpecifier() const;
612 [[nodiscard
]] bool isTypeOrIdentifier() const;
614 bool isObjCAccessSpecifier() const {
615 return is(tok::at
) && Next
&&
616 (Next
->isObjCAtKeyword(tok::objc_public
) ||
617 Next
->isObjCAtKeyword(tok::objc_protected
) ||
618 Next
->isObjCAtKeyword(tok::objc_package
) ||
619 Next
->isObjCAtKeyword(tok::objc_private
));
622 /// Returns whether \p Tok is ([{ or an opening < of a template or in
624 bool opensScope() const {
625 if (is(TT_TemplateString
) && TokenText
.endswith("${"))
627 if (is(TT_DictLiteral
) && is(tok::less
))
629 return isOneOf(tok::l_paren
, tok::l_brace
, tok::l_square
,
632 /// Returns whether \p Tok is )]} or a closing > of a template or in
634 bool closesScope() const {
635 if (is(TT_TemplateString
) && TokenText
.startswith("}"))
637 if (is(TT_DictLiteral
) && is(tok::greater
))
639 return isOneOf(tok::r_paren
, tok::r_brace
, tok::r_square
,
643 /// Returns \c true if this is a "." or "->" accessing a member.
644 bool isMemberAccess() const {
645 return isOneOf(tok::arrow
, tok::period
, tok::arrowstar
) &&
646 !isOneOf(TT_DesignatedInitializerPeriod
, TT_TrailingReturnArrow
,
647 TT_LambdaArrow
, TT_LeadingJavaAnnotation
);
650 bool isUnaryOperator() const {
651 switch (Tok
.getKind()) {
655 case tok::minusminus
:
659 case tok::kw_alignof
:
666 bool isBinaryOperator() const {
667 // Comma is a binary operator, but does not behave as such wrt. formatting.
668 return getPrecedence() > prec::Comma
;
671 bool isTrailingComment() const {
672 return is(tok::comment
) &&
673 (is(TT_LineComment
) || !Next
|| Next
->NewlinesBefore
> 0);
676 /// Returns \c true if this is a keyword that can be used
677 /// like a function call (e.g. sizeof, typeid, ...).
678 bool isFunctionLikeKeyword() const {
679 switch (Tok
.getKind()) {
684 case tok::kw_alignof
:
685 case tok::kw_alignas
:
686 case tok::kw_decltype
:
687 case tok::kw_noexcept
:
688 case tok::kw_static_assert
:
689 case tok::kw__Atomic
:
690 case tok::kw___attribute
:
691 #define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case tok::kw___##Trait:
692 #include "clang/Basic/TransformTypeTraits.def"
693 case tok::kw_requires
:
700 /// Returns \c true if this is a string literal that's like a label,
701 /// e.g. ends with "=" or ":".
702 bool isLabelString() const {
703 if (!is(tok::string_literal
))
705 StringRef Content
= TokenText
;
706 if (Content
.startswith("\"") || Content
.startswith("'"))
707 Content
= Content
.drop_front(1);
708 if (Content
.endswith("\"") || Content
.endswith("'"))
709 Content
= Content
.drop_back(1);
710 Content
= Content
.trim();
711 return Content
.size() > 1 &&
712 (Content
.back() == ':' || Content
.back() == '=');
715 /// Returns actual token start location without leading escaped
716 /// newlines and whitespace.
718 /// This can be different to Tok.getLocation(), which includes leading escaped
720 SourceLocation
getStartOfNonWhitespace() const {
721 return WhitespaceRange
.getEnd();
724 /// Returns \c true if the range of whitespace immediately preceding the \c
725 /// Token is not empty.
726 bool hasWhitespaceBefore() const {
727 return WhitespaceRange
.getBegin() != WhitespaceRange
.getEnd();
730 prec::Level
getPrecedence() const {
731 if (ForcedPrecedence
!= prec::Unknown
)
732 return ForcedPrecedence
;
733 return getBinOpPrecedence(Tok
.getKind(), /*GreaterThanIsOperator=*/true,
734 /*CPlusPlus11=*/true);
737 /// Returns the previous token ignoring comments.
738 [[nodiscard
]] FormatToken
*getPreviousNonComment() const {
739 FormatToken
*Tok
= Previous
;
740 while (Tok
&& Tok
->is(tok::comment
))
745 /// Returns the next token ignoring comments.
746 [[nodiscard
]] const FormatToken
*getNextNonComment() const {
747 const FormatToken
*Tok
= Next
;
748 while (Tok
&& Tok
->is(tok::comment
))
753 /// Returns \c true if this tokens starts a block-type list, i.e. a
754 /// list that should be indented with a block indent.
755 [[nodiscard
]] bool opensBlockOrBlockTypeList(const FormatStyle
&Style
) const;
757 /// Returns whether the token is the left square bracket of a C++
758 /// structured binding declaration.
759 bool isCppStructuredBinding(const FormatStyle
&Style
) const {
760 if (!Style
.isCpp() || isNot(tok::l_square
))
762 const FormatToken
*T
= this;
764 T
= T
->getPreviousNonComment();
765 } while (T
&& T
->isOneOf(tok::kw_const
, tok::kw_volatile
, tok::amp
,
767 return T
&& T
->is(tok::kw_auto
);
770 /// Same as opensBlockOrBlockTypeList, but for the closing token.
771 bool closesBlockOrBlockTypeList(const FormatStyle
&Style
) const {
772 if (is(TT_TemplateString
) && closesScope())
774 return MatchingParen
&& MatchingParen
->opensBlockOrBlockTypeList(Style
);
777 /// Return the actual namespace token, if this token starts a namespace
779 const FormatToken
*getNamespaceToken() const {
780 const FormatToken
*NamespaceTok
= this;
781 if (is(tok::comment
))
782 NamespaceTok
= NamespaceTok
->getNextNonComment();
783 // Detect "(inline|export)? namespace" in the beginning of a line.
784 if (NamespaceTok
&& NamespaceTok
->isOneOf(tok::kw_inline
, tok::kw_export
))
785 NamespaceTok
= NamespaceTok
->getNextNonComment();
786 return NamespaceTok
&&
787 NamespaceTok
->isOneOf(tok::kw_namespace
, TT_NamespaceMacro
)
792 void copyFrom(const FormatToken
&Tok
) { *this = Tok
; }
795 // Only allow copying via the explicit copyFrom method.
796 FormatToken(const FormatToken
&) = delete;
797 FormatToken
&operator=(const FormatToken
&) = default;
799 template <typename A
, typename
... Ts
>
800 bool startsSequenceInternal(A K1
, Ts
... Tokens
) const {
801 if (is(tok::comment
) && Next
)
802 return Next
->startsSequenceInternal(K1
, Tokens
...);
803 return is(K1
) && Next
&& Next
->startsSequenceInternal(Tokens
...);
806 template <typename A
> bool startsSequenceInternal(A K1
) const {
807 if (is(tok::comment
) && Next
)
808 return Next
->startsSequenceInternal(K1
);
812 template <typename A
, typename
... Ts
> bool endsSequenceInternal(A K1
) const {
813 if (is(tok::comment
) && Previous
)
814 return Previous
->endsSequenceInternal(K1
);
818 template <typename A
, typename
... Ts
>
819 bool endsSequenceInternal(A K1
, Ts
... Tokens
) const {
820 if (is(tok::comment
) && Previous
)
821 return Previous
->endsSequenceInternal(K1
, Tokens
...);
822 return is(K1
) && Previous
&& Previous
->endsSequenceInternal(Tokens
...);
826 class ContinuationIndenter
;
831 TokenRole(const FormatStyle
&Style
) : Style(Style
) {}
832 virtual ~TokenRole();
834 /// After the \c TokenAnnotator has finished annotating all the tokens,
835 /// this function precomputes required information for formatting.
836 virtual void precomputeFormattingInfos(const FormatToken
*Token
);
838 /// Apply the special formatting that the given role demands.
840 /// Assumes that the token having this role is already formatted.
842 /// Continues formatting from \p State leaving indentation to \p Indenter and
843 /// returns the total penalty that this formatting incurs.
844 virtual unsigned formatFromToken(LineState
&State
,
845 ContinuationIndenter
*Indenter
,
850 /// Same as \c formatFromToken, but assumes that the first token has
851 /// already been set thereby deciding on the first line break.
852 virtual unsigned formatAfterToken(LineState
&State
,
853 ContinuationIndenter
*Indenter
,
858 /// Notifies the \c Role that a comma was found.
859 virtual void CommaFound(const FormatToken
*Token
) {}
861 virtual const FormatToken
*lastComma() { return nullptr; }
864 const FormatStyle
&Style
;
867 class CommaSeparatedList
: public TokenRole
{
869 CommaSeparatedList(const FormatStyle
&Style
)
870 : TokenRole(Style
), HasNestedBracedList(false) {}
872 void precomputeFormattingInfos(const FormatToken
*Token
) override
;
874 unsigned formatAfterToken(LineState
&State
, ContinuationIndenter
*Indenter
,
875 bool DryRun
) override
;
877 unsigned formatFromToken(LineState
&State
, ContinuationIndenter
*Indenter
,
878 bool DryRun
) override
;
880 /// Adds \p Token as the next comma to the \c CommaSeparated list.
881 void CommaFound(const FormatToken
*Token
) override
{
882 Commas
.push_back(Token
);
885 const FormatToken
*lastComma() override
{
888 return Commas
.back();
892 /// A struct that holds information on how to format a given list with
893 /// a specific number of columns.
894 struct ColumnFormat
{
895 /// The number of columns to use.
898 /// The total width in characters.
901 /// The number of lines required for this format.
904 /// The size of each column in characters.
905 SmallVector
<unsigned, 8> ColumnSizes
;
908 /// Calculate which \c ColumnFormat fits best into
909 /// \p RemainingCharacters.
910 const ColumnFormat
*getColumnFormat(unsigned RemainingCharacters
) const;
912 /// The ordered \c FormatTokens making up the commas of this list.
913 SmallVector
<const FormatToken
*, 8> Commas
;
915 /// The length of each of the list's items in characters including the
917 SmallVector
<unsigned, 8> ItemLengths
;
919 /// Precomputed formats that can be used for this list.
920 SmallVector
<ColumnFormat
, 4> Formats
;
922 bool HasNestedBracedList
;
925 /// Encapsulates keywords that are context sensitive or for languages not
926 /// properly supported by Clang's lexer.
927 struct AdditionalKeywords
{
928 AdditionalKeywords(IdentifierTable
&IdentTable
) {
929 kw_final
= &IdentTable
.get("final");
930 kw_override
= &IdentTable
.get("override");
931 kw_in
= &IdentTable
.get("in");
932 kw_of
= &IdentTable
.get("of");
933 kw_CF_CLOSED_ENUM
= &IdentTable
.get("CF_CLOSED_ENUM");
934 kw_CF_ENUM
= &IdentTable
.get("CF_ENUM");
935 kw_CF_OPTIONS
= &IdentTable
.get("CF_OPTIONS");
936 kw_NS_CLOSED_ENUM
= &IdentTable
.get("NS_CLOSED_ENUM");
937 kw_NS_ENUM
= &IdentTable
.get("NS_ENUM");
938 kw_NS_OPTIONS
= &IdentTable
.get("NS_OPTIONS");
940 kw_as
= &IdentTable
.get("as");
941 kw_async
= &IdentTable
.get("async");
942 kw_await
= &IdentTable
.get("await");
943 kw_declare
= &IdentTable
.get("declare");
944 kw_finally
= &IdentTable
.get("finally");
945 kw_from
= &IdentTable
.get("from");
946 kw_function
= &IdentTable
.get("function");
947 kw_get
= &IdentTable
.get("get");
948 kw_import
= &IdentTable
.get("import");
949 kw_infer
= &IdentTable
.get("infer");
950 kw_is
= &IdentTable
.get("is");
951 kw_let
= &IdentTable
.get("let");
952 kw_module
= &IdentTable
.get("module");
953 kw_readonly
= &IdentTable
.get("readonly");
954 kw_set
= &IdentTable
.get("set");
955 kw_type
= &IdentTable
.get("type");
956 kw_typeof
= &IdentTable
.get("typeof");
957 kw_var
= &IdentTable
.get("var");
958 kw_yield
= &IdentTable
.get("yield");
960 kw_abstract
= &IdentTable
.get("abstract");
961 kw_assert
= &IdentTable
.get("assert");
962 kw_extends
= &IdentTable
.get("extends");
963 kw_implements
= &IdentTable
.get("implements");
964 kw_instanceof
= &IdentTable
.get("instanceof");
965 kw_interface
= &IdentTable
.get("interface");
966 kw_native
= &IdentTable
.get("native");
967 kw_package
= &IdentTable
.get("package");
968 kw_synchronized
= &IdentTable
.get("synchronized");
969 kw_throws
= &IdentTable
.get("throws");
970 kw___except
= &IdentTable
.get("__except");
971 kw___has_include
= &IdentTable
.get("__has_include");
972 kw___has_include_next
= &IdentTable
.get("__has_include_next");
974 kw_mark
= &IdentTable
.get("mark");
975 kw_region
= &IdentTable
.get("region");
977 kw_extend
= &IdentTable
.get("extend");
978 kw_option
= &IdentTable
.get("option");
979 kw_optional
= &IdentTable
.get("optional");
980 kw_repeated
= &IdentTable
.get("repeated");
981 kw_required
= &IdentTable
.get("required");
982 kw_returns
= &IdentTable
.get("returns");
984 kw_signals
= &IdentTable
.get("signals");
985 kw_qsignals
= &IdentTable
.get("Q_SIGNALS");
986 kw_slots
= &IdentTable
.get("slots");
987 kw_qslots
= &IdentTable
.get("Q_SLOTS");
989 // For internal clang-format use.
990 kw_internal_ident_after_define
=
991 &IdentTable
.get("__CLANG_FORMAT_INTERNAL_IDENT_AFTER_DEFINE__");
994 kw_dollar
= &IdentTable
.get("dollar");
995 kw_base
= &IdentTable
.get("base");
996 kw_byte
= &IdentTable
.get("byte");
997 kw_checked
= &IdentTable
.get("checked");
998 kw_decimal
= &IdentTable
.get("decimal");
999 kw_delegate
= &IdentTable
.get("delegate");
1000 kw_event
= &IdentTable
.get("event");
1001 kw_fixed
= &IdentTable
.get("fixed");
1002 kw_foreach
= &IdentTable
.get("foreach");
1003 kw_init
= &IdentTable
.get("init");
1004 kw_implicit
= &IdentTable
.get("implicit");
1005 kw_internal
= &IdentTable
.get("internal");
1006 kw_lock
= &IdentTable
.get("lock");
1007 kw_null
= &IdentTable
.get("null");
1008 kw_object
= &IdentTable
.get("object");
1009 kw_out
= &IdentTable
.get("out");
1010 kw_params
= &IdentTable
.get("params");
1011 kw_ref
= &IdentTable
.get("ref");
1012 kw_string
= &IdentTable
.get("string");
1013 kw_stackalloc
= &IdentTable
.get("stackalloc");
1014 kw_sbyte
= &IdentTable
.get("sbyte");
1015 kw_sealed
= &IdentTable
.get("sealed");
1016 kw_uint
= &IdentTable
.get("uint");
1017 kw_ulong
= &IdentTable
.get("ulong");
1018 kw_unchecked
= &IdentTable
.get("unchecked");
1019 kw_unsafe
= &IdentTable
.get("unsafe");
1020 kw_ushort
= &IdentTable
.get("ushort");
1021 kw_when
= &IdentTable
.get("when");
1022 kw_where
= &IdentTable
.get("where");
1025 kw_always
= &IdentTable
.get("always");
1026 kw_always_comb
= &IdentTable
.get("always_comb");
1027 kw_always_ff
= &IdentTable
.get("always_ff");
1028 kw_always_latch
= &IdentTable
.get("always_latch");
1029 kw_assign
= &IdentTable
.get("assign");
1030 kw_assume
= &IdentTable
.get("assume");
1031 kw_automatic
= &IdentTable
.get("automatic");
1032 kw_before
= &IdentTable
.get("before");
1033 kw_begin
= &IdentTable
.get("begin");
1034 kw_begin_keywords
= &IdentTable
.get("begin_keywords");
1035 kw_bins
= &IdentTable
.get("bins");
1036 kw_binsof
= &IdentTable
.get("binsof");
1037 kw_casex
= &IdentTable
.get("casex");
1038 kw_casez
= &IdentTable
.get("casez");
1039 kw_celldefine
= &IdentTable
.get("celldefine");
1040 kw_checker
= &IdentTable
.get("checker");
1041 kw_clocking
= &IdentTable
.get("clocking");
1042 kw_constraint
= &IdentTable
.get("constraint");
1043 kw_cover
= &IdentTable
.get("cover");
1044 kw_covergroup
= &IdentTable
.get("covergroup");
1045 kw_coverpoint
= &IdentTable
.get("coverpoint");
1046 kw_default_decay_time
= &IdentTable
.get("default_decay_time");
1047 kw_default_nettype
= &IdentTable
.get("default_nettype");
1048 kw_default_trireg_strength
= &IdentTable
.get("default_trireg_strength");
1049 kw_delay_mode_distributed
= &IdentTable
.get("delay_mode_distributed");
1050 kw_delay_mode_path
= &IdentTable
.get("delay_mode_path");
1051 kw_delay_mode_unit
= &IdentTable
.get("delay_mode_unit");
1052 kw_delay_mode_zero
= &IdentTable
.get("delay_mode_zero");
1053 kw_disable
= &IdentTable
.get("disable");
1054 kw_dist
= &IdentTable
.get("dist");
1055 kw_elsif
= &IdentTable
.get("elsif");
1056 kw_end
= &IdentTable
.get("end");
1057 kw_end_keywords
= &IdentTable
.get("end_keywords");
1058 kw_endcase
= &IdentTable
.get("endcase");
1059 kw_endcelldefine
= &IdentTable
.get("endcelldefine");
1060 kw_endchecker
= &IdentTable
.get("endchecker");
1061 kw_endclass
= &IdentTable
.get("endclass");
1062 kw_endclocking
= &IdentTable
.get("endclocking");
1063 kw_endfunction
= &IdentTable
.get("endfunction");
1064 kw_endgenerate
= &IdentTable
.get("endgenerate");
1065 kw_endgroup
= &IdentTable
.get("endgroup");
1066 kw_endinterface
= &IdentTable
.get("endinterface");
1067 kw_endmodule
= &IdentTable
.get("endmodule");
1068 kw_endpackage
= &IdentTable
.get("endpackage");
1069 kw_endprimitive
= &IdentTable
.get("endprimitive");
1070 kw_endprogram
= &IdentTable
.get("endprogram");
1071 kw_endproperty
= &IdentTable
.get("endproperty");
1072 kw_endsequence
= &IdentTable
.get("endsequence");
1073 kw_endspecify
= &IdentTable
.get("endspecify");
1074 kw_endtable
= &IdentTable
.get("endtable");
1075 kw_endtask
= &IdentTable
.get("endtask");
1076 kw_forever
= &IdentTable
.get("forever");
1077 kw_fork
= &IdentTable
.get("fork");
1078 kw_generate
= &IdentTable
.get("generate");
1079 kw_highz0
= &IdentTable
.get("highz0");
1080 kw_highz1
= &IdentTable
.get("highz1");
1081 kw_iff
= &IdentTable
.get("iff");
1082 kw_ifnone
= &IdentTable
.get("ifnone");
1083 kw_ignore_bins
= &IdentTable
.get("ignore_bins");
1084 kw_illegal_bins
= &IdentTable
.get("illegal_bins");
1085 kw_initial
= &IdentTable
.get("initial");
1086 kw_inout
= &IdentTable
.get("inout");
1087 kw_input
= &IdentTable
.get("input");
1088 kw_inside
= &IdentTable
.get("inside");
1089 kw_interconnect
= &IdentTable
.get("interconnect");
1090 kw_intersect
= &IdentTable
.get("intersect");
1091 kw_join
= &IdentTable
.get("join");
1092 kw_join_any
= &IdentTable
.get("join_any");
1093 kw_join_none
= &IdentTable
.get("join_none");
1094 kw_large
= &IdentTable
.get("large");
1095 kw_local
= &IdentTable
.get("local");
1096 kw_localparam
= &IdentTable
.get("localparam");
1097 kw_macromodule
= &IdentTable
.get("macromodule");
1098 kw_matches
= &IdentTable
.get("matches");
1099 kw_medium
= &IdentTable
.get("medium");
1100 kw_nounconnected_drive
= &IdentTable
.get("nounconnected_drive");
1101 kw_output
= &IdentTable
.get("output");
1102 kw_packed
= &IdentTable
.get("packed");
1103 kw_parameter
= &IdentTable
.get("parameter");
1104 kw_primitive
= &IdentTable
.get("primitive");
1105 kw_priority
= &IdentTable
.get("priority");
1106 kw_program
= &IdentTable
.get("program");
1107 kw_property
= &IdentTable
.get("property");
1108 kw_pull0
= &IdentTable
.get("pull0");
1109 kw_pull1
= &IdentTable
.get("pull1");
1110 kw_pure
= &IdentTable
.get("pure");
1111 kw_rand
= &IdentTable
.get("rand");
1112 kw_randc
= &IdentTable
.get("randc");
1113 kw_randcase
= &IdentTable
.get("randcase");
1114 kw_randsequence
= &IdentTable
.get("randsequence");
1115 kw_repeat
= &IdentTable
.get("repeat");
1116 kw_resetall
= &IdentTable
.get("resetall");
1117 kw_sample
= &IdentTable
.get("sample");
1118 kw_scalared
= &IdentTable
.get("scalared");
1119 kw_sequence
= &IdentTable
.get("sequence");
1120 kw_small
= &IdentTable
.get("small");
1121 kw_soft
= &IdentTable
.get("soft");
1122 kw_solve
= &IdentTable
.get("solve");
1123 kw_specify
= &IdentTable
.get("specify");
1124 kw_specparam
= &IdentTable
.get("specparam");
1125 kw_strong0
= &IdentTable
.get("strong0");
1126 kw_strong1
= &IdentTable
.get("strong1");
1127 kw_supply0
= &IdentTable
.get("supply0");
1128 kw_supply1
= &IdentTable
.get("supply1");
1129 kw_table
= &IdentTable
.get("table");
1130 kw_tagged
= &IdentTable
.get("tagged");
1131 kw_task
= &IdentTable
.get("task");
1132 kw_timescale
= &IdentTable
.get("timescale");
1133 kw_tri
= &IdentTable
.get("tri");
1134 kw_tri0
= &IdentTable
.get("tri0");
1135 kw_tri1
= &IdentTable
.get("tri1");
1136 kw_triand
= &IdentTable
.get("triand");
1137 kw_trior
= &IdentTable
.get("trior");
1138 kw_trireg
= &IdentTable
.get("trireg");
1139 kw_unconnected_drive
= &IdentTable
.get("unconnected_drive");
1140 kw_undefineall
= &IdentTable
.get("undefineall");
1141 kw_unique
= &IdentTable
.get("unique");
1142 kw_unique0
= &IdentTable
.get("unique0");
1143 kw_uwire
= &IdentTable
.get("uwire");
1144 kw_vectored
= &IdentTable
.get("vectored");
1145 kw_wand
= &IdentTable
.get("wand");
1146 kw_weak0
= &IdentTable
.get("weak0");
1147 kw_weak1
= &IdentTable
.get("weak1");
1148 kw_wildcard
= &IdentTable
.get("wildcard");
1149 kw_wire
= &IdentTable
.get("wire");
1150 kw_with
= &IdentTable
.get("with");
1151 kw_wor
= &IdentTable
.get("wor");
1153 // Symbols that are treated as keywords.
1154 kw_verilogHash
= &IdentTable
.get("#");
1155 kw_verilogHashHash
= &IdentTable
.get("##");
1156 kw_apostrophe
= &IdentTable
.get("\'");
1158 // Keep this at the end of the constructor to make sure everything here
1160 // already initialized.
1161 JsExtraKeywords
= std::unordered_set
<IdentifierInfo
*>(
1162 {kw_as
, kw_async
, kw_await
, kw_declare
, kw_finally
, kw_from
,
1163 kw_function
, kw_get
, kw_import
, kw_is
, kw_let
, kw_module
, kw_override
,
1164 kw_readonly
, kw_set
, kw_type
, kw_typeof
, kw_var
, kw_yield
,
1165 // Keywords from the Java section.
1166 kw_abstract
, kw_extends
, kw_implements
, kw_instanceof
, kw_interface
});
1168 CSharpExtraKeywords
= std::unordered_set
<IdentifierInfo
*>(
1169 {kw_base
, kw_byte
, kw_checked
, kw_decimal
, kw_delegate
, kw_event
,
1170 kw_fixed
, kw_foreach
, kw_implicit
, kw_in
, kw_init
, kw_interface
,
1171 kw_internal
, kw_is
, kw_lock
, kw_null
, kw_object
, kw_out
, kw_override
,
1172 kw_params
, kw_readonly
, kw_ref
, kw_string
, kw_stackalloc
, kw_sbyte
,
1173 kw_sealed
, kw_uint
, kw_ulong
, kw_unchecked
, kw_unsafe
, kw_ushort
,
1175 // Keywords from the JavaScript section.
1176 kw_as
, kw_async
, kw_await
, kw_declare
, kw_finally
, kw_from
,
1177 kw_function
, kw_get
, kw_import
, kw_is
, kw_let
, kw_module
, kw_readonly
,
1178 kw_set
, kw_type
, kw_typeof
, kw_var
, kw_yield
,
1179 // Keywords from the Java section.
1180 kw_abstract
, kw_extends
, kw_implements
, kw_instanceof
, kw_interface
});
1182 // Some keywords are not included here because they don't need special
1183 // treatment like `showcancelled` or they should be treated as identifiers
1184 // like `int` and `logic`.
1185 VerilogExtraKeywords
=
1186 std::unordered_set
<IdentifierInfo
*>({kw_always
,
1310 kw_verilogHashHash
});
1313 // Context sensitive keywords.
1314 IdentifierInfo
*kw_final
;
1315 IdentifierInfo
*kw_override
;
1316 IdentifierInfo
*kw_in
;
1317 IdentifierInfo
*kw_of
;
1318 IdentifierInfo
*kw_CF_CLOSED_ENUM
;
1319 IdentifierInfo
*kw_CF_ENUM
;
1320 IdentifierInfo
*kw_CF_OPTIONS
;
1321 IdentifierInfo
*kw_NS_CLOSED_ENUM
;
1322 IdentifierInfo
*kw_NS_ENUM
;
1323 IdentifierInfo
*kw_NS_OPTIONS
;
1324 IdentifierInfo
*kw___except
;
1325 IdentifierInfo
*kw___has_include
;
1326 IdentifierInfo
*kw___has_include_next
;
1328 // JavaScript keywords.
1329 IdentifierInfo
*kw_as
;
1330 IdentifierInfo
*kw_async
;
1331 IdentifierInfo
*kw_await
;
1332 IdentifierInfo
*kw_declare
;
1333 IdentifierInfo
*kw_finally
;
1334 IdentifierInfo
*kw_from
;
1335 IdentifierInfo
*kw_function
;
1336 IdentifierInfo
*kw_get
;
1337 IdentifierInfo
*kw_import
;
1338 IdentifierInfo
*kw_infer
;
1339 IdentifierInfo
*kw_is
;
1340 IdentifierInfo
*kw_let
;
1341 IdentifierInfo
*kw_module
;
1342 IdentifierInfo
*kw_readonly
;
1343 IdentifierInfo
*kw_set
;
1344 IdentifierInfo
*kw_type
;
1345 IdentifierInfo
*kw_typeof
;
1346 IdentifierInfo
*kw_var
;
1347 IdentifierInfo
*kw_yield
;
1350 IdentifierInfo
*kw_abstract
;
1351 IdentifierInfo
*kw_assert
;
1352 IdentifierInfo
*kw_extends
;
1353 IdentifierInfo
*kw_implements
;
1354 IdentifierInfo
*kw_instanceof
;
1355 IdentifierInfo
*kw_interface
;
1356 IdentifierInfo
*kw_native
;
1357 IdentifierInfo
*kw_package
;
1358 IdentifierInfo
*kw_synchronized
;
1359 IdentifierInfo
*kw_throws
;
1362 IdentifierInfo
*kw_mark
;
1363 IdentifierInfo
*kw_region
;
1366 IdentifierInfo
*kw_extend
;
1367 IdentifierInfo
*kw_option
;
1368 IdentifierInfo
*kw_optional
;
1369 IdentifierInfo
*kw_repeated
;
1370 IdentifierInfo
*kw_required
;
1371 IdentifierInfo
*kw_returns
;
1374 IdentifierInfo
*kw_signals
;
1375 IdentifierInfo
*kw_qsignals
;
1376 IdentifierInfo
*kw_slots
;
1377 IdentifierInfo
*kw_qslots
;
1379 // For internal use by clang-format.
1380 IdentifierInfo
*kw_internal_ident_after_define
;
1383 IdentifierInfo
*kw_dollar
;
1384 IdentifierInfo
*kw_base
;
1385 IdentifierInfo
*kw_byte
;
1386 IdentifierInfo
*kw_checked
;
1387 IdentifierInfo
*kw_decimal
;
1388 IdentifierInfo
*kw_delegate
;
1389 IdentifierInfo
*kw_event
;
1390 IdentifierInfo
*kw_fixed
;
1391 IdentifierInfo
*kw_foreach
;
1392 IdentifierInfo
*kw_implicit
;
1393 IdentifierInfo
*kw_init
;
1394 IdentifierInfo
*kw_internal
;
1396 IdentifierInfo
*kw_lock
;
1397 IdentifierInfo
*kw_null
;
1398 IdentifierInfo
*kw_object
;
1399 IdentifierInfo
*kw_out
;
1401 IdentifierInfo
*kw_params
;
1403 IdentifierInfo
*kw_ref
;
1404 IdentifierInfo
*kw_string
;
1405 IdentifierInfo
*kw_stackalloc
;
1406 IdentifierInfo
*kw_sbyte
;
1407 IdentifierInfo
*kw_sealed
;
1408 IdentifierInfo
*kw_uint
;
1409 IdentifierInfo
*kw_ulong
;
1410 IdentifierInfo
*kw_unchecked
;
1411 IdentifierInfo
*kw_unsafe
;
1412 IdentifierInfo
*kw_ushort
;
1413 IdentifierInfo
*kw_when
;
1414 IdentifierInfo
*kw_where
;
1417 IdentifierInfo
*kw_always
;
1418 IdentifierInfo
*kw_always_comb
;
1419 IdentifierInfo
*kw_always_ff
;
1420 IdentifierInfo
*kw_always_latch
;
1421 IdentifierInfo
*kw_assign
;
1422 IdentifierInfo
*kw_assume
;
1423 IdentifierInfo
*kw_automatic
;
1424 IdentifierInfo
*kw_before
;
1425 IdentifierInfo
*kw_begin
;
1426 IdentifierInfo
*kw_begin_keywords
;
1427 IdentifierInfo
*kw_bins
;
1428 IdentifierInfo
*kw_binsof
;
1429 IdentifierInfo
*kw_casex
;
1430 IdentifierInfo
*kw_casez
;
1431 IdentifierInfo
*kw_celldefine
;
1432 IdentifierInfo
*kw_checker
;
1433 IdentifierInfo
*kw_clocking
;
1434 IdentifierInfo
*kw_constraint
;
1435 IdentifierInfo
*kw_cover
;
1436 IdentifierInfo
*kw_covergroup
;
1437 IdentifierInfo
*kw_coverpoint
;
1438 IdentifierInfo
*kw_default_decay_time
;
1439 IdentifierInfo
*kw_default_nettype
;
1440 IdentifierInfo
*kw_default_trireg_strength
;
1441 IdentifierInfo
*kw_delay_mode_distributed
;
1442 IdentifierInfo
*kw_delay_mode_path
;
1443 IdentifierInfo
*kw_delay_mode_unit
;
1444 IdentifierInfo
*kw_delay_mode_zero
;
1445 IdentifierInfo
*kw_disable
;
1446 IdentifierInfo
*kw_dist
;
1447 IdentifierInfo
*kw_elsif
;
1448 IdentifierInfo
*kw_end
;
1449 IdentifierInfo
*kw_end_keywords
;
1450 IdentifierInfo
*kw_endcase
;
1451 IdentifierInfo
*kw_endcelldefine
;
1452 IdentifierInfo
*kw_endchecker
;
1453 IdentifierInfo
*kw_endclass
;
1454 IdentifierInfo
*kw_endclocking
;
1455 IdentifierInfo
*kw_endfunction
;
1456 IdentifierInfo
*kw_endgenerate
;
1457 IdentifierInfo
*kw_endgroup
;
1458 IdentifierInfo
*kw_endinterface
;
1459 IdentifierInfo
*kw_endmodule
;
1460 IdentifierInfo
*kw_endpackage
;
1461 IdentifierInfo
*kw_endprimitive
;
1462 IdentifierInfo
*kw_endprogram
;
1463 IdentifierInfo
*kw_endproperty
;
1464 IdentifierInfo
*kw_endsequence
;
1465 IdentifierInfo
*kw_endspecify
;
1466 IdentifierInfo
*kw_endtable
;
1467 IdentifierInfo
*kw_endtask
;
1468 IdentifierInfo
*kw_forever
;
1469 IdentifierInfo
*kw_fork
;
1470 IdentifierInfo
*kw_generate
;
1471 IdentifierInfo
*kw_highz0
;
1472 IdentifierInfo
*kw_highz1
;
1473 IdentifierInfo
*kw_iff
;
1474 IdentifierInfo
*kw_ifnone
;
1475 IdentifierInfo
*kw_ignore_bins
;
1476 IdentifierInfo
*kw_illegal_bins
;
1477 IdentifierInfo
*kw_initial
;
1478 IdentifierInfo
*kw_inout
;
1479 IdentifierInfo
*kw_input
;
1480 IdentifierInfo
*kw_inside
;
1481 IdentifierInfo
*kw_interconnect
;
1482 IdentifierInfo
*kw_intersect
;
1483 IdentifierInfo
*kw_join
;
1484 IdentifierInfo
*kw_join_any
;
1485 IdentifierInfo
*kw_join_none
;
1486 IdentifierInfo
*kw_large
;
1487 IdentifierInfo
*kw_local
;
1488 IdentifierInfo
*kw_localparam
;
1489 IdentifierInfo
*kw_macromodule
;
1490 IdentifierInfo
*kw_matches
;
1491 IdentifierInfo
*kw_medium
;
1492 IdentifierInfo
*kw_nounconnected_drive
;
1493 IdentifierInfo
*kw_output
;
1494 IdentifierInfo
*kw_packed
;
1495 IdentifierInfo
*kw_parameter
;
1496 IdentifierInfo
*kw_primitive
;
1497 IdentifierInfo
*kw_priority
;
1498 IdentifierInfo
*kw_program
;
1499 IdentifierInfo
*kw_property
;
1500 IdentifierInfo
*kw_pull0
;
1501 IdentifierInfo
*kw_pull1
;
1502 IdentifierInfo
*kw_pure
;
1503 IdentifierInfo
*kw_rand
;
1504 IdentifierInfo
*kw_randc
;
1505 IdentifierInfo
*kw_randcase
;
1506 IdentifierInfo
*kw_randsequence
;
1507 IdentifierInfo
*kw_repeat
;
1508 IdentifierInfo
*kw_resetall
;
1509 IdentifierInfo
*kw_sample
;
1510 IdentifierInfo
*kw_scalared
;
1511 IdentifierInfo
*kw_sequence
;
1512 IdentifierInfo
*kw_small
;
1513 IdentifierInfo
*kw_soft
;
1514 IdentifierInfo
*kw_solve
;
1515 IdentifierInfo
*kw_specify
;
1516 IdentifierInfo
*kw_specparam
;
1517 IdentifierInfo
*kw_strong0
;
1518 IdentifierInfo
*kw_strong1
;
1519 IdentifierInfo
*kw_supply0
;
1520 IdentifierInfo
*kw_supply1
;
1521 IdentifierInfo
*kw_table
;
1522 IdentifierInfo
*kw_tagged
;
1523 IdentifierInfo
*kw_task
;
1524 IdentifierInfo
*kw_timescale
;
1525 IdentifierInfo
*kw_tri0
;
1526 IdentifierInfo
*kw_tri1
;
1527 IdentifierInfo
*kw_tri
;
1528 IdentifierInfo
*kw_triand
;
1529 IdentifierInfo
*kw_trior
;
1530 IdentifierInfo
*kw_trireg
;
1531 IdentifierInfo
*kw_unconnected_drive
;
1532 IdentifierInfo
*kw_undefineall
;
1533 IdentifierInfo
*kw_unique
;
1534 IdentifierInfo
*kw_unique0
;
1535 IdentifierInfo
*kw_uwire
;
1536 IdentifierInfo
*kw_vectored
;
1537 IdentifierInfo
*kw_wand
;
1538 IdentifierInfo
*kw_weak0
;
1539 IdentifierInfo
*kw_weak1
;
1540 IdentifierInfo
*kw_wildcard
;
1541 IdentifierInfo
*kw_wire
;
1542 IdentifierInfo
*kw_with
;
1543 IdentifierInfo
*kw_wor
;
1545 // Workaround for hashes and backticks in Verilog.
1546 IdentifierInfo
*kw_verilogHash
;
1547 IdentifierInfo
*kw_verilogHashHash
;
1549 // Symbols in Verilog that don't exist in C++.
1550 IdentifierInfo
*kw_apostrophe
;
1552 /// Returns \c true if \p Tok is a keyword or an identifier.
1553 bool isWordLike(const FormatToken
&Tok
) const {
1554 // getIdentifierinfo returns non-null for keywords as well as identifiers.
1555 return Tok
.Tok
.getIdentifierInfo() != nullptr &&
1556 !Tok
.isOneOf(kw_verilogHash
, kw_verilogHashHash
, kw_apostrophe
);
1559 /// Returns \c true if \p Tok is a true JavaScript identifier, returns
1560 /// \c false if it is a keyword or a pseudo keyword.
1561 /// If \c AcceptIdentifierName is true, returns true not only for keywords,
1562 // but also for IdentifierName tokens (aka pseudo-keywords), such as
1564 bool IsJavaScriptIdentifier(const FormatToken
&Tok
,
1565 bool AcceptIdentifierName
= true) const {
1566 // Based on the list of JavaScript & TypeScript keywords here:
1567 // https://github.com/microsoft/TypeScript/blob/main/src/compiler/scanner.ts#L74
1568 switch (Tok
.Tok
.getKind()) {
1573 case tok::kw_continue
:
1575 case tok::kw_default
:
1576 case tok::kw_delete
:
1580 case tok::kw_export
:
1584 case tok::kw_import
:
1585 case tok::kw_module
:
1587 case tok::kw_private
:
1588 case tok::kw_protected
:
1589 case tok::kw_public
:
1590 case tok::kw_return
:
1591 case tok::kw_static
:
1592 case tok::kw_switch
:
1597 case tok::kw_typeof
:
1600 // These are JS keywords that are lexed by LLVM/clang as keywords.
1602 case tok::identifier
: {
1603 // For identifiers, make sure they are true identifiers, excluding the
1604 // JavaScript pseudo-keywords (not lexed by LLVM/clang as keywords).
1605 bool IsPseudoKeyword
=
1606 JsExtraKeywords
.find(Tok
.Tok
.getIdentifierInfo()) !=
1607 JsExtraKeywords
.end();
1608 return AcceptIdentifierName
|| !IsPseudoKeyword
;
1611 // Other keywords are handled in the switch below, to avoid problems due
1612 // to duplicate case labels when using the #include trick.
1616 switch (Tok
.Tok
.getKind()) {
1617 // Handle C++ keywords not included above: these are all JS identifiers.
1618 #define KEYWORD(X, Y) case tok::kw_##X:
1619 #include "clang/Basic/TokenKinds.def"
1620 // #undef KEYWORD is not needed -- it's #undef-ed at the end of
1624 // All other tokens (punctuation etc) are not JS identifiers.
1629 /// Returns \c true if \p Tok is a C# keyword, returns
1630 /// \c false if it is a anything else.
1631 bool isCSharpKeyword(const FormatToken
&Tok
) const {
1632 switch (Tok
.Tok
.getKind()) {
1640 case tok::kw_continue
:
1641 case tok::kw_default
:
1643 case tok::kw_double
:
1646 case tok::kw_explicit
:
1647 case tok::kw_extern
:
1655 case tok::kw_namespace
:
1657 case tok::kw_operator
:
1658 case tok::kw_private
:
1659 case tok::kw_protected
:
1660 case tok::kw_public
:
1661 case tok::kw_return
:
1663 case tok::kw_sizeof
:
1664 case tok::kw_static
:
1665 case tok::kw_struct
:
1666 case tok::kw_switch
:
1671 case tok::kw_typeof
:
1673 case tok::kw_virtual
:
1675 case tok::kw_volatile
:
1679 return Tok
.is(tok::identifier
) &&
1680 CSharpExtraKeywords
.find(Tok
.Tok
.getIdentifierInfo()) ==
1681 CSharpExtraKeywords
.end();
1685 bool isVerilogWordOperator(const FormatToken
&Tok
) const {
1686 return Tok
.isOneOf(kw_before
, kw_intersect
, kw_dist
, kw_iff
, kw_inside
,
1690 bool isVerilogIdentifier(const FormatToken
&Tok
) const {
1691 switch (Tok
.Tok
.getKind()) {
1695 case tok::kw_continue
:
1696 case tok::kw_default
:
1698 case tok::kw_extern
:
1703 case tok::kw_restrict
:
1704 case tok::kw_signed
:
1705 case tok::kw_static
:
1706 case tok::kw_struct
:
1707 case tok::kw_typedef
:
1709 case tok::kw_unsigned
:
1710 case tok::kw_virtual
:
1713 case tok::identifier
:
1714 return VerilogExtraKeywords
.find(Tok
.Tok
.getIdentifierInfo()) ==
1715 VerilogExtraKeywords
.end();
1717 // getIdentifierInfo returns non-null for both identifiers and keywords.
1718 return Tok
.Tok
.getIdentifierInfo() != nullptr;
1722 /// Returns whether \p Tok is a Verilog preprocessor directive. This is
1723 /// needed because macro expansions start with a backtick as well and they
1724 /// need to be treated differently.
1725 bool isVerilogPPDirective(const FormatToken
&Tok
) const {
1726 auto Info
= Tok
.Tok
.getIdentifierInfo();
1729 switch (Info
->getPPKeywordID()) {
1730 case tok::pp_define
:
1734 case tok::pp_ifndef
:
1735 case tok::pp_include
:
1737 case tok::pp_pragma
:
1741 return Tok
.isOneOf(kw_begin_keywords
, kw_celldefine
,
1742 kw_default_decay_time
, kw_default_nettype
,
1743 kw_default_trireg_strength
, kw_delay_mode_distributed
,
1744 kw_delay_mode_path
, kw_delay_mode_unit
,
1745 kw_delay_mode_zero
, kw_elsif
, kw_end_keywords
,
1746 kw_endcelldefine
, kw_nounconnected_drive
, kw_resetall
,
1747 kw_timescale
, kw_unconnected_drive
, kw_undefineall
);
1751 /// Returns whether \p Tok is a Verilog keyword that opens a block.
1752 bool isVerilogBegin(const FormatToken
&Tok
) const {
1753 // `table` is not included since it needs to be treated specially.
1754 return !Tok
.endsSequence(kw_fork
, kw_disable
) &&
1755 Tok
.isOneOf(kw_begin
, kw_fork
, kw_generate
, kw_specify
);
1758 /// Returns whether \p Tok is a Verilog keyword that closes a block.
1759 bool isVerilogEnd(const FormatToken
&Tok
) const {
1760 return !Tok
.endsSequence(kw_join
, kw_rand
) &&
1761 Tok
.isOneOf(TT_MacroBlockEnd
, kw_end
, kw_endcase
, kw_endclass
,
1762 kw_endclocking
, kw_endchecker
, kw_endfunction
,
1763 kw_endgenerate
, kw_endgroup
, kw_endinterface
,
1764 kw_endmodule
, kw_endpackage
, kw_endprimitive
,
1765 kw_endprogram
, kw_endproperty
, kw_endsequence
,
1766 kw_endspecify
, kw_endtable
, kw_endtask
, kw_join
,
1767 kw_join_any
, kw_join_none
);
1770 /// Returns whether \p Tok is a Verilog keyword that opens a module, etc.
1771 bool isVerilogHierarchy(const FormatToken
&Tok
) const {
1772 if (Tok
.endsSequence(kw_function
, kw_with
))
1774 if (Tok
.is(kw_property
)) {
1775 const FormatToken
*Prev
= Tok
.getPreviousNonComment();
1777 Prev
->isOneOf(tok::kw_restrict
, kw_assert
, kw_assume
, kw_cover
));
1779 return Tok
.isOneOf(tok::kw_case
, tok::kw_class
, kw_function
, kw_module
,
1780 kw_interface
, kw_package
, kw_casex
, kw_casez
, kw_checker
,
1781 kw_clocking
, kw_covergroup
, kw_macromodule
, kw_primitive
,
1782 kw_program
, kw_property
, kw_randcase
, kw_randsequence
,
1786 bool isVerilogEndOfLabel(const FormatToken
&Tok
) const {
1787 const FormatToken
*Next
= Tok
.getNextNonComment();
1788 // In Verilog the colon in a default label is optional.
1789 return Tok
.is(TT_GotoLabelColon
) ||
1790 (Tok
.is(tok::kw_default
) &&
1791 !(Next
&& Next
->isOneOf(tok::colon
, tok::semi
, kw_clocking
, kw_iff
,
1792 kw_input
, kw_output
, kw_sequence
)));
1796 /// The JavaScript keywords beyond the C++ keyword set.
1797 std::unordered_set
<IdentifierInfo
*> JsExtraKeywords
;
1799 /// The C# keywords beyond the C++ keyword set
1800 std::unordered_set
<IdentifierInfo
*> CSharpExtraKeywords
;
1802 /// The Verilog keywords beyond the C++ keyword set.
1803 std::unordered_set
<IdentifierInfo
*> VerilogExtraKeywords
;
1806 inline bool isLineComment(const FormatToken
&FormatTok
) {
1807 return FormatTok
.is(tok::comment
) && !FormatTok
.TokenText
.startswith("/*");
1810 // Checks if \p FormatTok is a line comment that continues the line comment
1811 // \p Previous. The original column of \p MinColumnToken is used to determine
1812 // whether \p FormatTok is indented enough to the right to continue \p Previous.
1813 inline bool continuesLineComment(const FormatToken
&FormatTok
,
1814 const FormatToken
*Previous
,
1815 const FormatToken
*MinColumnToken
) {
1816 if (!Previous
|| !MinColumnToken
)
1818 unsigned MinContinueColumn
=
1819 MinColumnToken
->OriginalColumn
+ (isLineComment(*MinColumnToken
) ? 0 : 1);
1820 return isLineComment(FormatTok
) && FormatTok
.NewlinesBefore
== 1 &&
1821 isLineComment(*Previous
) &&
1822 FormatTok
.OriginalColumn
>= MinContinueColumn
;
1825 } // namespace format
1826 } // namespace clang