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