1 //===--- FormatToken.h - Format C++ code ------------------------*- C++ -*-===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 /// 10 /// \file 11 /// \brief This file contains the declaration of the FormatToken, a wrapper 12 /// around Token with additional information related to formatting. 13 /// 14 //===----------------------------------------------------------------------===// 15 16 #ifndef LLVM_CLANG_LIB_FORMAT_FORMATTOKEN_H 17 #define LLVM_CLANG_LIB_FORMAT_FORMATTOKEN_H 18 19 #include "clang/Basic/IdentifierTable.h" 20 #include "clang/Basic/OperatorPrecedence.h" 21 #include "clang/Format/Format.h" 22 #include "clang/Lex/Lexer.h" 23 #include <memory> 24 #include <unordered_set> 25 26 namespace clang { 27 namespace format { 28 29 #define LIST_TOKEN_TYPES \ 30 TYPE(ArrayInitializerLSquare) \ 31 TYPE(ArraySubscriptLSquare) \ 32 TYPE(AttributeColon) \ 33 TYPE(AttributeParen) \ 34 TYPE(AttributeSquare) \ 35 TYPE(BinaryOperator) \ 36 TYPE(BitFieldColon) \ 37 TYPE(BlockComment) \ 38 TYPE(CastRParen) \ 39 TYPE(ConditionalExpr) \ 40 TYPE(ConflictAlternative) \ 41 TYPE(ConflictEnd) \ 42 TYPE(ConflictStart) \ 43 TYPE(CtorInitializerColon) \ 44 TYPE(CtorInitializerComma) \ 45 TYPE(DesignatedInitializerLSquare) \ 46 TYPE(DesignatedInitializerPeriod) \ 47 TYPE(DictLiteral) \ 48 TYPE(ForEachMacro) \ 49 TYPE(FunctionAnnotationRParen) \ 50 TYPE(FunctionDeclarationName) \ 51 TYPE(FunctionLBrace) \ 52 TYPE(FunctionTypeLParen) \ 53 TYPE(ImplicitStringLiteral) \ 54 TYPE(InheritanceColon) \ 55 TYPE(InheritanceComma) \ 56 TYPE(InlineASMBrace) \ 57 TYPE(InlineASMColon) \ 58 TYPE(JavaAnnotation) \ 59 TYPE(JsComputedPropertyName) \ 60 TYPE(JsExponentiation) \ 61 TYPE(JsExponentiationEqual) \ 62 TYPE(JsFatArrow) \ 63 TYPE(JsNonNullAssertion) \ 64 TYPE(JsTypeColon) \ 65 TYPE(JsTypeOperator) \ 66 TYPE(JsTypeOptionalQuestion) \ 67 TYPE(LambdaArrow) \ 68 TYPE(LambdaLSquare) \ 69 TYPE(LeadingJavaAnnotation) \ 70 TYPE(LineComment) \ 71 TYPE(MacroBlockBegin) \ 72 TYPE(MacroBlockEnd) \ 73 TYPE(ObjCBlockLBrace) \ 74 TYPE(ObjCBlockLParen) \ 75 TYPE(ObjCDecl) \ 76 TYPE(ObjCForIn) \ 77 TYPE(ObjCMethodExpr) \ 78 TYPE(ObjCMethodSpecifier) \ 79 TYPE(ObjCProperty) \ 80 TYPE(ObjCStringLiteral) \ 81 TYPE(OverloadedOperator) \ 82 TYPE(OverloadedOperatorLParen) \ 83 TYPE(PointerOrReference) \ 84 TYPE(PureVirtualSpecifier) \ 85 TYPE(RangeBasedForLoopColon) \ 86 TYPE(RegexLiteral) \ 87 TYPE(SelectorName) \ 88 TYPE(StartOfName) \ 89 TYPE(StructuredBindingLSquare) \ 90 TYPE(TemplateCloser) \ 91 TYPE(TemplateOpener) \ 92 TYPE(TemplateString) \ 93 TYPE(ProtoExtensionLSquare) \ 94 TYPE(TrailingAnnotation) \ 95 TYPE(TrailingReturnArrow) \ 96 TYPE(TrailingUnaryOperator) \ 97 TYPE(UnaryOperator) \ 98 TYPE(Unknown) 99 100 enum TokenType { 101 #define TYPE(X) TT_##X, 102 LIST_TOKEN_TYPES 103 #undef TYPE 104 NUM_TOKEN_TYPES 105 }; 106 107 /// \brief Determines the name of a token type. 108 const char *getTokenTypeName(TokenType Type); 109 110 // Represents what type of block a set of braces open. 111 enum BraceBlockKind { BK_Unknown, BK_Block, BK_BracedInit }; 112 113 // The packing kind of a function's parameters. 114 enum ParameterPackingKind { PPK_BinPacked, PPK_OnePerLine, PPK_Inconclusive }; 115 116 enum FormatDecision { FD_Unformatted, FD_Continue, FD_Break }; 117 118 class TokenRole; 119 class AnnotatedLine; 120 121 /// \brief A wrapper around a \c Token storing information about the 122 /// whitespace characters preceding it. 123 struct FormatToken { 124 FormatToken() {} 125 126 /// \brief The \c Token. 127 Token Tok; 128 129 /// \brief The number of newlines immediately before the \c Token. 130 /// 131 /// This can be used to determine what the user wrote in the original code 132 /// and thereby e.g. leave an empty line between two function definitions. 133 unsigned NewlinesBefore = 0; 134 135 /// \brief Whether there is at least one unescaped newline before the \c 136 /// Token. 137 bool HasUnescapedNewline = false; 138 139 /// \brief The range of the whitespace immediately preceding the \c Token. 140 SourceRange WhitespaceRange; 141 142 /// \brief The offset just past the last '\n' in this token's leading 143 /// whitespace (relative to \c WhiteSpaceStart). 0 if there is no '\n'. 144 unsigned LastNewlineOffset = 0; 145 146 /// \brief The width of the non-whitespace parts of the token (or its first 147 /// line for multi-line tokens) in columns. 148 /// We need this to correctly measure number of columns a token spans. 149 unsigned ColumnWidth = 0; 150 151 /// \brief Contains the width in columns of the last line of a multi-line 152 /// token. 153 unsigned LastLineColumnWidth = 0; 154 155 /// \brief Whether the token text contains newlines (escaped or not). 156 bool IsMultiline = false; 157 158 /// \brief Indicates that this is the first token of the file. 159 bool IsFirst = false; 160 161 /// \brief Whether there must be a line break before this token. 162 /// 163 /// This happens for example when a preprocessor directive ended directly 164 /// before the token. 165 bool MustBreakBefore = false; 166 167 /// \brief The raw text of the token. 168 /// 169 /// Contains the raw token text without leading whitespace and without leading 170 /// escaped newlines. 171 StringRef TokenText; 172 173 /// \brief Set to \c true if this token is an unterminated literal. 174 bool IsUnterminatedLiteral = 0; 175 176 /// \brief Contains the kind of block if this token is a brace. 177 BraceBlockKind BlockKind = BK_Unknown; 178 179 TokenType Type = TT_Unknown; 180 181 /// \brief The number of spaces that should be inserted before this token. 182 unsigned SpacesRequiredBefore = 0; 183 184 /// \brief \c true if it is allowed to break before this token. 185 bool CanBreakBefore = false; 186 187 /// \brief \c true if this is the ">" of "template<..>". 188 bool ClosesTemplateDeclaration = false; 189 190 /// \brief Number of parameters, if this is "(", "[" or "<". 191 /// 192 /// This is initialized to 1 as we don't need to distinguish functions with 193 /// 0 parameters from functions with 1 parameter. Thus, we can simply count 194 /// the number of commas. 195 unsigned ParameterCount = 0; 196 197 /// \brief Number of parameters that are nested blocks, 198 /// if this is "(", "[" or "<". 199 unsigned BlockParameterCount = 0; 200 201 /// \brief If this is a bracket ("<", "(", "[" or "{"), contains the kind of 202 /// the surrounding bracket. 203 tok::TokenKind ParentBracket = tok::unknown; 204 205 /// \brief A token can have a special role that can carry extra information 206 /// about the token's formatting. 207 std::unique_ptr<TokenRole> Role; 208 209 /// \brief If this is an opening parenthesis, how are the parameters packed? 210 ParameterPackingKind PackingKind = PPK_Inconclusive; 211 212 /// \brief The total length of the unwrapped line up to and including this 213 /// token. 214 unsigned TotalLength = 0; 215 216 /// \brief The original 0-based column of this token, including expanded tabs. 217 /// The configured TabWidth is used as tab width. 218 unsigned OriginalColumn = 0; 219 220 /// \brief The length of following tokens until the next natural split point, 221 /// or the next token that can be broken. 222 unsigned UnbreakableTailLength = 0; 223 224 // FIXME: Come up with a 'cleaner' concept. 225 /// \brief The binding strength of a token. This is a combined value of 226 /// operator precedence, parenthesis nesting, etc. 227 unsigned BindingStrength = 0; 228 229 /// \brief The nesting level of this token, i.e. the number of surrounding (), 230 /// [], {} or <>. 231 unsigned NestingLevel = 0; 232 233 /// \brief The indent level of this token. Copied from the surrounding line. 234 unsigned IndentLevel = 0; 235 236 /// \brief Penalty for inserting a line break before this token. 237 unsigned SplitPenalty = 0; 238 239 /// \brief If this is the first ObjC selector name in an ObjC method 240 /// definition or call, this contains the length of the longest name. 241 /// 242 /// This being set to 0 means that the selectors should not be colon-aligned, 243 /// e.g. because several of them are block-type. 244 unsigned LongestObjCSelectorName = 0; 245 246 /// \brief How many parts ObjC selector have (i.e. how many parameters method 247 /// has). 248 unsigned ObjCSelectorNameParts = 0; 249 250 /// \brief Stores the number of required fake parentheses and the 251 /// corresponding operator precedence. 252 /// 253 /// If multiple fake parentheses start at a token, this vector stores them in 254 /// reverse order, i.e. inner fake parenthesis first. 255 SmallVector<prec::Level, 4> FakeLParens; 256 /// \brief Insert this many fake ) after this token for correct indentation. 257 unsigned FakeRParens = 0; 258 259 /// \brief \c true if this token starts a binary expression, i.e. has at least 260 /// one fake l_paren with a precedence greater than prec::Unknown. 261 bool StartsBinaryExpression = false; 262 /// \brief \c true if this token ends a binary expression. 263 bool EndsBinaryExpression = false; 264 265 /// \brief Is this is an operator (or "."/"->") in a sequence of operators 266 /// with the same precedence, contains the 0-based operator index. 267 unsigned OperatorIndex = 0; 268 269 /// \brief If this is an operator (or "."/"->") in a sequence of operators 270 /// with the same precedence, points to the next operator. 271 FormatToken *NextOperator = nullptr; 272 273 /// \brief Is this token part of a \c DeclStmt defining multiple variables? 274 /// 275 /// Only set if \c Type == \c TT_StartOfName. 276 bool PartOfMultiVariableDeclStmt = false; 277 278 /// \brief Does this line comment continue a line comment section? 279 /// 280 /// Only set to true if \c Type == \c TT_LineComment. 281 bool ContinuesLineCommentSection = false; 282 283 /// \brief If this is a bracket, this points to the matching one. 284 FormatToken *MatchingParen = nullptr; 285 286 /// \brief The previous token in the unwrapped line. 287 FormatToken *Previous = nullptr; 288 289 /// \brief The next token in the unwrapped line. 290 FormatToken *Next = nullptr; 291 292 /// \brief If this token starts a block, this contains all the unwrapped lines 293 /// in it. 294 SmallVector<AnnotatedLine *, 1> Children; 295 296 /// \brief Stores the formatting decision for the token once it was made. 297 FormatDecision Decision = FD_Unformatted; 298 299 /// \brief If \c true, this token has been fully formatted (indented and 300 /// potentially re-formatted inside), and we do not allow further formatting 301 /// changes. 302 bool Finalized = false; 303 304 bool is(tok::TokenKind Kind) const { return Tok.is(Kind); } 305 bool is(TokenType TT) const { return Type == TT; } 306 bool is(const IdentifierInfo *II) const { 307 return II && II == Tok.getIdentifierInfo(); 308 } 309 bool is(tok::PPKeywordKind Kind) const { 310 return Tok.getIdentifierInfo() && 311 Tok.getIdentifierInfo()->getPPKeywordID() == Kind; 312 } 313 template <typename A, typename B> bool isOneOf(A K1, B K2) const { 314 return is(K1) || is(K2); 315 } 316 template <typename A, typename B, typename... Ts> 317 bool isOneOf(A K1, B K2, Ts... Ks) const { 318 return is(K1) || isOneOf(K2, Ks...); 319 } 320 template <typename T> bool isNot(T Kind) const { return !is(Kind); } 321 322 /// \c true if this token starts a sequence with the given tokens in order, 323 /// following the ``Next`` pointers, ignoring comments. 324 template <typename A, typename... Ts> 325 bool startsSequence(A K1, Ts... Tokens) const { 326 return startsSequenceInternal(K1, Tokens...); 327 } 328 329 /// \c true if this token ends a sequence with the given tokens in order, 330 /// following the ``Previous`` pointers, ignoring comments. 331 template <typename A, typename... Ts> 332 bool endsSequence(A K1, Ts... Tokens) const { 333 return endsSequenceInternal(K1, Tokens...); 334 } 335 336 bool isStringLiteral() const { return tok::isStringLiteral(Tok.getKind()); } 337 338 bool isObjCAtKeyword(tok::ObjCKeywordKind Kind) const { 339 return Tok.isObjCAtKeyword(Kind); 340 } 341 342 bool isAccessSpecifier(bool ColonRequired = true) const { 343 return isOneOf(tok::kw_public, tok::kw_protected, tok::kw_private) && 344 (!ColonRequired || (Next && Next->is(tok::colon))); 345 } 346 347 /// \brief Determine whether the token is a simple-type-specifier. 348 bool isSimpleTypeSpecifier() const; 349 350 bool isObjCAccessSpecifier() const { 351 return is(tok::at) && Next && 352 (Next->isObjCAtKeyword(tok::objc_public) || 353 Next->isObjCAtKeyword(tok::objc_protected) || 354 Next->isObjCAtKeyword(tok::objc_package) || 355 Next->isObjCAtKeyword(tok::objc_private)); 356 } 357 358 /// \brief Returns whether \p Tok is ([{ or an opening < of a template or in 359 /// protos. 360 bool opensScope() const { 361 if (is(TT_TemplateString) && TokenText.endswith("${")) 362 return true; 363 if (is(TT_DictLiteral) && is(tok::less)) 364 return true; 365 return isOneOf(tok::l_paren, tok::l_brace, tok::l_square, 366 TT_TemplateOpener); 367 } 368 /// \brief Returns whether \p Tok is )]} or a closing > of a template or in 369 /// protos. 370 bool closesScope() const { 371 if (is(TT_TemplateString) && TokenText.startswith("}")) 372 return true; 373 if (is(TT_DictLiteral) && is(tok::greater)) 374 return true; 375 return isOneOf(tok::r_paren, tok::r_brace, tok::r_square, 376 TT_TemplateCloser); 377 } 378 379 /// \brief Returns \c true if this is a "." or "->" accessing a member. 380 bool isMemberAccess() const { 381 return isOneOf(tok::arrow, tok::period, tok::arrowstar) && 382 !isOneOf(TT_DesignatedInitializerPeriod, TT_TrailingReturnArrow, 383 TT_LambdaArrow); 384 } 385 386 bool isUnaryOperator() const { 387 switch (Tok.getKind()) { 388 case tok::plus: 389 case tok::plusplus: 390 case tok::minus: 391 case tok::minusminus: 392 case tok::exclaim: 393 case tok::tilde: 394 case tok::kw_sizeof: 395 case tok::kw_alignof: 396 return true; 397 default: 398 return false; 399 } 400 } 401 402 bool isBinaryOperator() const { 403 // Comma is a binary operator, but does not behave as such wrt. formatting. 404 return getPrecedence() > prec::Comma; 405 } 406 407 bool isTrailingComment() const { 408 return is(tok::comment) && 409 (is(TT_LineComment) || !Next || Next->NewlinesBefore > 0); 410 } 411 412 /// \brief Returns \c true if this is a keyword that can be used 413 /// like a function call (e.g. sizeof, typeid, ...). 414 bool isFunctionLikeKeyword() const { 415 switch (Tok.getKind()) { 416 case tok::kw_throw: 417 case tok::kw_typeid: 418 case tok::kw_return: 419 case tok::kw_sizeof: 420 case tok::kw_alignof: 421 case tok::kw_alignas: 422 case tok::kw_decltype: 423 case tok::kw_noexcept: 424 case tok::kw_static_assert: 425 case tok::kw___attribute: 426 return true; 427 default: 428 return false; 429 } 430 } 431 432 /// \brief Returns \c true if this is a string literal that's like a label, 433 /// e.g. ends with "=" or ":". 434 bool isLabelString() const { 435 if (!is(tok::string_literal)) 436 return false; 437 StringRef Content = TokenText; 438 if (Content.startswith("\"") || Content.startswith("'")) 439 Content = Content.drop_front(1); 440 if (Content.endswith("\"") || Content.endswith("'")) 441 Content = Content.drop_back(1); 442 Content = Content.trim(); 443 return Content.size() > 1 && 444 (Content.back() == ':' || Content.back() == '='); 445 } 446 447 /// \brief Returns actual token start location without leading escaped 448 /// newlines and whitespace. 449 /// 450 /// This can be different to Tok.getLocation(), which includes leading escaped 451 /// newlines. 452 SourceLocation getStartOfNonWhitespace() const { 453 return WhitespaceRange.getEnd(); 454 } 455 456 prec::Level getPrecedence() const { 457 return getBinOpPrecedence(Tok.getKind(), /*GreaterThanIsOperator=*/true, 458 /*CPlusPlus11=*/true); 459 } 460 461 /// \brief Returns the previous token ignoring comments. 462 FormatToken *getPreviousNonComment() const { 463 FormatToken *Tok = Previous; 464 while (Tok && Tok->is(tok::comment)) 465 Tok = Tok->Previous; 466 return Tok; 467 } 468 469 /// \brief Returns the next token ignoring comments. 470 const FormatToken *getNextNonComment() const { 471 const FormatToken *Tok = Next; 472 while (Tok && Tok->is(tok::comment)) 473 Tok = Tok->Next; 474 return Tok; 475 } 476 477 /// \brief Returns \c true if this tokens starts a block-type list, i.e. a 478 /// list that should be indented with a block indent. 479 bool opensBlockOrBlockTypeList(const FormatStyle &Style) const { 480 if (is(TT_TemplateString) && opensScope()) 481 return true; 482 return is(TT_ArrayInitializerLSquare) || 483 is(TT_ProtoExtensionLSquare) || 484 (is(tok::l_brace) && 485 (BlockKind == BK_Block || is(TT_DictLiteral) || 486 (!Style.Cpp11BracedListStyle && NestingLevel == 0))) || 487 (is(tok::less) && (Style.Language == FormatStyle::LK_Proto || 488 Style.Language == FormatStyle::LK_TextProto)); 489 } 490 491 /// \brief Returns whether the token is the left square bracket of a C++ 492 /// structured binding declaration. 493 bool isCppStructuredBinding(const FormatStyle &Style) const { 494 if (!Style.isCpp() || isNot(tok::l_square)) 495 return false; 496 const FormatToken *T = this; 497 do { 498 T = T->getPreviousNonComment(); 499 } while (T && T->isOneOf(tok::kw_const, tok::kw_volatile, tok::amp, 500 tok::ampamp)); 501 return T && T->is(tok::kw_auto); 502 } 503 504 /// \brief Same as opensBlockOrBlockTypeList, but for the closing token. 505 bool closesBlockOrBlockTypeList(const FormatStyle &Style) const { 506 if (is(TT_TemplateString) && closesScope()) 507 return true; 508 return MatchingParen && MatchingParen->opensBlockOrBlockTypeList(Style); 509 } 510 511 /// \brief Return the actual namespace token, if this token starts a namespace 512 /// block. 513 const FormatToken *getNamespaceToken() const { 514 const FormatToken *NamespaceTok = this; 515 if (is(tok::comment)) 516 NamespaceTok = NamespaceTok->getNextNonComment(); 517 // Detect "(inline)? namespace" in the beginning of a line. 518 if (NamespaceTok && NamespaceTok->is(tok::kw_inline)) 519 NamespaceTok = NamespaceTok->getNextNonComment(); 520 return NamespaceTok && NamespaceTok->is(tok::kw_namespace) ? NamespaceTok 521 : nullptr; 522 } 523 524 private: 525 // Disallow copying. 526 FormatToken(const FormatToken &) = delete; 527 void operator=(const FormatToken &) = delete; 528 529 template <typename A, typename... Ts> 530 bool startsSequenceInternal(A K1, Ts... Tokens) const { 531 if (is(tok::comment) && Next) 532 return Next->startsSequenceInternal(K1, Tokens...); 533 return is(K1) && Next && Next->startsSequenceInternal(Tokens...); 534 } 535 536 template <typename A> bool startsSequenceInternal(A K1) const { 537 if (is(tok::comment) && Next) 538 return Next->startsSequenceInternal(K1); 539 return is(K1); 540 } 541 542 template <typename A, typename... Ts> bool endsSequenceInternal(A K1) const { 543 if (is(tok::comment) && Previous) 544 return Previous->endsSequenceInternal(K1); 545 return is(K1); 546 } 547 548 template <typename A, typename... Ts> 549 bool endsSequenceInternal(A K1, Ts... Tokens) const { 550 if (is(tok::comment) && Previous) 551 return Previous->endsSequenceInternal(K1, Tokens...); 552 return is(K1) && Previous && Previous->endsSequenceInternal(Tokens...); 553 } 554 }; 555 556 class ContinuationIndenter; 557 struct LineState; 558 559 class TokenRole { 560 public: 561 TokenRole(const FormatStyle &Style) : Style(Style) {} 562 virtual ~TokenRole(); 563 564 /// \brief After the \c TokenAnnotator has finished annotating all the tokens, 565 /// this function precomputes required information for formatting. 566 virtual void precomputeFormattingInfos(const FormatToken *Token); 567 568 /// \brief Apply the special formatting that the given role demands. 569 /// 570 /// Assumes that the token having this role is already formatted. 571 /// 572 /// Continues formatting from \p State leaving indentation to \p Indenter and 573 /// returns the total penalty that this formatting incurs. 574 virtual unsigned formatFromToken(LineState &State, 575 ContinuationIndenter *Indenter, 576 bool DryRun) { 577 return 0; 578 } 579 580 /// \brief Same as \c formatFromToken, but assumes that the first token has 581 /// already been set thereby deciding on the first line break. 582 virtual unsigned formatAfterToken(LineState &State, 583 ContinuationIndenter *Indenter, 584 bool DryRun) { 585 return 0; 586 } 587 588 /// \brief Notifies the \c Role that a comma was found. 589 virtual void CommaFound(const FormatToken *Token) {} 590 591 protected: 592 const FormatStyle &Style; 593 }; 594 595 class CommaSeparatedList : public TokenRole { 596 public: 597 CommaSeparatedList(const FormatStyle &Style) 598 : TokenRole(Style), HasNestedBracedList(false) {} 599 600 void precomputeFormattingInfos(const FormatToken *Token) override; 601 602 unsigned formatAfterToken(LineState &State, ContinuationIndenter *Indenter, 603 bool DryRun) override; 604 605 unsigned formatFromToken(LineState &State, ContinuationIndenter *Indenter, 606 bool DryRun) override; 607 608 /// \brief Adds \p Token as the next comma to the \c CommaSeparated list. 609 void CommaFound(const FormatToken *Token) override { 610 Commas.push_back(Token); 611 } 612 613 private: 614 /// \brief A struct that holds information on how to format a given list with 615 /// a specific number of columns. 616 struct ColumnFormat { 617 /// \brief The number of columns to use. 618 unsigned Columns; 619 620 /// \brief The total width in characters. 621 unsigned TotalWidth; 622 623 /// \brief The number of lines required for this format. 624 unsigned LineCount; 625 626 /// \brief The size of each column in characters. 627 SmallVector<unsigned, 8> ColumnSizes; 628 }; 629 630 /// \brief Calculate which \c ColumnFormat fits best into 631 /// \p RemainingCharacters. 632 const ColumnFormat *getColumnFormat(unsigned RemainingCharacters) const; 633 634 /// \brief The ordered \c FormatTokens making up the commas of this list. 635 SmallVector<const FormatToken *, 8> Commas; 636 637 /// \brief The length of each of the list's items in characters including the 638 /// trailing comma. 639 SmallVector<unsigned, 8> ItemLengths; 640 641 /// \brief Precomputed formats that can be used for this list. 642 SmallVector<ColumnFormat, 4> Formats; 643 644 bool HasNestedBracedList; 645 }; 646 647 /// \brief Encapsulates keywords that are context sensitive or for languages not 648 /// properly supported by Clang's lexer. 649 struct AdditionalKeywords { 650 AdditionalKeywords(IdentifierTable &IdentTable) { 651 kw_final = &IdentTable.get("final"); 652 kw_override = &IdentTable.get("override"); 653 kw_in = &IdentTable.get("in"); 654 kw_of = &IdentTable.get("of"); 655 kw_CF_ENUM = &IdentTable.get("CF_ENUM"); 656 kw_CF_OPTIONS = &IdentTable.get("CF_OPTIONS"); 657 kw_NS_ENUM = &IdentTable.get("NS_ENUM"); 658 kw_NS_OPTIONS = &IdentTable.get("NS_OPTIONS"); 659 660 kw_as = &IdentTable.get("as"); 661 kw_async = &IdentTable.get("async"); 662 kw_await = &IdentTable.get("await"); 663 kw_declare = &IdentTable.get("declare"); 664 kw_finally = &IdentTable.get("finally"); 665 kw_from = &IdentTable.get("from"); 666 kw_function = &IdentTable.get("function"); 667 kw_get = &IdentTable.get("get"); 668 kw_import = &IdentTable.get("import"); 669 kw_is = &IdentTable.get("is"); 670 kw_let = &IdentTable.get("let"); 671 kw_module = &IdentTable.get("module"); 672 kw_readonly = &IdentTable.get("readonly"); 673 kw_set = &IdentTable.get("set"); 674 kw_type = &IdentTable.get("type"); 675 kw_typeof = &IdentTable.get("typeof"); 676 kw_var = &IdentTable.get("var"); 677 kw_yield = &IdentTable.get("yield"); 678 679 kw_abstract = &IdentTable.get("abstract"); 680 kw_assert = &IdentTable.get("assert"); 681 kw_extends = &IdentTable.get("extends"); 682 kw_implements = &IdentTable.get("implements"); 683 kw_instanceof = &IdentTable.get("instanceof"); 684 kw_interface = &IdentTable.get("interface"); 685 kw_native = &IdentTable.get("native"); 686 kw_package = &IdentTable.get("package"); 687 kw_synchronized = &IdentTable.get("synchronized"); 688 kw_throws = &IdentTable.get("throws"); 689 kw___except = &IdentTable.get("__except"); 690 kw___has_include = &IdentTable.get("__has_include"); 691 kw___has_include_next = &IdentTable.get("__has_include_next"); 692 693 kw_mark = &IdentTable.get("mark"); 694 695 kw_extend = &IdentTable.get("extend"); 696 kw_option = &IdentTable.get("option"); 697 kw_optional = &IdentTable.get("optional"); 698 kw_repeated = &IdentTable.get("repeated"); 699 kw_required = &IdentTable.get("required"); 700 kw_returns = &IdentTable.get("returns"); 701 702 kw_signals = &IdentTable.get("signals"); 703 kw_qsignals = &IdentTable.get("Q_SIGNALS"); 704 kw_slots = &IdentTable.get("slots"); 705 kw_qslots = &IdentTable.get("Q_SLOTS"); 706 707 // Keep this at the end of the constructor to make sure everything here is 708 // already initialized. 709 JsExtraKeywords = std::unordered_set<IdentifierInfo *>( 710 {kw_as, kw_async, kw_await, kw_declare, kw_finally, kw_from, 711 kw_function, kw_get, kw_import, kw_is, kw_let, kw_module, kw_readonly, 712 kw_set, kw_type, kw_typeof, kw_var, kw_yield, 713 // Keywords from the Java section. 714 kw_abstract, kw_extends, kw_implements, kw_instanceof, kw_interface}); 715 } 716 717 // Context sensitive keywords. 718 IdentifierInfo *kw_final; 719 IdentifierInfo *kw_override; 720 IdentifierInfo *kw_in; 721 IdentifierInfo *kw_of; 722 IdentifierInfo *kw_CF_ENUM; 723 IdentifierInfo *kw_CF_OPTIONS; 724 IdentifierInfo *kw_NS_ENUM; 725 IdentifierInfo *kw_NS_OPTIONS; 726 IdentifierInfo *kw___except; 727 IdentifierInfo *kw___has_include; 728 IdentifierInfo *kw___has_include_next; 729 730 // JavaScript keywords. 731 IdentifierInfo *kw_as; 732 IdentifierInfo *kw_async; 733 IdentifierInfo *kw_await; 734 IdentifierInfo *kw_declare; 735 IdentifierInfo *kw_finally; 736 IdentifierInfo *kw_from; 737 IdentifierInfo *kw_function; 738 IdentifierInfo *kw_get; 739 IdentifierInfo *kw_import; 740 IdentifierInfo *kw_is; 741 IdentifierInfo *kw_let; 742 IdentifierInfo *kw_module; 743 IdentifierInfo *kw_readonly; 744 IdentifierInfo *kw_set; 745 IdentifierInfo *kw_type; 746 IdentifierInfo *kw_typeof; 747 IdentifierInfo *kw_var; 748 IdentifierInfo *kw_yield; 749 750 // Java keywords. 751 IdentifierInfo *kw_abstract; 752 IdentifierInfo *kw_assert; 753 IdentifierInfo *kw_extends; 754 IdentifierInfo *kw_implements; 755 IdentifierInfo *kw_instanceof; 756 IdentifierInfo *kw_interface; 757 IdentifierInfo *kw_native; 758 IdentifierInfo *kw_package; 759 IdentifierInfo *kw_synchronized; 760 IdentifierInfo *kw_throws; 761 762 // Pragma keywords. 763 IdentifierInfo *kw_mark; 764 765 // Proto keywords. 766 IdentifierInfo *kw_extend; 767 IdentifierInfo *kw_option; 768 IdentifierInfo *kw_optional; 769 IdentifierInfo *kw_repeated; 770 IdentifierInfo *kw_required; 771 IdentifierInfo *kw_returns; 772 773 // QT keywords. 774 IdentifierInfo *kw_signals; 775 IdentifierInfo *kw_qsignals; 776 IdentifierInfo *kw_slots; 777 IdentifierInfo *kw_qslots; 778 779 /// \brief Returns \c true if \p Tok is a true JavaScript identifier, returns 780 /// \c false if it is a keyword or a pseudo keyword. 781 bool IsJavaScriptIdentifier(const FormatToken &Tok) const { 782 return Tok.is(tok::identifier) && 783 JsExtraKeywords.find(Tok.Tok.getIdentifierInfo()) == 784 JsExtraKeywords.end(); 785 } 786 787 private: 788 /// \brief The JavaScript keywords beyond the C++ keyword set. 789 std::unordered_set<IdentifierInfo *> JsExtraKeywords; 790 }; 791 792 } // namespace format 793 } // namespace clang 794 795 #endif 796