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