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