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

source code of clang/lib/Format/FormatToken.h