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