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