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