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