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