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