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