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