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(CastRParen) \ 39 TYPE(ConditionalExpr) \ 40 TYPE(ConflictAlternative) \ 41 TYPE(ConflictEnd) \ 42 TYPE(ConflictStart) \ 43 TYPE(ConstraintJunctions) \ 44 TYPE(CtorInitializerColon) \ 45 TYPE(CtorInitializerComma) \ 46 TYPE(DesignatedInitializerLSquare) \ 47 TYPE(DesignatedInitializerPeriod) \ 48 TYPE(DictLiteral) \ 49 TYPE(FatArrow) \ 50 TYPE(ForEachMacro) \ 51 TYPE(FunctionAnnotationRParen) \ 52 TYPE(FunctionDeclarationName) \ 53 TYPE(FunctionLBrace) \ 54 TYPE(FunctionLikeOrFreestandingMacro) \ 55 TYPE(FunctionTypeLParen) \ 56 TYPE(IfMacro) \ 57 TYPE(ImplicitStringLiteral) \ 58 TYPE(InheritanceColon) \ 59 TYPE(InheritanceComma) \ 60 TYPE(InlineASMBrace) \ 61 TYPE(InlineASMColon) \ 62 TYPE(InlineASMSymbolicNameLSquare) \ 63 TYPE(JavaAnnotation) \ 64 TYPE(JsComputedPropertyName) \ 65 TYPE(JsExponentiation) \ 66 TYPE(JsExponentiationEqual) \ 67 TYPE(JsPipePipeEqual) \ 68 TYPE(JsPrivateIdentifier) \ 69 TYPE(JsTypeColon) \ 70 TYPE(JsTypeOperator) \ 71 TYPE(JsTypeOptionalQuestion) \ 72 TYPE(JsAndAndEqual) \ 73 TYPE(LambdaArrow) \ 74 TYPE(LambdaLBrace) \ 75 TYPE(LambdaLSquare) \ 76 TYPE(LeadingJavaAnnotation) \ 77 TYPE(LineComment) \ 78 TYPE(MacroBlockBegin) \ 79 TYPE(MacroBlockEnd) \ 80 TYPE(ModulePartitionColon) \ 81 TYPE(NamespaceMacro) \ 82 TYPE(NonNullAssertion) \ 83 TYPE(NullCoalescingEqual) \ 84 TYPE(NullCoalescingOperator) \ 85 TYPE(NullPropagatingOperator) \ 86 TYPE(ObjCBlockLBrace) \ 87 TYPE(ObjCBlockLParen) \ 88 TYPE(ObjCDecl) \ 89 TYPE(ObjCForIn) \ 90 TYPE(ObjCMethodExpr) \ 91 TYPE(ObjCMethodSpecifier) \ 92 TYPE(ObjCProperty) \ 93 TYPE(ObjCStringLiteral) \ 94 TYPE(OverloadedOperator) \ 95 TYPE(OverloadedOperatorLParen) \ 96 TYPE(PointerOrReference) \ 97 TYPE(PureVirtualSpecifier) \ 98 TYPE(RangeBasedForLoopColon) \ 99 TYPE(RegexLiteral) \ 100 TYPE(SelectorName) \ 101 TYPE(StartOfName) \ 102 TYPE(StatementAttributeLikeMacro) \ 103 TYPE(StatementMacro) \ 104 TYPE(StructuredBindingLSquare) \ 105 TYPE(TemplateCloser) \ 106 TYPE(TemplateOpener) \ 107 TYPE(TemplateString) \ 108 TYPE(ProtoExtensionLSquare) \ 109 TYPE(TrailingAnnotation) \ 110 TYPE(TrailingReturnArrow) \ 111 TYPE(TrailingUnaryOperator) \ 112 TYPE(TypeDeclarationParen) \ 113 TYPE(TypenameMacro) \ 114 TYPE(UnaryOperator) \ 115 TYPE(UntouchableMacroFunc) \ 116 TYPE(CSharpStringLiteral) \ 117 TYPE(CSharpNamedArgumentColon) \ 118 TYPE(CSharpNullable) \ 119 TYPE(CSharpNullConditionalLSquare) \ 120 TYPE(CSharpGenericTypeConstraint) \ 121 TYPE(CSharpGenericTypeConstraintColon) \ 122 TYPE(CSharpGenericTypeConstraintComma) \ 123 TYPE(Unknown) 124 125 /// Determines the semantic type of a syntactic token, e.g. whether "<" is a 126 /// template opener or binary operator. 127 enum TokenType : uint8_t { 128 #define TYPE(X) TT_##X, 129 LIST_TOKEN_TYPES 130 #undef TYPE 131 NUM_TOKEN_TYPES 132 }; 133 134 /// Determines the name of a token type. 135 const char *getTokenTypeName(TokenType Type); 136 137 // Represents what type of block a set of braces open. 138 enum BraceBlockKind { BK_Unknown, BK_Block, BK_BracedInit }; 139 140 // The packing kind of a function's parameters. 141 enum ParameterPackingKind { PPK_BinPacked, PPK_OnePerLine, PPK_Inconclusive }; 142 143 enum FormatDecision { FD_Unformatted, FD_Continue, FD_Break }; 144 145 /// Roles a token can take in a configured macro expansion. 146 enum MacroRole { 147 /// The token was expanded from a macro argument when formatting the expanded 148 /// token sequence. 149 MR_ExpandedArg, 150 /// The token is part of a macro argument that was previously formatted as 151 /// expansion when formatting the unexpanded macro call. 152 MR_UnexpandedArg, 153 /// The token was expanded from a macro definition, and is not visible as part 154 /// of the macro call. 155 MR_Hidden, 156 }; 157 158 struct FormatToken; 159 160 /// Contains information on the token's role in a macro expansion. 161 /// 162 /// Given the following definitions: 163 /// A(X) = [ X ] 164 /// B(X) = < X > 165 /// C(X) = X 166 /// 167 /// Consider the macro call: 168 /// A({B(C(C(x)))}) -> [{<x>}] 169 /// 170 /// In this case, the tokens of the unexpanded macro call will have the 171 /// following relevant entries in their macro context (note that formatting 172 /// the unexpanded macro call happens *after* formatting the expanded macro 173 /// call): 174 /// A( { B( C( C(x) ) ) } ) 175 /// Role: NN U NN NN NNUN N N U N (N=None, U=UnexpandedArg) 176 /// 177 /// [ { < x > } ] 178 /// Role: H E H E H E H (H=Hidden, E=ExpandedArg) 179 /// ExpandedFrom[0]: A A A A A A A 180 /// ExpandedFrom[1]: B B B 181 /// ExpandedFrom[2]: C 182 /// ExpandedFrom[3]: C 183 /// StartOfExpansion: 1 0 1 2 0 0 0 184 /// EndOfExpansion: 0 0 0 2 1 0 1 185 struct MacroExpansion { 186 MacroExpansion(MacroRole Role) : Role(Role) {} 187 188 /// The token's role in the macro expansion. 189 /// When formatting an expanded macro, all tokens that are part of macro 190 /// arguments will be MR_ExpandedArg, while all tokens that are not visible in 191 /// the macro call will be MR_Hidden. 192 /// When formatting an unexpanded macro call, all tokens that are part of 193 /// macro arguments will be MR_UnexpandedArg. 194 MacroRole Role; 195 196 /// The stack of macro call identifier tokens this token was expanded from. 197 llvm::SmallVector<FormatToken *, 1> ExpandedFrom; 198 199 /// The number of expansions of which this macro is the first entry. 200 unsigned StartOfExpansion = 0; 201 202 /// The number of currently open expansions in \c ExpandedFrom this macro is 203 /// the last token in. 204 unsigned EndOfExpansion = 0; 205 }; 206 207 class TokenRole; 208 class AnnotatedLine; 209 210 /// A wrapper around a \c Token storing information about the 211 /// whitespace characters preceding it. 212 struct FormatToken { 213 FormatToken() 214 : HasUnescapedNewline(false), IsMultiline(false), IsFirst(false), 215 MustBreakBefore(false), IsUnterminatedLiteral(false), 216 CanBreakBefore(false), ClosesTemplateDeclaration(false), 217 StartsBinaryExpression(false), EndsBinaryExpression(false), 218 PartOfMultiVariableDeclStmt(false), ContinuesLineCommentSection(false), 219 Finalized(false), BlockKind(BK_Unknown), Decision(FD_Unformatted), 220 PackingKind(PPK_Inconclusive), Type(TT_Unknown) {} 221 222 /// The \c Token. 223 Token Tok; 224 225 /// The raw text of the token. 226 /// 227 /// Contains the raw token text without leading whitespace and without leading 228 /// escaped newlines. 229 StringRef TokenText; 230 231 /// A token can have a special role that can carry extra information 232 /// about the token's formatting. 233 /// FIXME: Make FormatToken for parsing and AnnotatedToken two different 234 /// classes and make this a unique_ptr in the AnnotatedToken class. 235 std::shared_ptr<TokenRole> Role; 236 237 /// The range of the whitespace immediately preceding the \c Token. 238 SourceRange WhitespaceRange; 239 240 /// Whether there is at least one unescaped newline before the \c 241 /// Token. 242 unsigned HasUnescapedNewline : 1; 243 244 /// Whether the token text contains newlines (escaped or not). 245 unsigned IsMultiline : 1; 246 247 /// Indicates that this is the first token of the file. 248 unsigned IsFirst : 1; 249 250 /// Whether there must be a line break before this token. 251 /// 252 /// This happens for example when a preprocessor directive ended directly 253 /// before the token. 254 unsigned MustBreakBefore : 1; 255 256 /// Set to \c true if this token is an unterminated literal. 257 unsigned IsUnterminatedLiteral : 1; 258 259 /// \c true if it is allowed to break before this token. 260 unsigned CanBreakBefore : 1; 261 262 /// \c true if this is the ">" of "template<..>". 263 unsigned ClosesTemplateDeclaration : 1; 264 265 /// \c true if this token starts a binary expression, i.e. has at least 266 /// one fake l_paren with a precedence greater than prec::Unknown. 267 unsigned StartsBinaryExpression : 1; 268 /// \c true if this token ends a binary expression. 269 unsigned EndsBinaryExpression : 1; 270 271 /// Is this token part of a \c DeclStmt defining multiple variables? 272 /// 273 /// Only set if \c Type == \c TT_StartOfName. 274 unsigned PartOfMultiVariableDeclStmt : 1; 275 276 /// Does this line comment continue a line comment section? 277 /// 278 /// Only set to true if \c Type == \c TT_LineComment. 279 unsigned ContinuesLineCommentSection : 1; 280 281 /// If \c true, this token has been fully formatted (indented and 282 /// potentially re-formatted inside), and we do not allow further formatting 283 /// changes. 284 unsigned Finalized : 1; 285 286 private: 287 /// Contains the kind of block if this token is a brace. 288 unsigned BlockKind : 2; 289 290 public: 291 BraceBlockKind getBlockKind() const { 292 return static_cast<BraceBlockKind>(BlockKind); 293 } 294 void setBlockKind(BraceBlockKind BBK) { 295 BlockKind = BBK; 296 assert(getBlockKind() == BBK && "BraceBlockKind overflow!"); 297 } 298 299 private: 300 /// Stores the formatting decision for the token once it was made. 301 unsigned Decision : 2; 302 303 public: 304 FormatDecision getDecision() const { 305 return static_cast<FormatDecision>(Decision); 306 } 307 void setDecision(FormatDecision D) { 308 Decision = D; 309 assert(getDecision() == D && "FormatDecision overflow!"); 310 } 311 312 private: 313 /// If this is an opening parenthesis, how are the parameters packed? 314 unsigned PackingKind : 2; 315 316 public: 317 ParameterPackingKind getPackingKind() const { 318 return static_cast<ParameterPackingKind>(PackingKind); 319 } 320 void setPackingKind(ParameterPackingKind K) { 321 PackingKind = K; 322 assert(getPackingKind() == K && "ParameterPackingKind overflow!"); 323 } 324 325 private: 326 TokenType Type; 327 328 public: 329 /// Returns the token's type, e.g. whether "<" is a template opener or 330 /// binary operator. 331 TokenType getType() const { return Type; } 332 void setType(TokenType T) { Type = T; } 333 334 /// The number of newlines immediately before the \c Token. 335 /// 336 /// This can be used to determine what the user wrote in the original code 337 /// and thereby e.g. leave an empty line between two function definitions. 338 unsigned NewlinesBefore = 0; 339 340 /// The offset just past the last '\n' in this token's leading 341 /// whitespace (relative to \c WhiteSpaceStart). 0 if there is no '\n'. 342 unsigned LastNewlineOffset = 0; 343 344 /// The width of the non-whitespace parts of the token (or its first 345 /// line for multi-line tokens) in columns. 346 /// We need this to correctly measure number of columns a token spans. 347 unsigned ColumnWidth = 0; 348 349 /// Contains the width in columns of the last line of a multi-line 350 /// token. 351 unsigned LastLineColumnWidth = 0; 352 353 /// The number of spaces that should be inserted before this token. 354 unsigned SpacesRequiredBefore = 0; 355 356 /// Number of parameters, if this is "(", "[" or "<". 357 unsigned ParameterCount = 0; 358 359 /// Number of parameters that are nested blocks, 360 /// if this is "(", "[" or "<". 361 unsigned BlockParameterCount = 0; 362 363 /// If this is a bracket ("<", "(", "[" or "{"), contains the kind of 364 /// the surrounding bracket. 365 tok::TokenKind ParentBracket = tok::unknown; 366 367 /// The total length of the unwrapped line up to and including this 368 /// token. 369 unsigned TotalLength = 0; 370 371 /// The original 0-based column of this token, including expanded tabs. 372 /// The configured TabWidth is used as tab width. 373 unsigned OriginalColumn = 0; 374 375 /// The length of following tokens until the next natural split point, 376 /// or the next token that can be broken. 377 unsigned UnbreakableTailLength = 0; 378 379 // FIXME: Come up with a 'cleaner' concept. 380 /// The binding strength of a token. This is a combined value of 381 /// operator precedence, parenthesis nesting, etc. 382 unsigned BindingStrength = 0; 383 384 /// The nesting level of this token, i.e. the number of surrounding (), 385 /// [], {} or <>. 386 unsigned NestingLevel = 0; 387 388 /// The indent level of this token. Copied from the surrounding line. 389 unsigned IndentLevel = 0; 390 391 /// Penalty for inserting a line break before this token. 392 unsigned SplitPenalty = 0; 393 394 /// If this is the first ObjC selector name in an ObjC method 395 /// definition or call, this contains the length of the longest name. 396 /// 397 /// This being set to 0 means that the selectors should not be colon-aligned, 398 /// e.g. because several of them are block-type. 399 unsigned LongestObjCSelectorName = 0; 400 401 /// If this is the first ObjC selector name in an ObjC method 402 /// definition or call, this contains the number of parts that the whole 403 /// selector consist of. 404 unsigned ObjCSelectorNameParts = 0; 405 406 /// The 0-based index of the parameter/argument. For ObjC it is set 407 /// for the selector name token. 408 /// For now calculated only for ObjC. 409 unsigned ParameterIndex = 0; 410 411 /// Stores the number of required fake parentheses and the 412 /// corresponding operator precedence. 413 /// 414 /// If multiple fake parentheses start at a token, this vector stores them in 415 /// reverse order, i.e. inner fake parenthesis first. 416 SmallVector<prec::Level, 4> FakeLParens; 417 /// Insert this many fake ) after this token for correct indentation. 418 unsigned FakeRParens = 0; 419 420 /// If this is an operator (or "."/"->") in a sequence of operators 421 /// with the same precedence, contains the 0-based operator index. 422 unsigned OperatorIndex = 0; 423 424 /// If this is an operator (or "."/"->") in a sequence of operators 425 /// with the same precedence, points to the next operator. 426 FormatToken *NextOperator = nullptr; 427 428 /// If this is a bracket, this points to the matching one. 429 FormatToken *MatchingParen = nullptr; 430 431 /// The previous token in the unwrapped line. 432 FormatToken *Previous = nullptr; 433 434 /// The next token in the unwrapped line. 435 FormatToken *Next = nullptr; 436 437 /// The first token in set of column elements. 438 bool StartsColumn = false; 439 440 /// This notes the start of the line of an array initializer. 441 bool ArrayInitializerLineStart = false; 442 443 /// This starts an array initializer. 444 bool IsArrayInitializer = false; 445 446 /// Is optional and can be removed. 447 bool Optional = false; 448 449 /// If this token starts a block, this contains all the unwrapped lines 450 /// in it. 451 SmallVector<AnnotatedLine *, 1> Children; 452 453 // Contains all attributes related to how this token takes part 454 // in a configured macro expansion. 455 llvm::Optional<MacroExpansion> MacroCtx; 456 457 bool is(tok::TokenKind Kind) const { return Tok.is(Kind); } 458 bool is(TokenType TT) const { return getType() == TT; } 459 bool is(const IdentifierInfo *II) const { 460 return II && II == Tok.getIdentifierInfo(); 461 } 462 bool is(tok::PPKeywordKind Kind) const { 463 return Tok.getIdentifierInfo() && 464 Tok.getIdentifierInfo()->getPPKeywordID() == Kind; 465 } 466 bool is(BraceBlockKind BBK) const { return getBlockKind() == BBK; } 467 bool is(ParameterPackingKind PPK) const { return getPackingKind() == PPK; } 468 469 template <typename A, typename B> bool isOneOf(A K1, B K2) const { 470 return is(K1) || is(K2); 471 } 472 template <typename A, typename B, typename... Ts> 473 bool isOneOf(A K1, B K2, Ts... Ks) const { 474 return is(K1) || isOneOf(K2, Ks...); 475 } 476 template <typename T> bool isNot(T Kind) const { return !is(Kind); } 477 478 bool isIf(bool AllowConstexprMacro = true) const { 479 return is(tok::kw_if) || endsSequence(tok::kw_constexpr, tok::kw_if) || 480 (endsSequence(tok::identifier, tok::kw_if) && AllowConstexprMacro); 481 } 482 483 bool closesScopeAfterBlock() const { 484 if (getBlockKind() == BK_Block) 485 return true; 486 if (closesScope()) 487 return Previous->closesScopeAfterBlock(); 488 return false; 489 } 490 491 /// \c true if this token starts a sequence with the given tokens in order, 492 /// following the ``Next`` pointers, ignoring comments. 493 template <typename A, typename... Ts> 494 bool startsSequence(A K1, Ts... Tokens) const { 495 return startsSequenceInternal(K1, Tokens...); 496 } 497 498 /// \c true if this token ends a sequence with the given tokens in order, 499 /// following the ``Previous`` pointers, ignoring comments. 500 /// For example, given tokens [T1, T2, T3], the function returns true if 501 /// 3 tokens ending at this (ignoring comments) are [T3, T2, T1]. In other 502 /// words, the tokens passed to this function need to the reverse of the 503 /// order the tokens appear in code. 504 template <typename A, typename... Ts> 505 bool endsSequence(A K1, Ts... Tokens) const { 506 return endsSequenceInternal(K1, Tokens...); 507 } 508 509 bool isStringLiteral() const { return tok::isStringLiteral(Tok.getKind()); } 510 511 bool isObjCAtKeyword(tok::ObjCKeywordKind Kind) const { 512 return Tok.isObjCAtKeyword(Kind); 513 } 514 515 bool isAccessSpecifier(bool ColonRequired = true) const { 516 return isOneOf(tok::kw_public, tok::kw_protected, tok::kw_private) && 517 (!ColonRequired || (Next && Next->is(tok::colon))); 518 } 519 520 bool canBePointerOrReferenceQualifier() const { 521 return isOneOf(tok::kw_const, tok::kw_restrict, tok::kw_volatile, 522 tok::kw___attribute, tok::kw__Nonnull, tok::kw__Nullable, 523 tok::kw__Null_unspecified, tok::kw___ptr32, tok::kw___ptr64, 524 TT_AttributeMacro); 525 } 526 527 /// Determine whether the token is a simple-type-specifier. 528 LLVM_NODISCARD bool isSimpleTypeSpecifier() const; 529 530 LLVM_NODISCARD bool isTypeOrIdentifier() const; 531 532 bool isObjCAccessSpecifier() const { 533 return is(tok::at) && Next && 534 (Next->isObjCAtKeyword(tok::objc_public) || 535 Next->isObjCAtKeyword(tok::objc_protected) || 536 Next->isObjCAtKeyword(tok::objc_package) || 537 Next->isObjCAtKeyword(tok::objc_private)); 538 } 539 540 /// Returns whether \p Tok is ([{ or an opening < of a template or in 541 /// protos. 542 bool opensScope() const { 543 if (is(TT_TemplateString) && TokenText.endswith("${")) 544 return true; 545 if (is(TT_DictLiteral) && is(tok::less)) 546 return true; 547 return isOneOf(tok::l_paren, tok::l_brace, tok::l_square, 548 TT_TemplateOpener); 549 } 550 /// Returns whether \p Tok is )]} or a closing > of a template or in 551 /// protos. 552 bool closesScope() const { 553 if (is(TT_TemplateString) && TokenText.startswith("}")) 554 return true; 555 if (is(TT_DictLiteral) && is(tok::greater)) 556 return true; 557 return isOneOf(tok::r_paren, tok::r_brace, tok::r_square, 558 TT_TemplateCloser); 559 } 560 561 /// Returns \c true if this is a "." or "->" accessing a member. 562 bool isMemberAccess() const { 563 return isOneOf(tok::arrow, tok::period, tok::arrowstar) && 564 !isOneOf(TT_DesignatedInitializerPeriod, TT_TrailingReturnArrow, 565 TT_LambdaArrow, TT_LeadingJavaAnnotation); 566 } 567 568 bool isUnaryOperator() const { 569 switch (Tok.getKind()) { 570 case tok::plus: 571 case tok::plusplus: 572 case tok::minus: 573 case tok::minusminus: 574 case tok::exclaim: 575 case tok::tilde: 576 case tok::kw_sizeof: 577 case tok::kw_alignof: 578 return true; 579 default: 580 return false; 581 } 582 } 583 584 bool isBinaryOperator() const { 585 // Comma is a binary operator, but does not behave as such wrt. formatting. 586 return getPrecedence() > prec::Comma; 587 } 588 589 bool isTrailingComment() const { 590 return is(tok::comment) && 591 (is(TT_LineComment) || !Next || Next->NewlinesBefore > 0); 592 } 593 594 /// Returns \c true if this is a keyword that can be used 595 /// like a function call (e.g. sizeof, typeid, ...). 596 bool isFunctionLikeKeyword() const { 597 switch (Tok.getKind()) { 598 case tok::kw_throw: 599 case tok::kw_typeid: 600 case tok::kw_return: 601 case tok::kw_sizeof: 602 case tok::kw_alignof: 603 case tok::kw_alignas: 604 case tok::kw_decltype: 605 case tok::kw_noexcept: 606 case tok::kw_static_assert: 607 case tok::kw__Atomic: 608 case tok::kw___attribute: 609 case tok::kw___underlying_type: 610 case tok::kw_requires: 611 return true; 612 default: 613 return false; 614 } 615 } 616 617 /// Returns \c true if this is a string literal that's like a label, 618 /// e.g. ends with "=" or ":". 619 bool isLabelString() const { 620 if (!is(tok::string_literal)) 621 return false; 622 StringRef Content = TokenText; 623 if (Content.startswith("\"") || Content.startswith("'")) 624 Content = Content.drop_front(1); 625 if (Content.endswith("\"") || Content.endswith("'")) 626 Content = Content.drop_back(1); 627 Content = Content.trim(); 628 return Content.size() > 1 && 629 (Content.back() == ':' || Content.back() == '='); 630 } 631 632 /// Returns actual token start location without leading escaped 633 /// newlines and whitespace. 634 /// 635 /// This can be different to Tok.getLocation(), which includes leading escaped 636 /// newlines. 637 SourceLocation getStartOfNonWhitespace() const { 638 return WhitespaceRange.getEnd(); 639 } 640 641 /// Returns \c true if the range of whitespace immediately preceding the \c 642 /// Token is not empty. 643 bool hasWhitespaceBefore() const { 644 return WhitespaceRange.getBegin() != WhitespaceRange.getEnd(); 645 } 646 647 prec::Level getPrecedence() const { 648 return getBinOpPrecedence(Tok.getKind(), /*GreaterThanIsOperator=*/true, 649 /*CPlusPlus11=*/true); 650 } 651 652 /// Returns the previous token ignoring comments. 653 FormatToken *getPreviousNonComment() const { 654 FormatToken *Tok = Previous; 655 while (Tok && Tok->is(tok::comment)) 656 Tok = Tok->Previous; 657 return Tok; 658 } 659 660 /// Returns the next token ignoring comments. 661 const FormatToken *getNextNonComment() const { 662 const FormatToken *Tok = Next; 663 while (Tok && Tok->is(tok::comment)) 664 Tok = Tok->Next; 665 return Tok; 666 } 667 668 /// Returns \c true if this tokens starts a block-type list, i.e. a 669 /// list that should be indented with a block indent. 670 bool opensBlockOrBlockTypeList(const FormatStyle &Style) const { 671 // C# Does not indent object initialisers as continuations. 672 if (is(tok::l_brace) && getBlockKind() == BK_BracedInit && Style.isCSharp()) 673 return true; 674 if (is(TT_TemplateString) && opensScope()) 675 return true; 676 return is(TT_ArrayInitializerLSquare) || is(TT_ProtoExtensionLSquare) || 677 (is(tok::l_brace) && 678 (getBlockKind() == BK_Block || is(TT_DictLiteral) || 679 (!Style.Cpp11BracedListStyle && NestingLevel == 0))) || 680 (is(tok::less) && (Style.Language == FormatStyle::LK_Proto || 681 Style.Language == FormatStyle::LK_TextProto)); 682 } 683 684 /// Returns whether the token is the left square bracket of a C++ 685 /// structured binding declaration. 686 bool isCppStructuredBinding(const FormatStyle &Style) const { 687 if (!Style.isCpp() || isNot(tok::l_square)) 688 return false; 689 const FormatToken *T = this; 690 do { 691 T = T->getPreviousNonComment(); 692 } while (T && T->isOneOf(tok::kw_const, tok::kw_volatile, tok::amp, 693 tok::ampamp)); 694 return T && T->is(tok::kw_auto); 695 } 696 697 /// Same as opensBlockOrBlockTypeList, but for the closing token. 698 bool closesBlockOrBlockTypeList(const FormatStyle &Style) const { 699 if (is(TT_TemplateString) && closesScope()) 700 return true; 701 return MatchingParen && MatchingParen->opensBlockOrBlockTypeList(Style); 702 } 703 704 /// Return the actual namespace token, if this token starts a namespace 705 /// block. 706 const FormatToken *getNamespaceToken() const { 707 const FormatToken *NamespaceTok = this; 708 if (is(tok::comment)) 709 NamespaceTok = NamespaceTok->getNextNonComment(); 710 // Detect "(inline|export)? namespace" in the beginning of a line. 711 if (NamespaceTok && NamespaceTok->isOneOf(tok::kw_inline, tok::kw_export)) 712 NamespaceTok = NamespaceTok->getNextNonComment(); 713 return NamespaceTok && 714 NamespaceTok->isOneOf(tok::kw_namespace, TT_NamespaceMacro) 715 ? NamespaceTok 716 : nullptr; 717 } 718 719 void copyFrom(const FormatToken &Tok) { *this = Tok; } 720 721 private: 722 // Only allow copying via the explicit copyFrom method. 723 FormatToken(const FormatToken &) = delete; 724 FormatToken &operator=(const FormatToken &) = default; 725 726 template <typename A, typename... Ts> 727 bool startsSequenceInternal(A K1, Ts... Tokens) const { 728 if (is(tok::comment) && Next) 729 return Next->startsSequenceInternal(K1, Tokens...); 730 return is(K1) && Next && Next->startsSequenceInternal(Tokens...); 731 } 732 733 template <typename A> bool startsSequenceInternal(A K1) const { 734 if (is(tok::comment) && Next) 735 return Next->startsSequenceInternal(K1); 736 return is(K1); 737 } 738 739 template <typename A, typename... Ts> bool endsSequenceInternal(A K1) const { 740 if (is(tok::comment) && Previous) 741 return Previous->endsSequenceInternal(K1); 742 return is(K1); 743 } 744 745 template <typename A, typename... Ts> 746 bool endsSequenceInternal(A K1, Ts... Tokens) const { 747 if (is(tok::comment) && Previous) 748 return Previous->endsSequenceInternal(K1, Tokens...); 749 return is(K1) && Previous && Previous->endsSequenceInternal(Tokens...); 750 } 751 }; 752 753 class ContinuationIndenter; 754 struct LineState; 755 756 class TokenRole { 757 public: 758 TokenRole(const FormatStyle &Style) : Style(Style) {} 759 virtual ~TokenRole(); 760 761 /// After the \c TokenAnnotator has finished annotating all the tokens, 762 /// this function precomputes required information for formatting. 763 virtual void precomputeFormattingInfos(const FormatToken *Token); 764 765 /// Apply the special formatting that the given role demands. 766 /// 767 /// Assumes that the token having this role is already formatted. 768 /// 769 /// Continues formatting from \p State leaving indentation to \p Indenter and 770 /// returns the total penalty that this formatting incurs. 771 virtual unsigned formatFromToken(LineState &State, 772 ContinuationIndenter *Indenter, 773 bool DryRun) { 774 return 0; 775 } 776 777 /// Same as \c formatFromToken, but assumes that the first token has 778 /// already been set thereby deciding on the first line break. 779 virtual unsigned formatAfterToken(LineState &State, 780 ContinuationIndenter *Indenter, 781 bool DryRun) { 782 return 0; 783 } 784 785 /// Notifies the \c Role that a comma was found. 786 virtual void CommaFound(const FormatToken *Token) {} 787 788 virtual const FormatToken *lastComma() { return nullptr; } 789 790 protected: 791 const FormatStyle &Style; 792 }; 793 794 class CommaSeparatedList : public TokenRole { 795 public: 796 CommaSeparatedList(const FormatStyle &Style) 797 : TokenRole(Style), HasNestedBracedList(false) {} 798 799 void precomputeFormattingInfos(const FormatToken *Token) override; 800 801 unsigned formatAfterToken(LineState &State, ContinuationIndenter *Indenter, 802 bool DryRun) override; 803 804 unsigned formatFromToken(LineState &State, ContinuationIndenter *Indenter, 805 bool DryRun) override; 806 807 /// Adds \p Token as the next comma to the \c CommaSeparated list. 808 void CommaFound(const FormatToken *Token) override { 809 Commas.push_back(Token); 810 } 811 812 const FormatToken *lastComma() override { 813 if (Commas.empty()) 814 return nullptr; 815 return Commas.back(); 816 } 817 818 private: 819 /// A struct that holds information on how to format a given list with 820 /// a specific number of columns. 821 struct ColumnFormat { 822 /// The number of columns to use. 823 unsigned Columns; 824 825 /// The total width in characters. 826 unsigned TotalWidth; 827 828 /// The number of lines required for this format. 829 unsigned LineCount; 830 831 /// The size of each column in characters. 832 SmallVector<unsigned, 8> ColumnSizes; 833 }; 834 835 /// Calculate which \c ColumnFormat fits best into 836 /// \p RemainingCharacters. 837 const ColumnFormat *getColumnFormat(unsigned RemainingCharacters) const; 838 839 /// The ordered \c FormatTokens making up the commas of this list. 840 SmallVector<const FormatToken *, 8> Commas; 841 842 /// The length of each of the list's items in characters including the 843 /// trailing comma. 844 SmallVector<unsigned, 8> ItemLengths; 845 846 /// Precomputed formats that can be used for this list. 847 SmallVector<ColumnFormat, 4> Formats; 848 849 bool HasNestedBracedList; 850 }; 851 852 /// Encapsulates keywords that are context sensitive or for languages not 853 /// properly supported by Clang's lexer. 854 struct AdditionalKeywords { 855 AdditionalKeywords(IdentifierTable &IdentTable) { 856 kw_final = &IdentTable.get("final"); 857 kw_override = &IdentTable.get("override"); 858 kw_in = &IdentTable.get("in"); 859 kw_of = &IdentTable.get("of"); 860 kw_CF_CLOSED_ENUM = &IdentTable.get("CF_CLOSED_ENUM"); 861 kw_CF_ENUM = &IdentTable.get("CF_ENUM"); 862 kw_CF_OPTIONS = &IdentTable.get("CF_OPTIONS"); 863 kw_NS_CLOSED_ENUM = &IdentTable.get("NS_CLOSED_ENUM"); 864 kw_NS_ENUM = &IdentTable.get("NS_ENUM"); 865 kw_NS_OPTIONS = &IdentTable.get("NS_OPTIONS"); 866 867 kw_as = &IdentTable.get("as"); 868 kw_async = &IdentTable.get("async"); 869 kw_await = &IdentTable.get("await"); 870 kw_declare = &IdentTable.get("declare"); 871 kw_finally = &IdentTable.get("finally"); 872 kw_from = &IdentTable.get("from"); 873 kw_function = &IdentTable.get("function"); 874 kw_get = &IdentTable.get("get"); 875 kw_import = &IdentTable.get("import"); 876 kw_infer = &IdentTable.get("infer"); 877 kw_is = &IdentTable.get("is"); 878 kw_let = &IdentTable.get("let"); 879 kw_module = &IdentTable.get("module"); 880 kw_readonly = &IdentTable.get("readonly"); 881 kw_set = &IdentTable.get("set"); 882 kw_type = &IdentTable.get("type"); 883 kw_typeof = &IdentTable.get("typeof"); 884 kw_var = &IdentTable.get("var"); 885 kw_yield = &IdentTable.get("yield"); 886 887 kw_abstract = &IdentTable.get("abstract"); 888 kw_assert = &IdentTable.get("assert"); 889 kw_extends = &IdentTable.get("extends"); 890 kw_implements = &IdentTable.get("implements"); 891 kw_instanceof = &IdentTable.get("instanceof"); 892 kw_interface = &IdentTable.get("interface"); 893 kw_native = &IdentTable.get("native"); 894 kw_package = &IdentTable.get("package"); 895 kw_synchronized = &IdentTable.get("synchronized"); 896 kw_throws = &IdentTable.get("throws"); 897 kw___except = &IdentTable.get("__except"); 898 kw___has_include = &IdentTable.get("__has_include"); 899 kw___has_include_next = &IdentTable.get("__has_include_next"); 900 901 kw_mark = &IdentTable.get("mark"); 902 903 kw_extend = &IdentTable.get("extend"); 904 kw_option = &IdentTable.get("option"); 905 kw_optional = &IdentTable.get("optional"); 906 kw_repeated = &IdentTable.get("repeated"); 907 kw_required = &IdentTable.get("required"); 908 kw_returns = &IdentTable.get("returns"); 909 910 kw_signals = &IdentTable.get("signals"); 911 kw_qsignals = &IdentTable.get("Q_SIGNALS"); 912 kw_slots = &IdentTable.get("slots"); 913 kw_qslots = &IdentTable.get("Q_SLOTS"); 914 915 // C# keywords 916 kw_dollar = &IdentTable.get("dollar"); 917 kw_base = &IdentTable.get("base"); 918 kw_byte = &IdentTable.get("byte"); 919 kw_checked = &IdentTable.get("checked"); 920 kw_decimal = &IdentTable.get("decimal"); 921 kw_delegate = &IdentTable.get("delegate"); 922 kw_event = &IdentTable.get("event"); 923 kw_fixed = &IdentTable.get("fixed"); 924 kw_foreach = &IdentTable.get("foreach"); 925 kw_implicit = &IdentTable.get("implicit"); 926 kw_internal = &IdentTable.get("internal"); 927 kw_lock = &IdentTable.get("lock"); 928 kw_null = &IdentTable.get("null"); 929 kw_object = &IdentTable.get("object"); 930 kw_out = &IdentTable.get("out"); 931 kw_params = &IdentTable.get("params"); 932 kw_ref = &IdentTable.get("ref"); 933 kw_string = &IdentTable.get("string"); 934 kw_stackalloc = &IdentTable.get("stackalloc"); 935 kw_sbyte = &IdentTable.get("sbyte"); 936 kw_sealed = &IdentTable.get("sealed"); 937 kw_uint = &IdentTable.get("uint"); 938 kw_ulong = &IdentTable.get("ulong"); 939 kw_unchecked = &IdentTable.get("unchecked"); 940 kw_unsafe = &IdentTable.get("unsafe"); 941 kw_ushort = &IdentTable.get("ushort"); 942 kw_when = &IdentTable.get("when"); 943 kw_where = &IdentTable.get("where"); 944 945 // Keep this at the end of the constructor to make sure everything here 946 // is 947 // already initialized. 948 JsExtraKeywords = std::unordered_set<IdentifierInfo *>( 949 {kw_as, kw_async, kw_await, kw_declare, kw_finally, kw_from, 950 kw_function, kw_get, kw_import, kw_is, kw_let, kw_module, kw_override, 951 kw_readonly, kw_set, kw_type, kw_typeof, kw_var, kw_yield, 952 // Keywords from the Java section. 953 kw_abstract, kw_extends, kw_implements, kw_instanceof, kw_interface}); 954 955 CSharpExtraKeywords = std::unordered_set<IdentifierInfo *>( 956 {kw_base, kw_byte, kw_checked, kw_decimal, kw_delegate, kw_event, 957 kw_fixed, kw_foreach, kw_implicit, kw_in, kw_interface, kw_internal, 958 kw_is, kw_lock, kw_null, kw_object, kw_out, kw_override, kw_params, 959 kw_readonly, kw_ref, kw_string, kw_stackalloc, kw_sbyte, kw_sealed, 960 kw_uint, kw_ulong, kw_unchecked, kw_unsafe, kw_ushort, kw_when, 961 kw_where, 962 // Keywords from the JavaScript section. 963 kw_as, kw_async, kw_await, kw_declare, kw_finally, kw_from, 964 kw_function, kw_get, kw_import, kw_is, kw_let, kw_module, kw_readonly, 965 kw_set, kw_type, kw_typeof, kw_var, kw_yield, 966 // Keywords from the Java section. 967 kw_abstract, kw_extends, kw_implements, kw_instanceof, kw_interface}); 968 } 969 970 // Context sensitive keywords. 971 IdentifierInfo *kw_final; 972 IdentifierInfo *kw_override; 973 IdentifierInfo *kw_in; 974 IdentifierInfo *kw_of; 975 IdentifierInfo *kw_CF_CLOSED_ENUM; 976 IdentifierInfo *kw_CF_ENUM; 977 IdentifierInfo *kw_CF_OPTIONS; 978 IdentifierInfo *kw_NS_CLOSED_ENUM; 979 IdentifierInfo *kw_NS_ENUM; 980 IdentifierInfo *kw_NS_OPTIONS; 981 IdentifierInfo *kw___except; 982 IdentifierInfo *kw___has_include; 983 IdentifierInfo *kw___has_include_next; 984 985 // JavaScript keywords. 986 IdentifierInfo *kw_as; 987 IdentifierInfo *kw_async; 988 IdentifierInfo *kw_await; 989 IdentifierInfo *kw_declare; 990 IdentifierInfo *kw_finally; 991 IdentifierInfo *kw_from; 992 IdentifierInfo *kw_function; 993 IdentifierInfo *kw_get; 994 IdentifierInfo *kw_import; 995 IdentifierInfo *kw_infer; 996 IdentifierInfo *kw_is; 997 IdentifierInfo *kw_let; 998 IdentifierInfo *kw_module; 999 IdentifierInfo *kw_readonly; 1000 IdentifierInfo *kw_set; 1001 IdentifierInfo *kw_type; 1002 IdentifierInfo *kw_typeof; 1003 IdentifierInfo *kw_var; 1004 IdentifierInfo *kw_yield; 1005 1006 // Java keywords. 1007 IdentifierInfo *kw_abstract; 1008 IdentifierInfo *kw_assert; 1009 IdentifierInfo *kw_extends; 1010 IdentifierInfo *kw_implements; 1011 IdentifierInfo *kw_instanceof; 1012 IdentifierInfo *kw_interface; 1013 IdentifierInfo *kw_native; 1014 IdentifierInfo *kw_package; 1015 IdentifierInfo *kw_synchronized; 1016 IdentifierInfo *kw_throws; 1017 1018 // Pragma keywords. 1019 IdentifierInfo *kw_mark; 1020 1021 // Proto keywords. 1022 IdentifierInfo *kw_extend; 1023 IdentifierInfo *kw_option; 1024 IdentifierInfo *kw_optional; 1025 IdentifierInfo *kw_repeated; 1026 IdentifierInfo *kw_required; 1027 IdentifierInfo *kw_returns; 1028 1029 // QT keywords. 1030 IdentifierInfo *kw_signals; 1031 IdentifierInfo *kw_qsignals; 1032 IdentifierInfo *kw_slots; 1033 IdentifierInfo *kw_qslots; 1034 1035 // C# keywords 1036 IdentifierInfo *kw_dollar; 1037 IdentifierInfo *kw_base; 1038 IdentifierInfo *kw_byte; 1039 IdentifierInfo *kw_checked; 1040 IdentifierInfo *kw_decimal; 1041 IdentifierInfo *kw_delegate; 1042 IdentifierInfo *kw_event; 1043 IdentifierInfo *kw_fixed; 1044 IdentifierInfo *kw_foreach; 1045 IdentifierInfo *kw_implicit; 1046 IdentifierInfo *kw_internal; 1047 1048 IdentifierInfo *kw_lock; 1049 IdentifierInfo *kw_null; 1050 IdentifierInfo *kw_object; 1051 IdentifierInfo *kw_out; 1052 1053 IdentifierInfo *kw_params; 1054 1055 IdentifierInfo *kw_ref; 1056 IdentifierInfo *kw_string; 1057 IdentifierInfo *kw_stackalloc; 1058 IdentifierInfo *kw_sbyte; 1059 IdentifierInfo *kw_sealed; 1060 IdentifierInfo *kw_uint; 1061 IdentifierInfo *kw_ulong; 1062 IdentifierInfo *kw_unchecked; 1063 IdentifierInfo *kw_unsafe; 1064 IdentifierInfo *kw_ushort; 1065 IdentifierInfo *kw_when; 1066 IdentifierInfo *kw_where; 1067 1068 /// Returns \c true if \p Tok is a true JavaScript identifier, returns 1069 /// \c false if it is a keyword or a pseudo keyword. 1070 /// If \c AcceptIdentifierName is true, returns true not only for keywords, 1071 // but also for IdentifierName tokens (aka pseudo-keywords), such as 1072 // ``yield``. 1073 bool IsJavaScriptIdentifier(const FormatToken &Tok, 1074 bool AcceptIdentifierName = true) const { 1075 // Based on the list of JavaScript & TypeScript keywords here: 1076 // https://github.com/microsoft/TypeScript/blob/main/src/compiler/scanner.ts#L74 1077 switch (Tok.Tok.getKind()) { 1078 case tok::kw_break: 1079 case tok::kw_case: 1080 case tok::kw_catch: 1081 case tok::kw_class: 1082 case tok::kw_continue: 1083 case tok::kw_const: 1084 case tok::kw_default: 1085 case tok::kw_delete: 1086 case tok::kw_do: 1087 case tok::kw_else: 1088 case tok::kw_enum: 1089 case tok::kw_export: 1090 case tok::kw_false: 1091 case tok::kw_for: 1092 case tok::kw_if: 1093 case tok::kw_import: 1094 case tok::kw_module: 1095 case tok::kw_new: 1096 case tok::kw_private: 1097 case tok::kw_protected: 1098 case tok::kw_public: 1099 case tok::kw_return: 1100 case tok::kw_static: 1101 case tok::kw_switch: 1102 case tok::kw_this: 1103 case tok::kw_throw: 1104 case tok::kw_true: 1105 case tok::kw_try: 1106 case tok::kw_typeof: 1107 case tok::kw_void: 1108 case tok::kw_while: 1109 // These are JS keywords that are lexed by LLVM/clang as keywords. 1110 return false; 1111 case tok::identifier: { 1112 // For identifiers, make sure they are true identifiers, excluding the 1113 // JavaScript pseudo-keywords (not lexed by LLVM/clang as keywords). 1114 bool IsPseudoKeyword = 1115 JsExtraKeywords.find(Tok.Tok.getIdentifierInfo()) != 1116 JsExtraKeywords.end(); 1117 return AcceptIdentifierName || !IsPseudoKeyword; 1118 } 1119 default: 1120 // Other keywords are handled in the switch below, to avoid problems due 1121 // to duplicate case labels when using the #include trick. 1122 break; 1123 } 1124 1125 switch (Tok.Tok.getKind()) { 1126 // Handle C++ keywords not included above: these are all JS identifiers. 1127 #define KEYWORD(X, Y) case tok::kw_##X: 1128 #include "clang/Basic/TokenKinds.def" 1129 // #undef KEYWORD is not needed -- it's #undef-ed at the end of 1130 // TokenKinds.def 1131 return true; 1132 default: 1133 // All other tokens (punctuation etc) are not JS identifiers. 1134 return false; 1135 } 1136 } 1137 1138 /// Returns \c true if \p Tok is a C# keyword, returns 1139 /// \c false if it is a anything else. 1140 bool isCSharpKeyword(const FormatToken &Tok) const { 1141 switch (Tok.Tok.getKind()) { 1142 case tok::kw_bool: 1143 case tok::kw_break: 1144 case tok::kw_case: 1145 case tok::kw_catch: 1146 case tok::kw_char: 1147 case tok::kw_class: 1148 case tok::kw_const: 1149 case tok::kw_continue: 1150 case tok::kw_default: 1151 case tok::kw_do: 1152 case tok::kw_double: 1153 case tok::kw_else: 1154 case tok::kw_enum: 1155 case tok::kw_explicit: 1156 case tok::kw_extern: 1157 case tok::kw_false: 1158 case tok::kw_float: 1159 case tok::kw_for: 1160 case tok::kw_goto: 1161 case tok::kw_if: 1162 case tok::kw_int: 1163 case tok::kw_long: 1164 case tok::kw_namespace: 1165 case tok::kw_new: 1166 case tok::kw_operator: 1167 case tok::kw_private: 1168 case tok::kw_protected: 1169 case tok::kw_public: 1170 case tok::kw_return: 1171 case tok::kw_short: 1172 case tok::kw_sizeof: 1173 case tok::kw_static: 1174 case tok::kw_struct: 1175 case tok::kw_switch: 1176 case tok::kw_this: 1177 case tok::kw_throw: 1178 case tok::kw_true: 1179 case tok::kw_try: 1180 case tok::kw_typeof: 1181 case tok::kw_using: 1182 case tok::kw_virtual: 1183 case tok::kw_void: 1184 case tok::kw_volatile: 1185 case tok::kw_while: 1186 return true; 1187 default: 1188 return Tok.is(tok::identifier) && 1189 CSharpExtraKeywords.find(Tok.Tok.getIdentifierInfo()) == 1190 CSharpExtraKeywords.end(); 1191 } 1192 } 1193 1194 private: 1195 /// The JavaScript keywords beyond the C++ keyword set. 1196 std::unordered_set<IdentifierInfo *> JsExtraKeywords; 1197 1198 /// The C# keywords beyond the C++ keyword set 1199 std::unordered_set<IdentifierInfo *> CSharpExtraKeywords; 1200 }; 1201 1202 } // namespace format 1203 } // namespace clang 1204 1205 #endif 1206