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