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