[DFAJumpThreading] Remove incoming StartBlock from all phis when unfolding select...
[llvm-project.git] / clang / lib / Format / FormatToken.h
blob87f6a76ec5bfd39fbf8f7c43ada578307a72ed2e
1 //===--- FormatToken.h - Format C++ code ------------------------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 ///
9 /// \file
10 /// This file contains the declaration of the FormatToken, a wrapper
11 /// around Token with additional information related to formatting.
12 ///
13 //===----------------------------------------------------------------------===//
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"
22 #include <memory>
23 #include <optional>
24 #include <unordered_set>
26 namespace clang {
27 namespace format {
29 #define LIST_TOKEN_TYPES \
30 TYPE(ArrayInitializerLSquare) \
31 TYPE(ArraySubscriptLSquare) \
32 TYPE(AttributeColon) \
33 TYPE(AttributeLParen) \
34 TYPE(AttributeMacro) \
35 TYPE(AttributeRParen) \
36 TYPE(AttributeSquare) \
37 TYPE(BinaryOperator) \
38 TYPE(BitFieldColon) \
39 TYPE(BlockComment) \
40 TYPE(BracedListLBrace) \
41 /* The colon at the end of a case label. */ \
42 TYPE(CaseLabelColon) \
43 TYPE(CastRParen) \
44 TYPE(ClassLBrace) \
45 TYPE(ClassRBrace) \
46 /* ternary ?: expression */ \
47 TYPE(ConditionalExpr) \
48 /* the condition in an if statement */ \
49 TYPE(ConditionLParen) \
50 TYPE(ConflictAlternative) \
51 TYPE(ConflictEnd) \
52 TYPE(ConflictStart) \
53 /* l_brace of if/for/while */ \
54 TYPE(ControlStatementLBrace) \
55 TYPE(ControlStatementRBrace) \
56 TYPE(CppCastLParen) \
57 TYPE(CSharpGenericTypeConstraint) \
58 TYPE(CSharpGenericTypeConstraintColon) \
59 TYPE(CSharpGenericTypeConstraintComma) \
60 TYPE(CSharpNamedArgumentColon) \
61 TYPE(CSharpNullable) \
62 TYPE(CSharpNullConditionalLSquare) \
63 TYPE(CSharpStringLiteral) \
64 TYPE(CtorInitializerColon) \
65 TYPE(CtorInitializerComma) \
66 TYPE(CtorDtorDeclName) \
67 TYPE(DesignatedInitializerLSquare) \
68 TYPE(DesignatedInitializerPeriod) \
69 TYPE(DictLiteral) \
70 TYPE(DoWhile) \
71 TYPE(ElseLBrace) \
72 TYPE(ElseRBrace) \
73 TYPE(EnumLBrace) \
74 TYPE(EnumRBrace) \
75 TYPE(FatArrow) \
76 TYPE(ForEachMacro) \
77 TYPE(FunctionAnnotationRParen) \
78 TYPE(FunctionDeclarationName) \
79 TYPE(FunctionLBrace) \
80 TYPE(FunctionLikeOrFreestandingMacro) \
81 TYPE(FunctionTypeLParen) \
82 /* The colons as part of a C11 _Generic selection */ \
83 TYPE(GenericSelectionColon) \
84 /* The colon at the end of a goto label. */ \
85 TYPE(GotoLabelColon) \
86 TYPE(IfMacro) \
87 TYPE(ImplicitStringLiteral) \
88 TYPE(InheritanceColon) \
89 TYPE(InheritanceComma) \
90 TYPE(InlineASMBrace) \
91 TYPE(InlineASMColon) \
92 TYPE(InlineASMSymbolicNameLSquare) \
93 TYPE(JavaAnnotation) \
94 TYPE(JsAndAndEqual) \
95 TYPE(JsComputedPropertyName) \
96 TYPE(JsExponentiation) \
97 TYPE(JsExponentiationEqual) \
98 TYPE(JsPipePipeEqual) \
99 TYPE(JsPrivateIdentifier) \
100 TYPE(JsTypeColon) \
101 TYPE(JsTypeOperator) \
102 TYPE(JsTypeOptionalQuestion) \
103 TYPE(LambdaLBrace) \
104 TYPE(LambdaLSquare) \
105 TYPE(LeadingJavaAnnotation) \
106 TYPE(LineComment) \
107 TYPE(MacroBlockBegin) \
108 TYPE(MacroBlockEnd) \
109 TYPE(ModulePartitionColon) \
110 TYPE(NamespaceLBrace) \
111 TYPE(NamespaceMacro) \
112 TYPE(NamespaceRBrace) \
113 TYPE(NonNullAssertion) \
114 TYPE(NullCoalescingEqual) \
115 TYPE(NullCoalescingOperator) \
116 TYPE(NullPropagatingOperator) \
117 TYPE(ObjCBlockLBrace) \
118 TYPE(ObjCBlockLParen) \
119 TYPE(ObjCDecl) \
120 TYPE(ObjCForIn) \
121 TYPE(ObjCMethodExpr) \
122 TYPE(ObjCMethodSpecifier) \
123 TYPE(ObjCProperty) \
124 TYPE(ObjCStringLiteral) \
125 TYPE(OverloadedOperator) \
126 TYPE(OverloadedOperatorLParen) \
127 TYPE(PointerOrReference) \
128 TYPE(ProtoExtensionLSquare) \
129 TYPE(PureVirtualSpecifier) \
130 TYPE(RangeBasedForLoopColon) \
131 TYPE(RecordLBrace) \
132 TYPE(RecordRBrace) \
133 TYPE(RegexLiteral) \
134 TYPE(RequiresClause) \
135 TYPE(RequiresClauseInARequiresExpression) \
136 TYPE(RequiresExpression) \
137 TYPE(RequiresExpressionLBrace) \
138 TYPE(RequiresExpressionLParen) \
139 TYPE(SelectorName) \
140 TYPE(StartOfName) \
141 TYPE(StatementAttributeLikeMacro) \
142 TYPE(StatementMacro) \
143 /* A string that is part of a string concatenation. For C#, JavaScript, and \
144 * Java, it is used for marking whether a string needs parentheses around it \
145 * if it is to be split into parts joined by `+`. For Verilog, whether \
146 * braces need to be added to split it. Not used for other languages. */ \
147 TYPE(StringInConcatenation) \
148 TYPE(StructLBrace) \
149 TYPE(StructRBrace) \
150 TYPE(StructuredBindingLSquare) \
151 TYPE(TemplateCloser) \
152 TYPE(TemplateOpener) \
153 TYPE(TemplateString) \
154 TYPE(TrailingAnnotation) \
155 TYPE(TrailingReturnArrow) \
156 TYPE(TrailingUnaryOperator) \
157 TYPE(TypeDeclarationParen) \
158 TYPE(TypeName) \
159 TYPE(TypenameMacro) \
160 TYPE(UnaryOperator) \
161 TYPE(UnionLBrace) \
162 TYPE(UnionRBrace) \
163 TYPE(UntouchableMacroFunc) \
164 /* Like in 'assign x = 0, y = 1;' . */ \
165 TYPE(VerilogAssignComma) \
166 /* like in begin : block */ \
167 TYPE(VerilogBlockLabelColon) \
168 /* The square bracket for the dimension part of the type name. \
169 * In 'logic [1:0] x[1:0]', only the first '['. This way we can have space \
170 * before the first bracket but not the second. */ \
171 TYPE(VerilogDimensionedTypeName) \
172 /* list of port connections or parameters in a module instantiation */ \
173 TYPE(VerilogInstancePortComma) \
174 TYPE(VerilogInstancePortLParen) \
175 /* A parenthesized list within which line breaks are inserted by the \
176 * formatter, for example the list of ports in a module header. */ \
177 TYPE(VerilogMultiLineListLParen) \
178 /* for the base in a number literal, not including the quote */ \
179 TYPE(VerilogNumberBase) \
180 /* like `(strong1, pull0)` */ \
181 TYPE(VerilogStrength) \
182 /* Things inside the table in user-defined primitives. */ \
183 TYPE(VerilogTableItem) \
184 /* those that separate ports of different types */ \
185 TYPE(VerilogTypeComma) \
186 TYPE(Unknown)
188 /// Determines the semantic type of a syntactic token, e.g. whether "<" is a
189 /// template opener or binary operator.
190 enum TokenType : uint8_t {
191 #define TYPE(X) TT_##X,
192 LIST_TOKEN_TYPES
193 #undef TYPE
194 NUM_TOKEN_TYPES
197 /// Determines the name of a token type.
198 const char *getTokenTypeName(TokenType Type);
200 // Represents what type of block a set of braces open.
201 enum BraceBlockKind { BK_Unknown, BK_Block, BK_BracedInit };
203 // The packing kind of a function's parameters.
204 enum ParameterPackingKind { PPK_BinPacked, PPK_OnePerLine, PPK_Inconclusive };
206 enum FormatDecision { FD_Unformatted, FD_Continue, FD_Break };
208 /// Roles a token can take in a configured macro expansion.
209 enum MacroRole {
210 /// The token was expanded from a macro argument when formatting the expanded
211 /// token sequence.
212 MR_ExpandedArg,
213 /// The token is part of a macro argument that was previously formatted as
214 /// expansion when formatting the unexpanded macro call.
215 MR_UnexpandedArg,
216 /// The token was expanded from a macro definition, and is not visible as part
217 /// of the macro call.
218 MR_Hidden,
221 struct FormatToken;
223 /// Contains information on the token's role in a macro expansion.
225 /// Given the following definitions:
226 /// A(X) = [ X ]
227 /// B(X) = < X >
228 /// C(X) = X
230 /// Consider the macro call:
231 /// A({B(C(C(x)))}) -> [{<x>}]
233 /// In this case, the tokens of the unexpanded macro call will have the
234 /// following relevant entries in their macro context (note that formatting
235 /// the unexpanded macro call happens *after* formatting the expanded macro
236 /// call):
237 /// A( { B( C( C(x) ) ) } )
238 /// Role: NN U NN NN NNUN N N U N (N=None, U=UnexpandedArg)
240 /// [ { < x > } ]
241 /// Role: H E H E H E H (H=Hidden, E=ExpandedArg)
242 /// ExpandedFrom[0]: A A A A A A A
243 /// ExpandedFrom[1]: B B B
244 /// ExpandedFrom[2]: C
245 /// ExpandedFrom[3]: C
246 /// StartOfExpansion: 1 0 1 2 0 0 0
247 /// EndOfExpansion: 0 0 0 2 1 0 1
248 struct MacroExpansion {
249 MacroExpansion(MacroRole Role) : Role(Role) {}
251 /// The token's role in the macro expansion.
252 /// When formatting an expanded macro, all tokens that are part of macro
253 /// arguments will be MR_ExpandedArg, while all tokens that are not visible in
254 /// the macro call will be MR_Hidden.
255 /// When formatting an unexpanded macro call, all tokens that are part of
256 /// macro arguments will be MR_UnexpandedArg.
257 MacroRole Role;
259 /// The stack of macro call identifier tokens this token was expanded from.
260 llvm::SmallVector<FormatToken *, 1> ExpandedFrom;
262 /// The number of expansions of which this macro is the first entry.
263 unsigned StartOfExpansion = 0;
265 /// The number of currently open expansions in \c ExpandedFrom this macro is
266 /// the last token in.
267 unsigned EndOfExpansion = 0;
270 class TokenRole;
271 class AnnotatedLine;
273 /// A wrapper around a \c Token storing information about the
274 /// whitespace characters preceding it.
275 struct FormatToken {
276 FormatToken()
277 : HasUnescapedNewline(false), IsMultiline(false), IsFirst(false),
278 MustBreakBefore(false), IsUnterminatedLiteral(false),
279 CanBreakBefore(false), ClosesTemplateDeclaration(false),
280 StartsBinaryExpression(false), EndsBinaryExpression(false),
281 PartOfMultiVariableDeclStmt(false), ContinuesLineCommentSection(false),
282 Finalized(false), ClosesRequiresClause(false),
283 EndsCppAttributeGroup(false), BlockKind(BK_Unknown),
284 Decision(FD_Unformatted), PackingKind(PPK_Inconclusive),
285 TypeIsFinalized(false), Type(TT_Unknown) {}
287 /// The \c Token.
288 Token Tok;
290 /// The raw text of the token.
292 /// Contains the raw token text without leading whitespace and without leading
293 /// escaped newlines.
294 StringRef TokenText;
296 /// A token can have a special role that can carry extra information
297 /// about the token's formatting.
298 /// FIXME: Make FormatToken for parsing and AnnotatedToken two different
299 /// classes and make this a unique_ptr in the AnnotatedToken class.
300 std::shared_ptr<TokenRole> Role;
302 /// The range of the whitespace immediately preceding the \c Token.
303 SourceRange WhitespaceRange;
305 /// Whether there is at least one unescaped newline before the \c
306 /// Token.
307 unsigned HasUnescapedNewline : 1;
309 /// Whether the token text contains newlines (escaped or not).
310 unsigned IsMultiline : 1;
312 /// Indicates that this is the first token of the file.
313 unsigned IsFirst : 1;
315 /// Whether there must be a line break before this token.
317 /// This happens for example when a preprocessor directive ended directly
318 /// before the token.
319 unsigned MustBreakBefore : 1;
321 /// Set to \c true if this token is an unterminated literal.
322 unsigned IsUnterminatedLiteral : 1;
324 /// \c true if it is allowed to break before this token.
325 unsigned CanBreakBefore : 1;
327 /// \c true if this is the ">" of "template<..>".
328 unsigned ClosesTemplateDeclaration : 1;
330 /// \c true if this token starts a binary expression, i.e. has at least
331 /// one fake l_paren with a precedence greater than prec::Unknown.
332 unsigned StartsBinaryExpression : 1;
333 /// \c true if this token ends a binary expression.
334 unsigned EndsBinaryExpression : 1;
336 /// Is this token part of a \c DeclStmt defining multiple variables?
338 /// Only set if \c Type == \c TT_StartOfName.
339 unsigned PartOfMultiVariableDeclStmt : 1;
341 /// Does this line comment continue a line comment section?
343 /// Only set to true if \c Type == \c TT_LineComment.
344 unsigned ContinuesLineCommentSection : 1;
346 /// If \c true, this token has been fully formatted (indented and
347 /// potentially re-formatted inside), and we do not allow further formatting
348 /// changes.
349 unsigned Finalized : 1;
351 /// \c true if this is the last token within requires clause.
352 unsigned ClosesRequiresClause : 1;
354 /// \c true if this token ends a group of C++ attributes.
355 unsigned EndsCppAttributeGroup : 1;
357 private:
358 /// Contains the kind of block if this token is a brace.
359 unsigned BlockKind : 2;
361 public:
362 BraceBlockKind getBlockKind() const {
363 return static_cast<BraceBlockKind>(BlockKind);
365 void setBlockKind(BraceBlockKind BBK) {
366 BlockKind = BBK;
367 assert(getBlockKind() == BBK && "BraceBlockKind overflow!");
370 private:
371 /// Stores the formatting decision for the token once it was made.
372 unsigned Decision : 2;
374 public:
375 FormatDecision getDecision() const {
376 return static_cast<FormatDecision>(Decision);
378 void setDecision(FormatDecision D) {
379 Decision = D;
380 assert(getDecision() == D && "FormatDecision overflow!");
383 private:
384 /// If this is an opening parenthesis, how are the parameters packed?
385 unsigned PackingKind : 2;
387 public:
388 ParameterPackingKind getPackingKind() const {
389 return static_cast<ParameterPackingKind>(PackingKind);
391 void setPackingKind(ParameterPackingKind K) {
392 PackingKind = K;
393 assert(getPackingKind() == K && "ParameterPackingKind overflow!");
396 private:
397 unsigned TypeIsFinalized : 1;
398 TokenType Type;
400 public:
401 /// Returns the token's type, e.g. whether "<" is a template opener or
402 /// binary operator.
403 TokenType getType() const { return Type; }
404 void setType(TokenType T) {
405 // If this token is a macro argument while formatting an unexpanded macro
406 // call, we do not change its type any more - the type was deduced from
407 // formatting the expanded macro stream already.
408 if (MacroCtx && MacroCtx->Role == MR_UnexpandedArg)
409 return;
410 assert((!TypeIsFinalized || T == Type) &&
411 "Please use overwriteFixedType to change a fixed type.");
412 Type = T;
414 /// Sets the type and also the finalized flag. This prevents the type to be
415 /// reset in TokenAnnotator::resetTokenMetadata(). If the type needs to be set
416 /// to another one please use overwriteFixedType, or even better remove the
417 /// need to reassign the type.
418 void setFinalizedType(TokenType T) {
419 Type = T;
420 TypeIsFinalized = true;
422 void overwriteFixedType(TokenType T) {
423 TypeIsFinalized = false;
424 setType(T);
426 bool isTypeFinalized() const { return TypeIsFinalized; }
428 /// Used to set an operator precedence explicitly.
429 prec::Level ForcedPrecedence = prec::Unknown;
431 /// The number of newlines immediately before the \c Token.
433 /// This can be used to determine what the user wrote in the original code
434 /// and thereby e.g. leave an empty line between two function definitions.
435 unsigned NewlinesBefore = 0;
437 /// The number of newlines immediately before the \c Token after formatting.
439 /// This is used to avoid overlapping whitespace replacements when \c Newlines
440 /// is recomputed for a finalized preprocessor branching directive.
441 int Newlines = -1;
443 /// The offset just past the last '\n' in this token's leading
444 /// whitespace (relative to \c WhiteSpaceStart). 0 if there is no '\n'.
445 unsigned LastNewlineOffset = 0;
447 /// The width of the non-whitespace parts of the token (or its first
448 /// line for multi-line tokens) in columns.
449 /// We need this to correctly measure number of columns a token spans.
450 unsigned ColumnWidth = 0;
452 /// Contains the width in columns of the last line of a multi-line
453 /// token.
454 unsigned LastLineColumnWidth = 0;
456 /// The number of spaces that should be inserted before this token.
457 unsigned SpacesRequiredBefore = 0;
459 /// Number of parameters, if this is "(", "[" or "<".
460 unsigned ParameterCount = 0;
462 /// Number of parameters that are nested blocks,
463 /// if this is "(", "[" or "<".
464 unsigned BlockParameterCount = 0;
466 /// If this is a bracket ("<", "(", "[" or "{"), contains the kind of
467 /// the surrounding bracket.
468 tok::TokenKind ParentBracket = tok::unknown;
470 /// The total length of the unwrapped line up to and including this
471 /// token.
472 unsigned TotalLength = 0;
474 /// The original 0-based column of this token, including expanded tabs.
475 /// The configured TabWidth is used as tab width.
476 unsigned OriginalColumn = 0;
478 /// The length of following tokens until the next natural split point,
479 /// or the next token that can be broken.
480 unsigned UnbreakableTailLength = 0;
482 // FIXME: Come up with a 'cleaner' concept.
483 /// The binding strength of a token. This is a combined value of
484 /// operator precedence, parenthesis nesting, etc.
485 unsigned BindingStrength = 0;
487 /// The nesting level of this token, i.e. the number of surrounding (),
488 /// [], {} or <>.
489 unsigned NestingLevel = 0;
491 /// The indent level of this token. Copied from the surrounding line.
492 unsigned IndentLevel = 0;
494 /// Penalty for inserting a line break before this token.
495 unsigned SplitPenalty = 0;
497 /// If this is the first ObjC selector name in an ObjC method
498 /// definition or call, this contains the length of the longest name.
500 /// This being set to 0 means that the selectors should not be colon-aligned,
501 /// e.g. because several of them are block-type.
502 unsigned LongestObjCSelectorName = 0;
504 /// If this is the first ObjC selector name in an ObjC method
505 /// definition or call, this contains the number of parts that the whole
506 /// selector consist of.
507 unsigned ObjCSelectorNameParts = 0;
509 /// The 0-based index of the parameter/argument. For ObjC it is set
510 /// for the selector name token.
511 /// For now calculated only for ObjC.
512 unsigned ParameterIndex = 0;
514 /// Stores the number of required fake parentheses and the
515 /// corresponding operator precedence.
517 /// If multiple fake parentheses start at a token, this vector stores them in
518 /// reverse order, i.e. inner fake parenthesis first.
519 SmallVector<prec::Level, 4> FakeLParens;
520 /// Insert this many fake ) after this token for correct indentation.
521 unsigned FakeRParens = 0;
523 /// If this is an operator (or "."/"->") in a sequence of operators
524 /// with the same precedence, contains the 0-based operator index.
525 unsigned OperatorIndex = 0;
527 /// If this is an operator (or "."/"->") in a sequence of operators
528 /// with the same precedence, points to the next operator.
529 FormatToken *NextOperator = nullptr;
531 /// If this is a bracket, this points to the matching one.
532 FormatToken *MatchingParen = nullptr;
534 /// The previous token in the unwrapped line.
535 FormatToken *Previous = nullptr;
537 /// The next token in the unwrapped line.
538 FormatToken *Next = nullptr;
540 /// The first token in set of column elements.
541 bool StartsColumn = false;
543 /// This notes the start of the line of an array initializer.
544 bool ArrayInitializerLineStart = false;
546 /// This starts an array initializer.
547 bool IsArrayInitializer = false;
549 /// Is optional and can be removed.
550 bool Optional = false;
552 /// Number of optional braces to be inserted after this token:
553 /// -1: a single left brace
554 /// 0: no braces
555 /// >0: number of right braces
556 int8_t BraceCount = 0;
558 /// If this token starts a block, this contains all the unwrapped lines
559 /// in it.
560 SmallVector<AnnotatedLine *, 1> Children;
562 // Contains all attributes related to how this token takes part
563 // in a configured macro expansion.
564 std::optional<MacroExpansion> MacroCtx;
566 /// When macro expansion introduces nodes with children, those are marked as
567 /// \c MacroParent.
568 /// FIXME: The formatting code currently hard-codes the assumption that
569 /// child nodes are introduced by blocks following an opening brace.
570 /// This is deeply baked into the code and disentangling this will require
571 /// signficant refactorings. \c MacroParent allows us to special-case the
572 /// cases in which we treat parents as block-openers for now.
573 bool MacroParent = false;
575 bool is(tok::TokenKind Kind) const { return Tok.is(Kind); }
576 bool is(TokenType TT) const { return getType() == TT; }
577 bool is(const IdentifierInfo *II) const {
578 return II && II == Tok.getIdentifierInfo();
580 bool is(tok::PPKeywordKind Kind) const {
581 return Tok.getIdentifierInfo() &&
582 Tok.getIdentifierInfo()->getPPKeywordID() == Kind;
584 bool is(BraceBlockKind BBK) const { return getBlockKind() == BBK; }
585 bool is(ParameterPackingKind PPK) const { return getPackingKind() == PPK; }
587 template <typename A, typename B> bool isOneOf(A K1, B K2) const {
588 return is(K1) || is(K2);
590 template <typename A, typename B, typename... Ts>
591 bool isOneOf(A K1, B K2, Ts... Ks) const {
592 return is(K1) || isOneOf(K2, Ks...);
594 template <typename T> bool isNot(T Kind) const { return !is(Kind); }
596 bool isIf(bool AllowConstexprMacro = true) const {
597 return is(tok::kw_if) || endsSequence(tok::kw_constexpr, tok::kw_if) ||
598 (endsSequence(tok::identifier, tok::kw_if) && AllowConstexprMacro);
601 bool closesScopeAfterBlock() const {
602 if (getBlockKind() == BK_Block)
603 return true;
604 if (closesScope())
605 return Previous->closesScopeAfterBlock();
606 return false;
609 /// \c true if this token starts a sequence with the given tokens in order,
610 /// following the ``Next`` pointers, ignoring comments.
611 template <typename A, typename... Ts>
612 bool startsSequence(A K1, Ts... Tokens) const {
613 return startsSequenceInternal(K1, Tokens...);
616 /// \c true if this token ends a sequence with the given tokens in order,
617 /// following the ``Previous`` pointers, ignoring comments.
618 /// For example, given tokens [T1, T2, T3], the function returns true if
619 /// 3 tokens ending at this (ignoring comments) are [T3, T2, T1]. In other
620 /// words, the tokens passed to this function need to the reverse of the
621 /// order the tokens appear in code.
622 template <typename A, typename... Ts>
623 bool endsSequence(A K1, Ts... Tokens) const {
624 return endsSequenceInternal(K1, Tokens...);
627 bool isStringLiteral() const { return tok::isStringLiteral(Tok.getKind()); }
629 bool isAttribute() const {
630 return isOneOf(tok::kw___attribute, tok::kw___declspec, TT_AttributeMacro);
633 bool isObjCAtKeyword(tok::ObjCKeywordKind Kind) const {
634 return Tok.isObjCAtKeyword(Kind);
637 bool isAccessSpecifier(bool ColonRequired = true) const {
638 if (!isOneOf(tok::kw_public, tok::kw_protected, tok::kw_private))
639 return false;
640 if (!ColonRequired)
641 return true;
642 const auto NextNonComment = getNextNonComment();
643 return NextNonComment && NextNonComment->is(tok::colon);
646 bool canBePointerOrReferenceQualifier() const {
647 return isOneOf(tok::kw_const, tok::kw_restrict, tok::kw_volatile,
648 tok::kw__Nonnull, tok::kw__Nullable,
649 tok::kw__Null_unspecified, tok::kw___ptr32, tok::kw___ptr64,
650 tok::kw___funcref) ||
651 isAttribute();
654 /// Determine whether the token is a simple-type-specifier.
655 [[nodiscard]] bool isSimpleTypeSpecifier() const;
657 [[nodiscard]] bool isTypeOrIdentifier() const;
659 bool isObjCAccessSpecifier() const {
660 return is(tok::at) && Next &&
661 (Next->isObjCAtKeyword(tok::objc_public) ||
662 Next->isObjCAtKeyword(tok::objc_protected) ||
663 Next->isObjCAtKeyword(tok::objc_package) ||
664 Next->isObjCAtKeyword(tok::objc_private));
667 /// Returns whether \p Tok is ([{ or an opening < of a template or in
668 /// protos.
669 bool opensScope() const {
670 if (is(TT_TemplateString) && TokenText.endswith("${"))
671 return true;
672 if (is(TT_DictLiteral) && is(tok::less))
673 return true;
674 return isOneOf(tok::l_paren, tok::l_brace, tok::l_square,
675 TT_TemplateOpener);
677 /// Returns whether \p Tok is )]} or a closing > of a template or in
678 /// protos.
679 bool closesScope() const {
680 if (is(TT_TemplateString) && TokenText.startswith("}"))
681 return true;
682 if (is(TT_DictLiteral) && is(tok::greater))
683 return true;
684 return isOneOf(tok::r_paren, tok::r_brace, tok::r_square,
685 TT_TemplateCloser);
688 /// Returns \c true if this is a "." or "->" accessing a member.
689 bool isMemberAccess() const {
690 return isOneOf(tok::arrow, tok::period, tok::arrowstar) &&
691 !isOneOf(TT_DesignatedInitializerPeriod, TT_TrailingReturnArrow,
692 TT_LeadingJavaAnnotation);
695 bool isUnaryOperator() const {
696 switch (Tok.getKind()) {
697 case tok::plus:
698 case tok::plusplus:
699 case tok::minus:
700 case tok::minusminus:
701 case tok::exclaim:
702 case tok::tilde:
703 case tok::kw_sizeof:
704 case tok::kw_alignof:
705 return true;
706 default:
707 return false;
711 bool isBinaryOperator() const {
712 // Comma is a binary operator, but does not behave as such wrt. formatting.
713 return getPrecedence() > prec::Comma;
716 bool isTrailingComment() const {
717 return is(tok::comment) &&
718 (is(TT_LineComment) || !Next || Next->NewlinesBefore > 0);
721 /// Returns \c true if this is a keyword that can be used
722 /// like a function call (e.g. sizeof, typeid, ...).
723 bool isFunctionLikeKeyword() const {
724 if (isAttribute())
725 return true;
727 return isOneOf(tok::kw_throw, tok::kw_typeid, tok::kw_return,
728 tok::kw_sizeof, tok::kw_alignof, tok::kw_alignas,
729 tok::kw_decltype, tok::kw_noexcept, tok::kw_static_assert,
730 tok::kw__Atomic,
731 #define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) tok::kw___##Trait,
732 #include "clang/Basic/TransformTypeTraits.def"
733 tok::kw_requires);
736 /// Returns \c true if this is a string literal that's like a label,
737 /// e.g. ends with "=" or ":".
738 bool isLabelString() const {
739 if (isNot(tok::string_literal))
740 return false;
741 StringRef Content = TokenText;
742 if (Content.startswith("\"") || Content.startswith("'"))
743 Content = Content.drop_front(1);
744 if (Content.endswith("\"") || Content.endswith("'"))
745 Content = Content.drop_back(1);
746 Content = Content.trim();
747 return Content.size() > 1 &&
748 (Content.back() == ':' || Content.back() == '=');
751 /// Returns actual token start location without leading escaped
752 /// newlines and whitespace.
754 /// This can be different to Tok.getLocation(), which includes leading escaped
755 /// newlines.
756 SourceLocation getStartOfNonWhitespace() const {
757 return WhitespaceRange.getEnd();
760 /// Returns \c true if the range of whitespace immediately preceding the \c
761 /// Token is not empty.
762 bool hasWhitespaceBefore() const {
763 return WhitespaceRange.getBegin() != WhitespaceRange.getEnd();
766 prec::Level getPrecedence() const {
767 if (ForcedPrecedence != prec::Unknown)
768 return ForcedPrecedence;
769 return getBinOpPrecedence(Tok.getKind(), /*GreaterThanIsOperator=*/true,
770 /*CPlusPlus11=*/true);
773 /// Returns the previous token ignoring comments.
774 [[nodiscard]] FormatToken *getPreviousNonComment() const {
775 FormatToken *Tok = Previous;
776 while (Tok && Tok->is(tok::comment))
777 Tok = Tok->Previous;
778 return Tok;
781 /// Returns the next token ignoring comments.
782 [[nodiscard]] FormatToken *getNextNonComment() const {
783 FormatToken *Tok = Next;
784 while (Tok && Tok->is(tok::comment))
785 Tok = Tok->Next;
786 return Tok;
789 /// Returns \c true if this token ends a block indented initializer list.
790 [[nodiscard]] bool isBlockIndentedInitRBrace(const FormatStyle &Style) const;
792 /// Returns \c true if this tokens starts a block-type list, i.e. a
793 /// list that should be indented with a block indent.
794 [[nodiscard]] bool opensBlockOrBlockTypeList(const FormatStyle &Style) const;
796 /// Returns whether the token is the left square bracket of a C++
797 /// structured binding declaration.
798 bool isCppStructuredBinding(const FormatStyle &Style) const {
799 if (!Style.isCpp() || isNot(tok::l_square))
800 return false;
801 const FormatToken *T = this;
802 do {
803 T = T->getPreviousNonComment();
804 } while (T && T->isOneOf(tok::kw_const, tok::kw_volatile, tok::amp,
805 tok::ampamp));
806 return T && T->is(tok::kw_auto);
809 /// Same as opensBlockOrBlockTypeList, but for the closing token.
810 bool closesBlockOrBlockTypeList(const FormatStyle &Style) const {
811 if (is(TT_TemplateString) && closesScope())
812 return true;
813 return MatchingParen && MatchingParen->opensBlockOrBlockTypeList(Style);
816 /// Return the actual namespace token, if this token starts a namespace
817 /// block.
818 const FormatToken *getNamespaceToken() const {
819 const FormatToken *NamespaceTok = this;
820 if (is(tok::comment))
821 NamespaceTok = NamespaceTok->getNextNonComment();
822 // Detect "(inline|export)? namespace" in the beginning of a line.
823 if (NamespaceTok && NamespaceTok->isOneOf(tok::kw_inline, tok::kw_export))
824 NamespaceTok = NamespaceTok->getNextNonComment();
825 return NamespaceTok &&
826 NamespaceTok->isOneOf(tok::kw_namespace, TT_NamespaceMacro)
827 ? NamespaceTok
828 : nullptr;
831 void copyFrom(const FormatToken &Tok) { *this = Tok; }
833 private:
834 // Only allow copying via the explicit copyFrom method.
835 FormatToken(const FormatToken &) = delete;
836 FormatToken &operator=(const FormatToken &) = default;
838 template <typename A, typename... Ts>
839 bool startsSequenceInternal(A K1, Ts... Tokens) const {
840 if (is(tok::comment) && Next)
841 return Next->startsSequenceInternal(K1, Tokens...);
842 return is(K1) && Next && Next->startsSequenceInternal(Tokens...);
845 template <typename A> bool startsSequenceInternal(A K1) const {
846 if (is(tok::comment) && Next)
847 return Next->startsSequenceInternal(K1);
848 return is(K1);
851 template <typename A, typename... Ts> bool endsSequenceInternal(A K1) const {
852 if (is(tok::comment) && Previous)
853 return Previous->endsSequenceInternal(K1);
854 return is(K1);
857 template <typename A, typename... Ts>
858 bool endsSequenceInternal(A K1, Ts... Tokens) const {
859 if (is(tok::comment) && Previous)
860 return Previous->endsSequenceInternal(K1, Tokens...);
861 return is(K1) && Previous && Previous->endsSequenceInternal(Tokens...);
865 class ContinuationIndenter;
866 struct LineState;
868 class TokenRole {
869 public:
870 TokenRole(const FormatStyle &Style) : Style(Style) {}
871 virtual ~TokenRole();
873 /// After the \c TokenAnnotator has finished annotating all the tokens,
874 /// this function precomputes required information for formatting.
875 virtual void precomputeFormattingInfos(const FormatToken *Token);
877 /// Apply the special formatting that the given role demands.
879 /// Assumes that the token having this role is already formatted.
881 /// Continues formatting from \p State leaving indentation to \p Indenter and
882 /// returns the total penalty that this formatting incurs.
883 virtual unsigned formatFromToken(LineState &State,
884 ContinuationIndenter *Indenter,
885 bool DryRun) {
886 return 0;
889 /// Same as \c formatFromToken, but assumes that the first token has
890 /// already been set thereby deciding on the first line break.
891 virtual unsigned formatAfterToken(LineState &State,
892 ContinuationIndenter *Indenter,
893 bool DryRun) {
894 return 0;
897 /// Notifies the \c Role that a comma was found.
898 virtual void CommaFound(const FormatToken *Token) {}
900 virtual const FormatToken *lastComma() { return nullptr; }
902 protected:
903 const FormatStyle &Style;
906 class CommaSeparatedList : public TokenRole {
907 public:
908 CommaSeparatedList(const FormatStyle &Style)
909 : TokenRole(Style), HasNestedBracedList(false) {}
911 void precomputeFormattingInfos(const FormatToken *Token) override;
913 unsigned formatAfterToken(LineState &State, ContinuationIndenter *Indenter,
914 bool DryRun) override;
916 unsigned formatFromToken(LineState &State, ContinuationIndenter *Indenter,
917 bool DryRun) override;
919 /// Adds \p Token as the next comma to the \c CommaSeparated list.
920 void CommaFound(const FormatToken *Token) override {
921 Commas.push_back(Token);
924 const FormatToken *lastComma() override {
925 if (Commas.empty())
926 return nullptr;
927 return Commas.back();
930 private:
931 /// A struct that holds information on how to format a given list with
932 /// a specific number of columns.
933 struct ColumnFormat {
934 /// The number of columns to use.
935 unsigned Columns;
937 /// The total width in characters.
938 unsigned TotalWidth;
940 /// The number of lines required for this format.
941 unsigned LineCount;
943 /// The size of each column in characters.
944 SmallVector<unsigned, 8> ColumnSizes;
947 /// Calculate which \c ColumnFormat fits best into
948 /// \p RemainingCharacters.
949 const ColumnFormat *getColumnFormat(unsigned RemainingCharacters) const;
951 /// The ordered \c FormatTokens making up the commas of this list.
952 SmallVector<const FormatToken *, 8> Commas;
954 /// The length of each of the list's items in characters including the
955 /// trailing comma.
956 SmallVector<unsigned, 8> ItemLengths;
958 /// Precomputed formats that can be used for this list.
959 SmallVector<ColumnFormat, 4> Formats;
961 bool HasNestedBracedList;
964 /// Encapsulates keywords that are context sensitive or for languages not
965 /// properly supported by Clang's lexer.
966 struct AdditionalKeywords {
967 AdditionalKeywords(IdentifierTable &IdentTable) {
968 kw_final = &IdentTable.get("final");
969 kw_override = &IdentTable.get("override");
970 kw_in = &IdentTable.get("in");
971 kw_of = &IdentTable.get("of");
972 kw_CF_CLOSED_ENUM = &IdentTable.get("CF_CLOSED_ENUM");
973 kw_CF_ENUM = &IdentTable.get("CF_ENUM");
974 kw_CF_OPTIONS = &IdentTable.get("CF_OPTIONS");
975 kw_NS_CLOSED_ENUM = &IdentTable.get("NS_CLOSED_ENUM");
976 kw_NS_ENUM = &IdentTable.get("NS_ENUM");
977 kw_NS_ERROR_ENUM = &IdentTable.get("NS_ERROR_ENUM");
978 kw_NS_OPTIONS = &IdentTable.get("NS_OPTIONS");
980 kw_as = &IdentTable.get("as");
981 kw_async = &IdentTable.get("async");
982 kw_await = &IdentTable.get("await");
983 kw_declare = &IdentTable.get("declare");
984 kw_finally = &IdentTable.get("finally");
985 kw_from = &IdentTable.get("from");
986 kw_function = &IdentTable.get("function");
987 kw_get = &IdentTable.get("get");
988 kw_import = &IdentTable.get("import");
989 kw_infer = &IdentTable.get("infer");
990 kw_is = &IdentTable.get("is");
991 kw_let = &IdentTable.get("let");
992 kw_module = &IdentTable.get("module");
993 kw_readonly = &IdentTable.get("readonly");
994 kw_set = &IdentTable.get("set");
995 kw_type = &IdentTable.get("type");
996 kw_typeof = &IdentTable.get("typeof");
997 kw_var = &IdentTable.get("var");
998 kw_yield = &IdentTable.get("yield");
1000 kw_abstract = &IdentTable.get("abstract");
1001 kw_assert = &IdentTable.get("assert");
1002 kw_extends = &IdentTable.get("extends");
1003 kw_implements = &IdentTable.get("implements");
1004 kw_instanceof = &IdentTable.get("instanceof");
1005 kw_interface = &IdentTable.get("interface");
1006 kw_native = &IdentTable.get("native");
1007 kw_package = &IdentTable.get("package");
1008 kw_synchronized = &IdentTable.get("synchronized");
1009 kw_throws = &IdentTable.get("throws");
1010 kw___except = &IdentTable.get("__except");
1011 kw___has_include = &IdentTable.get("__has_include");
1012 kw___has_include_next = &IdentTable.get("__has_include_next");
1014 kw_mark = &IdentTable.get("mark");
1015 kw_region = &IdentTable.get("region");
1017 kw_extend = &IdentTable.get("extend");
1018 kw_option = &IdentTable.get("option");
1019 kw_optional = &IdentTable.get("optional");
1020 kw_repeated = &IdentTable.get("repeated");
1021 kw_required = &IdentTable.get("required");
1022 kw_returns = &IdentTable.get("returns");
1024 kw_signals = &IdentTable.get("signals");
1025 kw_qsignals = &IdentTable.get("Q_SIGNALS");
1026 kw_slots = &IdentTable.get("slots");
1027 kw_qslots = &IdentTable.get("Q_SLOTS");
1029 // For internal clang-format use.
1030 kw_internal_ident_after_define =
1031 &IdentTable.get("__CLANG_FORMAT_INTERNAL_IDENT_AFTER_DEFINE__");
1033 // C# keywords
1034 kw_dollar = &IdentTable.get("dollar");
1035 kw_base = &IdentTable.get("base");
1036 kw_byte = &IdentTable.get("byte");
1037 kw_checked = &IdentTable.get("checked");
1038 kw_decimal = &IdentTable.get("decimal");
1039 kw_delegate = &IdentTable.get("delegate");
1040 kw_event = &IdentTable.get("event");
1041 kw_fixed = &IdentTable.get("fixed");
1042 kw_foreach = &IdentTable.get("foreach");
1043 kw_init = &IdentTable.get("init");
1044 kw_implicit = &IdentTable.get("implicit");
1045 kw_internal = &IdentTable.get("internal");
1046 kw_lock = &IdentTable.get("lock");
1047 kw_null = &IdentTable.get("null");
1048 kw_object = &IdentTable.get("object");
1049 kw_out = &IdentTable.get("out");
1050 kw_params = &IdentTable.get("params");
1051 kw_ref = &IdentTable.get("ref");
1052 kw_string = &IdentTable.get("string");
1053 kw_stackalloc = &IdentTable.get("stackalloc");
1054 kw_sbyte = &IdentTable.get("sbyte");
1055 kw_sealed = &IdentTable.get("sealed");
1056 kw_uint = &IdentTable.get("uint");
1057 kw_ulong = &IdentTable.get("ulong");
1058 kw_unchecked = &IdentTable.get("unchecked");
1059 kw_unsafe = &IdentTable.get("unsafe");
1060 kw_ushort = &IdentTable.get("ushort");
1061 kw_when = &IdentTable.get("when");
1062 kw_where = &IdentTable.get("where");
1064 // Verilog keywords
1065 kw_always = &IdentTable.get("always");
1066 kw_always_comb = &IdentTable.get("always_comb");
1067 kw_always_ff = &IdentTable.get("always_ff");
1068 kw_always_latch = &IdentTable.get("always_latch");
1069 kw_assign = &IdentTable.get("assign");
1070 kw_assume = &IdentTable.get("assume");
1071 kw_automatic = &IdentTable.get("automatic");
1072 kw_before = &IdentTable.get("before");
1073 kw_begin = &IdentTable.get("begin");
1074 kw_begin_keywords = &IdentTable.get("begin_keywords");
1075 kw_bins = &IdentTable.get("bins");
1076 kw_binsof = &IdentTable.get("binsof");
1077 kw_casex = &IdentTable.get("casex");
1078 kw_casez = &IdentTable.get("casez");
1079 kw_celldefine = &IdentTable.get("celldefine");
1080 kw_checker = &IdentTable.get("checker");
1081 kw_clocking = &IdentTable.get("clocking");
1082 kw_constraint = &IdentTable.get("constraint");
1083 kw_cover = &IdentTable.get("cover");
1084 kw_covergroup = &IdentTable.get("covergroup");
1085 kw_coverpoint = &IdentTable.get("coverpoint");
1086 kw_default_decay_time = &IdentTable.get("default_decay_time");
1087 kw_default_nettype = &IdentTable.get("default_nettype");
1088 kw_default_trireg_strength = &IdentTable.get("default_trireg_strength");
1089 kw_delay_mode_distributed = &IdentTable.get("delay_mode_distributed");
1090 kw_delay_mode_path = &IdentTable.get("delay_mode_path");
1091 kw_delay_mode_unit = &IdentTable.get("delay_mode_unit");
1092 kw_delay_mode_zero = &IdentTable.get("delay_mode_zero");
1093 kw_disable = &IdentTable.get("disable");
1094 kw_dist = &IdentTable.get("dist");
1095 kw_edge = &IdentTable.get("edge");
1096 kw_elsif = &IdentTable.get("elsif");
1097 kw_end = &IdentTable.get("end");
1098 kw_end_keywords = &IdentTable.get("end_keywords");
1099 kw_endcase = &IdentTable.get("endcase");
1100 kw_endcelldefine = &IdentTable.get("endcelldefine");
1101 kw_endchecker = &IdentTable.get("endchecker");
1102 kw_endclass = &IdentTable.get("endclass");
1103 kw_endclocking = &IdentTable.get("endclocking");
1104 kw_endfunction = &IdentTable.get("endfunction");
1105 kw_endgenerate = &IdentTable.get("endgenerate");
1106 kw_endgroup = &IdentTable.get("endgroup");
1107 kw_endinterface = &IdentTable.get("endinterface");
1108 kw_endmodule = &IdentTable.get("endmodule");
1109 kw_endpackage = &IdentTable.get("endpackage");
1110 kw_endprimitive = &IdentTable.get("endprimitive");
1111 kw_endprogram = &IdentTable.get("endprogram");
1112 kw_endproperty = &IdentTable.get("endproperty");
1113 kw_endsequence = &IdentTable.get("endsequence");
1114 kw_endspecify = &IdentTable.get("endspecify");
1115 kw_endtable = &IdentTable.get("endtable");
1116 kw_endtask = &IdentTable.get("endtask");
1117 kw_forever = &IdentTable.get("forever");
1118 kw_fork = &IdentTable.get("fork");
1119 kw_generate = &IdentTable.get("generate");
1120 kw_highz0 = &IdentTable.get("highz0");
1121 kw_highz1 = &IdentTable.get("highz1");
1122 kw_iff = &IdentTable.get("iff");
1123 kw_ifnone = &IdentTable.get("ifnone");
1124 kw_ignore_bins = &IdentTable.get("ignore_bins");
1125 kw_illegal_bins = &IdentTable.get("illegal_bins");
1126 kw_initial = &IdentTable.get("initial");
1127 kw_inout = &IdentTable.get("inout");
1128 kw_input = &IdentTable.get("input");
1129 kw_inside = &IdentTable.get("inside");
1130 kw_interconnect = &IdentTable.get("interconnect");
1131 kw_intersect = &IdentTable.get("intersect");
1132 kw_join = &IdentTable.get("join");
1133 kw_join_any = &IdentTable.get("join_any");
1134 kw_join_none = &IdentTable.get("join_none");
1135 kw_large = &IdentTable.get("large");
1136 kw_local = &IdentTable.get("local");
1137 kw_localparam = &IdentTable.get("localparam");
1138 kw_macromodule = &IdentTable.get("macromodule");
1139 kw_matches = &IdentTable.get("matches");
1140 kw_medium = &IdentTable.get("medium");
1141 kw_negedge = &IdentTable.get("negedge");
1142 kw_nounconnected_drive = &IdentTable.get("nounconnected_drive");
1143 kw_output = &IdentTable.get("output");
1144 kw_packed = &IdentTable.get("packed");
1145 kw_parameter = &IdentTable.get("parameter");
1146 kw_posedge = &IdentTable.get("posedge");
1147 kw_primitive = &IdentTable.get("primitive");
1148 kw_priority = &IdentTable.get("priority");
1149 kw_program = &IdentTable.get("program");
1150 kw_property = &IdentTable.get("property");
1151 kw_pull0 = &IdentTable.get("pull0");
1152 kw_pull1 = &IdentTable.get("pull1");
1153 kw_pure = &IdentTable.get("pure");
1154 kw_rand = &IdentTable.get("rand");
1155 kw_randc = &IdentTable.get("randc");
1156 kw_randcase = &IdentTable.get("randcase");
1157 kw_randsequence = &IdentTable.get("randsequence");
1158 kw_repeat = &IdentTable.get("repeat");
1159 kw_resetall = &IdentTable.get("resetall");
1160 kw_sample = &IdentTable.get("sample");
1161 kw_scalared = &IdentTable.get("scalared");
1162 kw_sequence = &IdentTable.get("sequence");
1163 kw_small = &IdentTable.get("small");
1164 kw_soft = &IdentTable.get("soft");
1165 kw_solve = &IdentTable.get("solve");
1166 kw_specify = &IdentTable.get("specify");
1167 kw_specparam = &IdentTable.get("specparam");
1168 kw_strong0 = &IdentTable.get("strong0");
1169 kw_strong1 = &IdentTable.get("strong1");
1170 kw_supply0 = &IdentTable.get("supply0");
1171 kw_supply1 = &IdentTable.get("supply1");
1172 kw_table = &IdentTable.get("table");
1173 kw_tagged = &IdentTable.get("tagged");
1174 kw_task = &IdentTable.get("task");
1175 kw_timescale = &IdentTable.get("timescale");
1176 kw_tri = &IdentTable.get("tri");
1177 kw_tri0 = &IdentTable.get("tri0");
1178 kw_tri1 = &IdentTable.get("tri1");
1179 kw_triand = &IdentTable.get("triand");
1180 kw_trior = &IdentTable.get("trior");
1181 kw_trireg = &IdentTable.get("trireg");
1182 kw_unconnected_drive = &IdentTable.get("unconnected_drive");
1183 kw_undefineall = &IdentTable.get("undefineall");
1184 kw_unique = &IdentTable.get("unique");
1185 kw_unique0 = &IdentTable.get("unique0");
1186 kw_uwire = &IdentTable.get("uwire");
1187 kw_vectored = &IdentTable.get("vectored");
1188 kw_wand = &IdentTable.get("wand");
1189 kw_weak0 = &IdentTable.get("weak0");
1190 kw_weak1 = &IdentTable.get("weak1");
1191 kw_wildcard = &IdentTable.get("wildcard");
1192 kw_wire = &IdentTable.get("wire");
1193 kw_with = &IdentTable.get("with");
1194 kw_wor = &IdentTable.get("wor");
1196 // Symbols that are treated as keywords.
1197 kw_verilogHash = &IdentTable.get("#");
1198 kw_verilogHashHash = &IdentTable.get("##");
1199 kw_apostrophe = &IdentTable.get("\'");
1201 // Keep this at the end of the constructor to make sure everything here
1202 // is
1203 // already initialized.
1204 JsExtraKeywords = std::unordered_set<IdentifierInfo *>(
1205 {kw_as, kw_async, kw_await, kw_declare, kw_finally, kw_from,
1206 kw_function, kw_get, kw_import, kw_is, kw_let, kw_module, kw_override,
1207 kw_readonly, kw_set, kw_type, kw_typeof, kw_var, kw_yield,
1208 // Keywords from the Java section.
1209 kw_abstract, kw_extends, kw_implements, kw_instanceof, kw_interface});
1211 CSharpExtraKeywords = std::unordered_set<IdentifierInfo *>(
1212 {kw_base, kw_byte, kw_checked, kw_decimal, kw_delegate, kw_event,
1213 kw_fixed, kw_foreach, kw_implicit, kw_in, kw_init, kw_interface,
1214 kw_internal, kw_is, kw_lock, kw_null, kw_object, kw_out, kw_override,
1215 kw_params, kw_readonly, kw_ref, kw_string, kw_stackalloc, kw_sbyte,
1216 kw_sealed, kw_uint, kw_ulong, kw_unchecked, kw_unsafe, kw_ushort,
1217 kw_when, kw_where,
1218 // Keywords from the JavaScript section.
1219 kw_as, kw_async, kw_await, kw_declare, kw_finally, kw_from,
1220 kw_function, kw_get, kw_import, kw_is, kw_let, kw_module, kw_readonly,
1221 kw_set, kw_type, kw_typeof, kw_var, kw_yield,
1222 // Keywords from the Java section.
1223 kw_abstract, kw_extends, kw_implements, kw_instanceof, kw_interface});
1225 // Some keywords are not included here because they don't need special
1226 // treatment like `showcancelled` or they should be treated as identifiers
1227 // like `int` and `logic`.
1228 VerilogExtraKeywords = std::unordered_set<IdentifierInfo *>(
1229 {kw_always, kw_always_comb,
1230 kw_always_ff, kw_always_latch,
1231 kw_assert, kw_assign,
1232 kw_assume, kw_automatic,
1233 kw_before, kw_begin,
1234 kw_bins, kw_binsof,
1235 kw_casex, kw_casez,
1236 kw_celldefine, kw_checker,
1237 kw_clocking, kw_constraint,
1238 kw_cover, kw_covergroup,
1239 kw_coverpoint, kw_disable,
1240 kw_dist, kw_edge,
1241 kw_end, kw_endcase,
1242 kw_endchecker, kw_endclass,
1243 kw_endclocking, kw_endfunction,
1244 kw_endgenerate, kw_endgroup,
1245 kw_endinterface, kw_endmodule,
1246 kw_endpackage, kw_endprimitive,
1247 kw_endprogram, kw_endproperty,
1248 kw_endsequence, kw_endspecify,
1249 kw_endtable, kw_endtask,
1250 kw_extends, kw_final,
1251 kw_foreach, kw_forever,
1252 kw_fork, kw_function,
1253 kw_generate, kw_highz0,
1254 kw_highz1, kw_iff,
1255 kw_ifnone, kw_ignore_bins,
1256 kw_illegal_bins, kw_implements,
1257 kw_import, kw_initial,
1258 kw_inout, kw_input,
1259 kw_inside, kw_interconnect,
1260 kw_interface, kw_intersect,
1261 kw_join, kw_join_any,
1262 kw_join_none, kw_large,
1263 kw_let, kw_local,
1264 kw_localparam, kw_macromodule,
1265 kw_matches, kw_medium,
1266 kw_negedge, kw_output,
1267 kw_package, kw_packed,
1268 kw_parameter, kw_posedge,
1269 kw_primitive, kw_priority,
1270 kw_program, kw_property,
1271 kw_pull0, kw_pull1,
1272 kw_pure, kw_rand,
1273 kw_randc, kw_randcase,
1274 kw_randsequence, kw_ref,
1275 kw_repeat, kw_sample,
1276 kw_scalared, kw_sequence,
1277 kw_small, kw_soft,
1278 kw_solve, kw_specify,
1279 kw_specparam, kw_strong0,
1280 kw_strong1, kw_supply0,
1281 kw_supply1, kw_table,
1282 kw_tagged, kw_task,
1283 kw_tri, kw_tri0,
1284 kw_tri1, kw_triand,
1285 kw_trior, kw_trireg,
1286 kw_unique, kw_unique0,
1287 kw_uwire, kw_var,
1288 kw_vectored, kw_wand,
1289 kw_weak0, kw_weak1,
1290 kw_wildcard, kw_wire,
1291 kw_with, kw_wor,
1292 kw_verilogHash, kw_verilogHashHash});
1295 // Context sensitive keywords.
1296 IdentifierInfo *kw_final;
1297 IdentifierInfo *kw_override;
1298 IdentifierInfo *kw_in;
1299 IdentifierInfo *kw_of;
1300 IdentifierInfo *kw_CF_CLOSED_ENUM;
1301 IdentifierInfo *kw_CF_ENUM;
1302 IdentifierInfo *kw_CF_OPTIONS;
1303 IdentifierInfo *kw_NS_CLOSED_ENUM;
1304 IdentifierInfo *kw_NS_ENUM;
1305 IdentifierInfo *kw_NS_ERROR_ENUM;
1306 IdentifierInfo *kw_NS_OPTIONS;
1307 IdentifierInfo *kw___except;
1308 IdentifierInfo *kw___has_include;
1309 IdentifierInfo *kw___has_include_next;
1311 // JavaScript keywords.
1312 IdentifierInfo *kw_as;
1313 IdentifierInfo *kw_async;
1314 IdentifierInfo *kw_await;
1315 IdentifierInfo *kw_declare;
1316 IdentifierInfo *kw_finally;
1317 IdentifierInfo *kw_from;
1318 IdentifierInfo *kw_function;
1319 IdentifierInfo *kw_get;
1320 IdentifierInfo *kw_import;
1321 IdentifierInfo *kw_infer;
1322 IdentifierInfo *kw_is;
1323 IdentifierInfo *kw_let;
1324 IdentifierInfo *kw_module;
1325 IdentifierInfo *kw_readonly;
1326 IdentifierInfo *kw_set;
1327 IdentifierInfo *kw_type;
1328 IdentifierInfo *kw_typeof;
1329 IdentifierInfo *kw_var;
1330 IdentifierInfo *kw_yield;
1332 // Java keywords.
1333 IdentifierInfo *kw_abstract;
1334 IdentifierInfo *kw_assert;
1335 IdentifierInfo *kw_extends;
1336 IdentifierInfo *kw_implements;
1337 IdentifierInfo *kw_instanceof;
1338 IdentifierInfo *kw_interface;
1339 IdentifierInfo *kw_native;
1340 IdentifierInfo *kw_package;
1341 IdentifierInfo *kw_synchronized;
1342 IdentifierInfo *kw_throws;
1344 // Pragma keywords.
1345 IdentifierInfo *kw_mark;
1346 IdentifierInfo *kw_region;
1348 // Proto keywords.
1349 IdentifierInfo *kw_extend;
1350 IdentifierInfo *kw_option;
1351 IdentifierInfo *kw_optional;
1352 IdentifierInfo *kw_repeated;
1353 IdentifierInfo *kw_required;
1354 IdentifierInfo *kw_returns;
1356 // QT keywords.
1357 IdentifierInfo *kw_signals;
1358 IdentifierInfo *kw_qsignals;
1359 IdentifierInfo *kw_slots;
1360 IdentifierInfo *kw_qslots;
1362 // For internal use by clang-format.
1363 IdentifierInfo *kw_internal_ident_after_define;
1365 // C# keywords
1366 IdentifierInfo *kw_dollar;
1367 IdentifierInfo *kw_base;
1368 IdentifierInfo *kw_byte;
1369 IdentifierInfo *kw_checked;
1370 IdentifierInfo *kw_decimal;
1371 IdentifierInfo *kw_delegate;
1372 IdentifierInfo *kw_event;
1373 IdentifierInfo *kw_fixed;
1374 IdentifierInfo *kw_foreach;
1375 IdentifierInfo *kw_implicit;
1376 IdentifierInfo *kw_init;
1377 IdentifierInfo *kw_internal;
1379 IdentifierInfo *kw_lock;
1380 IdentifierInfo *kw_null;
1381 IdentifierInfo *kw_object;
1382 IdentifierInfo *kw_out;
1384 IdentifierInfo *kw_params;
1386 IdentifierInfo *kw_ref;
1387 IdentifierInfo *kw_string;
1388 IdentifierInfo *kw_stackalloc;
1389 IdentifierInfo *kw_sbyte;
1390 IdentifierInfo *kw_sealed;
1391 IdentifierInfo *kw_uint;
1392 IdentifierInfo *kw_ulong;
1393 IdentifierInfo *kw_unchecked;
1394 IdentifierInfo *kw_unsafe;
1395 IdentifierInfo *kw_ushort;
1396 IdentifierInfo *kw_when;
1397 IdentifierInfo *kw_where;
1399 // Verilog keywords
1400 IdentifierInfo *kw_always;
1401 IdentifierInfo *kw_always_comb;
1402 IdentifierInfo *kw_always_ff;
1403 IdentifierInfo *kw_always_latch;
1404 IdentifierInfo *kw_assign;
1405 IdentifierInfo *kw_assume;
1406 IdentifierInfo *kw_automatic;
1407 IdentifierInfo *kw_before;
1408 IdentifierInfo *kw_begin;
1409 IdentifierInfo *kw_begin_keywords;
1410 IdentifierInfo *kw_bins;
1411 IdentifierInfo *kw_binsof;
1412 IdentifierInfo *kw_casex;
1413 IdentifierInfo *kw_casez;
1414 IdentifierInfo *kw_celldefine;
1415 IdentifierInfo *kw_checker;
1416 IdentifierInfo *kw_clocking;
1417 IdentifierInfo *kw_constraint;
1418 IdentifierInfo *kw_cover;
1419 IdentifierInfo *kw_covergroup;
1420 IdentifierInfo *kw_coverpoint;
1421 IdentifierInfo *kw_default_decay_time;
1422 IdentifierInfo *kw_default_nettype;
1423 IdentifierInfo *kw_default_trireg_strength;
1424 IdentifierInfo *kw_delay_mode_distributed;
1425 IdentifierInfo *kw_delay_mode_path;
1426 IdentifierInfo *kw_delay_mode_unit;
1427 IdentifierInfo *kw_delay_mode_zero;
1428 IdentifierInfo *kw_disable;
1429 IdentifierInfo *kw_dist;
1430 IdentifierInfo *kw_elsif;
1431 IdentifierInfo *kw_edge;
1432 IdentifierInfo *kw_end;
1433 IdentifierInfo *kw_end_keywords;
1434 IdentifierInfo *kw_endcase;
1435 IdentifierInfo *kw_endcelldefine;
1436 IdentifierInfo *kw_endchecker;
1437 IdentifierInfo *kw_endclass;
1438 IdentifierInfo *kw_endclocking;
1439 IdentifierInfo *kw_endfunction;
1440 IdentifierInfo *kw_endgenerate;
1441 IdentifierInfo *kw_endgroup;
1442 IdentifierInfo *kw_endinterface;
1443 IdentifierInfo *kw_endmodule;
1444 IdentifierInfo *kw_endpackage;
1445 IdentifierInfo *kw_endprimitive;
1446 IdentifierInfo *kw_endprogram;
1447 IdentifierInfo *kw_endproperty;
1448 IdentifierInfo *kw_endsequence;
1449 IdentifierInfo *kw_endspecify;
1450 IdentifierInfo *kw_endtable;
1451 IdentifierInfo *kw_endtask;
1452 IdentifierInfo *kw_forever;
1453 IdentifierInfo *kw_fork;
1454 IdentifierInfo *kw_generate;
1455 IdentifierInfo *kw_highz0;
1456 IdentifierInfo *kw_highz1;
1457 IdentifierInfo *kw_iff;
1458 IdentifierInfo *kw_ifnone;
1459 IdentifierInfo *kw_ignore_bins;
1460 IdentifierInfo *kw_illegal_bins;
1461 IdentifierInfo *kw_initial;
1462 IdentifierInfo *kw_inout;
1463 IdentifierInfo *kw_input;
1464 IdentifierInfo *kw_inside;
1465 IdentifierInfo *kw_interconnect;
1466 IdentifierInfo *kw_intersect;
1467 IdentifierInfo *kw_join;
1468 IdentifierInfo *kw_join_any;
1469 IdentifierInfo *kw_join_none;
1470 IdentifierInfo *kw_large;
1471 IdentifierInfo *kw_local;
1472 IdentifierInfo *kw_localparam;
1473 IdentifierInfo *kw_macromodule;
1474 IdentifierInfo *kw_matches;
1475 IdentifierInfo *kw_medium;
1476 IdentifierInfo *kw_negedge;
1477 IdentifierInfo *kw_nounconnected_drive;
1478 IdentifierInfo *kw_output;
1479 IdentifierInfo *kw_packed;
1480 IdentifierInfo *kw_parameter;
1481 IdentifierInfo *kw_posedge;
1482 IdentifierInfo *kw_primitive;
1483 IdentifierInfo *kw_priority;
1484 IdentifierInfo *kw_program;
1485 IdentifierInfo *kw_property;
1486 IdentifierInfo *kw_pull0;
1487 IdentifierInfo *kw_pull1;
1488 IdentifierInfo *kw_pure;
1489 IdentifierInfo *kw_rand;
1490 IdentifierInfo *kw_randc;
1491 IdentifierInfo *kw_randcase;
1492 IdentifierInfo *kw_randsequence;
1493 IdentifierInfo *kw_repeat;
1494 IdentifierInfo *kw_resetall;
1495 IdentifierInfo *kw_sample;
1496 IdentifierInfo *kw_scalared;
1497 IdentifierInfo *kw_sequence;
1498 IdentifierInfo *kw_small;
1499 IdentifierInfo *kw_soft;
1500 IdentifierInfo *kw_solve;
1501 IdentifierInfo *kw_specify;
1502 IdentifierInfo *kw_specparam;
1503 IdentifierInfo *kw_strong0;
1504 IdentifierInfo *kw_strong1;
1505 IdentifierInfo *kw_supply0;
1506 IdentifierInfo *kw_supply1;
1507 IdentifierInfo *kw_table;
1508 IdentifierInfo *kw_tagged;
1509 IdentifierInfo *kw_task;
1510 IdentifierInfo *kw_timescale;
1511 IdentifierInfo *kw_tri0;
1512 IdentifierInfo *kw_tri1;
1513 IdentifierInfo *kw_tri;
1514 IdentifierInfo *kw_triand;
1515 IdentifierInfo *kw_trior;
1516 IdentifierInfo *kw_trireg;
1517 IdentifierInfo *kw_unconnected_drive;
1518 IdentifierInfo *kw_undefineall;
1519 IdentifierInfo *kw_unique;
1520 IdentifierInfo *kw_unique0;
1521 IdentifierInfo *kw_uwire;
1522 IdentifierInfo *kw_vectored;
1523 IdentifierInfo *kw_wand;
1524 IdentifierInfo *kw_weak0;
1525 IdentifierInfo *kw_weak1;
1526 IdentifierInfo *kw_wildcard;
1527 IdentifierInfo *kw_wire;
1528 IdentifierInfo *kw_with;
1529 IdentifierInfo *kw_wor;
1531 // Workaround for hashes and backticks in Verilog.
1532 IdentifierInfo *kw_verilogHash;
1533 IdentifierInfo *kw_verilogHashHash;
1535 // Symbols in Verilog that don't exist in C++.
1536 IdentifierInfo *kw_apostrophe;
1538 /// Returns \c true if \p Tok is a keyword or an identifier.
1539 bool isWordLike(const FormatToken &Tok) const {
1540 // getIdentifierinfo returns non-null for keywords as well as identifiers.
1541 return Tok.Tok.getIdentifierInfo() &&
1542 !Tok.isOneOf(kw_verilogHash, kw_verilogHashHash, kw_apostrophe);
1545 /// Returns \c true if \p Tok is a true JavaScript identifier, returns
1546 /// \c false if it is a keyword or a pseudo keyword.
1547 /// If \c AcceptIdentifierName is true, returns true not only for keywords,
1548 // but also for IdentifierName tokens (aka pseudo-keywords), such as
1549 // ``yield``.
1550 bool IsJavaScriptIdentifier(const FormatToken &Tok,
1551 bool AcceptIdentifierName = true) const {
1552 // Based on the list of JavaScript & TypeScript keywords here:
1553 // https://github.com/microsoft/TypeScript/blob/main/src/compiler/scanner.ts#L74
1554 switch (Tok.Tok.getKind()) {
1555 case tok::kw_break:
1556 case tok::kw_case:
1557 case tok::kw_catch:
1558 case tok::kw_class:
1559 case tok::kw_continue:
1560 case tok::kw_const:
1561 case tok::kw_default:
1562 case tok::kw_delete:
1563 case tok::kw_do:
1564 case tok::kw_else:
1565 case tok::kw_enum:
1566 case tok::kw_export:
1567 case tok::kw_false:
1568 case tok::kw_for:
1569 case tok::kw_if:
1570 case tok::kw_import:
1571 case tok::kw_module:
1572 case tok::kw_new:
1573 case tok::kw_private:
1574 case tok::kw_protected:
1575 case tok::kw_public:
1576 case tok::kw_return:
1577 case tok::kw_static:
1578 case tok::kw_switch:
1579 case tok::kw_this:
1580 case tok::kw_throw:
1581 case tok::kw_true:
1582 case tok::kw_try:
1583 case tok::kw_typeof:
1584 case tok::kw_void:
1585 case tok::kw_while:
1586 // These are JS keywords that are lexed by LLVM/clang as keywords.
1587 return false;
1588 case tok::identifier: {
1589 // For identifiers, make sure they are true identifiers, excluding the
1590 // JavaScript pseudo-keywords (not lexed by LLVM/clang as keywords).
1591 bool IsPseudoKeyword =
1592 JsExtraKeywords.find(Tok.Tok.getIdentifierInfo()) !=
1593 JsExtraKeywords.end();
1594 return AcceptIdentifierName || !IsPseudoKeyword;
1596 default:
1597 // Other keywords are handled in the switch below, to avoid problems due
1598 // to duplicate case labels when using the #include trick.
1599 break;
1602 switch (Tok.Tok.getKind()) {
1603 // Handle C++ keywords not included above: these are all JS identifiers.
1604 #define KEYWORD(X, Y) case tok::kw_##X:
1605 #include "clang/Basic/TokenKinds.def"
1606 // #undef KEYWORD is not needed -- it's #undef-ed at the end of
1607 // TokenKinds.def
1608 return true;
1609 default:
1610 // All other tokens (punctuation etc) are not JS identifiers.
1611 return false;
1615 /// Returns \c true if \p Tok is a C# keyword, returns
1616 /// \c false if it is a anything else.
1617 bool isCSharpKeyword(const FormatToken &Tok) const {
1618 switch (Tok.Tok.getKind()) {
1619 case tok::kw_bool:
1620 case tok::kw_break:
1621 case tok::kw_case:
1622 case tok::kw_catch:
1623 case tok::kw_char:
1624 case tok::kw_class:
1625 case tok::kw_const:
1626 case tok::kw_continue:
1627 case tok::kw_default:
1628 case tok::kw_do:
1629 case tok::kw_double:
1630 case tok::kw_else:
1631 case tok::kw_enum:
1632 case tok::kw_explicit:
1633 case tok::kw_extern:
1634 case tok::kw_false:
1635 case tok::kw_float:
1636 case tok::kw_for:
1637 case tok::kw_goto:
1638 case tok::kw_if:
1639 case tok::kw_int:
1640 case tok::kw_long:
1641 case tok::kw_namespace:
1642 case tok::kw_new:
1643 case tok::kw_operator:
1644 case tok::kw_private:
1645 case tok::kw_protected:
1646 case tok::kw_public:
1647 case tok::kw_return:
1648 case tok::kw_short:
1649 case tok::kw_sizeof:
1650 case tok::kw_static:
1651 case tok::kw_struct:
1652 case tok::kw_switch:
1653 case tok::kw_this:
1654 case tok::kw_throw:
1655 case tok::kw_true:
1656 case tok::kw_try:
1657 case tok::kw_typeof:
1658 case tok::kw_using:
1659 case tok::kw_virtual:
1660 case tok::kw_void:
1661 case tok::kw_volatile:
1662 case tok::kw_while:
1663 return true;
1664 default:
1665 return Tok.is(tok::identifier) &&
1666 CSharpExtraKeywords.find(Tok.Tok.getIdentifierInfo()) ==
1667 CSharpExtraKeywords.end();
1671 bool isVerilogWordOperator(const FormatToken &Tok) const {
1672 return Tok.isOneOf(kw_before, kw_intersect, kw_dist, kw_iff, kw_inside,
1673 kw_with);
1676 bool isVerilogIdentifier(const FormatToken &Tok) const {
1677 switch (Tok.Tok.getKind()) {
1678 case tok::kw_case:
1679 case tok::kw_class:
1680 case tok::kw_const:
1681 case tok::kw_continue:
1682 case tok::kw_default:
1683 case tok::kw_do:
1684 case tok::kw_extern:
1685 case tok::kw_else:
1686 case tok::kw_enum:
1687 case tok::kw_for:
1688 case tok::kw_if:
1689 case tok::kw_restrict:
1690 case tok::kw_signed:
1691 case tok::kw_static:
1692 case tok::kw_struct:
1693 case tok::kw_typedef:
1694 case tok::kw_union:
1695 case tok::kw_unsigned:
1696 case tok::kw_virtual:
1697 case tok::kw_while:
1698 return false;
1699 case tok::identifier:
1700 return isWordLike(Tok) &&
1701 VerilogExtraKeywords.find(Tok.Tok.getIdentifierInfo()) ==
1702 VerilogExtraKeywords.end();
1703 default:
1704 // getIdentifierInfo returns non-null for both identifiers and keywords.
1705 return Tok.Tok.getIdentifierInfo();
1709 /// Returns whether \p Tok is a Verilog preprocessor directive. This is
1710 /// needed because macro expansions start with a backtick as well and they
1711 /// need to be treated differently.
1712 bool isVerilogPPDirective(const FormatToken &Tok) const {
1713 auto Info = Tok.Tok.getIdentifierInfo();
1714 if (!Info)
1715 return false;
1716 switch (Info->getPPKeywordID()) {
1717 case tok::pp_define:
1718 case tok::pp_else:
1719 case tok::pp_endif:
1720 case tok::pp_ifdef:
1721 case tok::pp_ifndef:
1722 case tok::pp_include:
1723 case tok::pp_line:
1724 case tok::pp_pragma:
1725 case tok::pp_undef:
1726 return true;
1727 default:
1728 return Tok.isOneOf(kw_begin_keywords, kw_celldefine,
1729 kw_default_decay_time, kw_default_nettype,
1730 kw_default_trireg_strength, kw_delay_mode_distributed,
1731 kw_delay_mode_path, kw_delay_mode_unit,
1732 kw_delay_mode_zero, kw_elsif, kw_end_keywords,
1733 kw_endcelldefine, kw_nounconnected_drive, kw_resetall,
1734 kw_timescale, kw_unconnected_drive, kw_undefineall);
1738 /// Returns whether \p Tok is a Verilog keyword that opens a block.
1739 bool isVerilogBegin(const FormatToken &Tok) const {
1740 // `table` is not included since it needs to be treated specially.
1741 return !Tok.endsSequence(kw_fork, kw_disable) &&
1742 Tok.isOneOf(kw_begin, kw_fork, kw_generate, kw_specify);
1745 /// Returns whether \p Tok is a Verilog keyword that closes a block.
1746 bool isVerilogEnd(const FormatToken &Tok) const {
1747 return !Tok.endsSequence(kw_join, kw_rand) &&
1748 Tok.isOneOf(TT_MacroBlockEnd, kw_end, kw_endcase, kw_endclass,
1749 kw_endclocking, kw_endchecker, kw_endfunction,
1750 kw_endgenerate, kw_endgroup, kw_endinterface,
1751 kw_endmodule, kw_endpackage, kw_endprimitive,
1752 kw_endprogram, kw_endproperty, kw_endsequence,
1753 kw_endspecify, kw_endtable, kw_endtask, kw_join,
1754 kw_join_any, kw_join_none);
1757 /// Returns whether \p Tok is a Verilog keyword that opens a module, etc.
1758 bool isVerilogHierarchy(const FormatToken &Tok) const {
1759 if (Tok.endsSequence(kw_function, kw_with))
1760 return false;
1761 if (Tok.is(kw_property)) {
1762 const FormatToken *Prev = Tok.getPreviousNonComment();
1763 return !(Prev &&
1764 Prev->isOneOf(tok::kw_restrict, kw_assert, kw_assume, kw_cover));
1766 return Tok.isOneOf(tok::kw_case, tok::kw_class, kw_function, kw_module,
1767 kw_interface, kw_package, kw_casex, kw_casez, kw_checker,
1768 kw_clocking, kw_covergroup, kw_macromodule, kw_primitive,
1769 kw_program, kw_property, kw_randcase, kw_randsequence,
1770 kw_task);
1773 bool isVerilogEndOfLabel(const FormatToken &Tok) const {
1774 const FormatToken *Next = Tok.getNextNonComment();
1775 // In Verilog the colon in a default label is optional.
1776 return Tok.is(TT_CaseLabelColon) ||
1777 (Tok.is(tok::kw_default) &&
1778 !(Next && Next->isOneOf(tok::colon, tok::semi, kw_clocking, kw_iff,
1779 kw_input, kw_output, kw_sequence)));
1782 /// Returns whether \p Tok is a Verilog keyword that starts a
1783 /// structured procedure like 'always'.
1784 bool isVerilogStructuredProcedure(const FormatToken &Tok) const {
1785 return Tok.isOneOf(kw_always, kw_always_comb, kw_always_ff, kw_always_latch,
1786 kw_final, kw_forever, kw_initial);
1789 bool isVerilogQualifier(const FormatToken &Tok) const {
1790 switch (Tok.Tok.getKind()) {
1791 case tok::kw_extern:
1792 case tok::kw_signed:
1793 case tok::kw_static:
1794 case tok::kw_unsigned:
1795 case tok::kw_virtual:
1796 return true;
1797 case tok::identifier:
1798 return Tok.isOneOf(
1799 kw_let, kw_var, kw_ref, kw_automatic, kw_bins, kw_coverpoint,
1800 kw_ignore_bins, kw_illegal_bins, kw_inout, kw_input, kw_interconnect,
1801 kw_local, kw_localparam, kw_output, kw_parameter, kw_pure, kw_rand,
1802 kw_randc, kw_scalared, kw_specparam, kw_tri, kw_tri0, kw_tri1,
1803 kw_triand, kw_trior, kw_trireg, kw_uwire, kw_vectored, kw_wand,
1804 kw_wildcard, kw_wire, kw_wor);
1805 default:
1806 return false;
1810 private:
1811 /// The JavaScript keywords beyond the C++ keyword set.
1812 std::unordered_set<IdentifierInfo *> JsExtraKeywords;
1814 /// The C# keywords beyond the C++ keyword set
1815 std::unordered_set<IdentifierInfo *> CSharpExtraKeywords;
1817 /// The Verilog keywords beyond the C++ keyword set.
1818 std::unordered_set<IdentifierInfo *> VerilogExtraKeywords;
1821 inline bool isLineComment(const FormatToken &FormatTok) {
1822 return FormatTok.is(tok::comment) && !FormatTok.TokenText.startswith("/*");
1825 // Checks if \p FormatTok is a line comment that continues the line comment
1826 // \p Previous. The original column of \p MinColumnToken is used to determine
1827 // whether \p FormatTok is indented enough to the right to continue \p Previous.
1828 inline bool continuesLineComment(const FormatToken &FormatTok,
1829 const FormatToken *Previous,
1830 const FormatToken *MinColumnToken) {
1831 if (!Previous || !MinColumnToken)
1832 return false;
1833 unsigned MinContinueColumn =
1834 MinColumnToken->OriginalColumn + (isLineComment(*MinColumnToken) ? 0 : 1);
1835 return isLineComment(FormatTok) && FormatTok.NewlinesBefore == 1 &&
1836 isLineComment(*Previous) &&
1837 FormatTok.OriginalColumn >= MinContinueColumn;
1840 } // namespace format
1841 } // namespace clang
1843 #endif