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