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