1 //===--- ParseTentative.cpp - Ambiguity Resolution Parsing ----------------===// 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 // This file implements the tentative parsing portions of the Parser 10 // interfaces, for ambiguity resolution. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "clang/Parse/Parser.h" 15 #include "clang/Parse/ParseDiagnostic.h" 16 #include "clang/Sema/ParsedTemplate.h" 17 using namespace clang; 18 19 /// isCXXDeclarationStatement - C++-specialized function that disambiguates 20 /// between a declaration or an expression statement, when parsing function 21 /// bodies. Returns true for declaration, false for expression. 22 /// 23 /// declaration-statement: 24 /// block-declaration 25 /// 26 /// block-declaration: 27 /// simple-declaration 28 /// asm-definition 29 /// namespace-alias-definition 30 /// using-declaration 31 /// using-directive 32 /// [C++0x] static_assert-declaration 33 /// 34 /// asm-definition: 35 /// 'asm' '(' string-literal ')' ';' 36 /// 37 /// namespace-alias-definition: 38 /// 'namespace' identifier = qualified-namespace-specifier ';' 39 /// 40 /// using-declaration: 41 /// 'using' typename[opt] '::'[opt] nested-name-specifier 42 /// unqualified-id ';' 43 /// 'using' '::' unqualified-id ; 44 /// 45 /// using-directive: 46 /// 'using' 'namespace' '::'[opt] nested-name-specifier[opt] 47 /// namespace-name ';' 48 /// 49 bool Parser::isCXXDeclarationStatement() { 50 switch (Tok.getKind()) { 51 // asm-definition 52 case tok::kw_asm: 53 // namespace-alias-definition 54 case tok::kw_namespace: 55 // using-declaration 56 // using-directive 57 case tok::kw_using: 58 // static_assert-declaration 59 case tok::kw_static_assert: 60 case tok::kw__Static_assert: 61 return true; 62 // simple-declaration 63 default: 64 return isCXXSimpleDeclaration(/*AllowForRangeDecl=*/false); 65 } 66 } 67 68 /// isCXXSimpleDeclaration - C++-specialized function that disambiguates 69 /// between a simple-declaration or an expression-statement. 70 /// If during the disambiguation process a parsing error is encountered, 71 /// the function returns true to let the declaration parsing code handle it. 72 /// Returns false if the statement is disambiguated as expression. 73 /// 74 /// simple-declaration: 75 /// decl-specifier-seq init-declarator-list[opt] ';' 76 /// decl-specifier-seq ref-qualifier[opt] '[' identifier-list ']' 77 /// brace-or-equal-initializer ';' [C++17] 78 /// 79 /// (if AllowForRangeDecl specified) 80 /// for ( for-range-declaration : for-range-initializer ) statement 81 /// 82 /// for-range-declaration: 83 /// decl-specifier-seq declarator 84 /// decl-specifier-seq ref-qualifier[opt] '[' identifier-list ']' 85 /// 86 /// In any of the above cases there can be a preceding attribute-specifier-seq, 87 /// but the caller is expected to handle that. 88 bool Parser::isCXXSimpleDeclaration(bool AllowForRangeDecl) { 89 // C++ 6.8p1: 90 // There is an ambiguity in the grammar involving expression-statements and 91 // declarations: An expression-statement with a function-style explicit type 92 // conversion (5.2.3) as its leftmost subexpression can be indistinguishable 93 // from a declaration where the first declarator starts with a '('. In those 94 // cases the statement is a declaration. [Note: To disambiguate, the whole 95 // statement might have to be examined to determine if it is an 96 // expression-statement or a declaration]. 97 98 // C++ 6.8p3: 99 // The disambiguation is purely syntactic; that is, the meaning of the names 100 // occurring in such a statement, beyond whether they are type-names or not, 101 // is not generally used in or changed by the disambiguation. Class 102 // templates are instantiated as necessary to determine if a qualified name 103 // is a type-name. Disambiguation precedes parsing, and a statement 104 // disambiguated as a declaration may be an ill-formed declaration. 105 106 // We don't have to parse all of the decl-specifier-seq part. There's only 107 // an ambiguity if the first decl-specifier is 108 // simple-type-specifier/typename-specifier followed by a '(', which may 109 // indicate a function-style cast expression. 110 // isCXXDeclarationSpecifier will return TPResult::Ambiguous only in such 111 // a case. 112 113 bool InvalidAsDeclaration = false; 114 TPResult TPR = isCXXDeclarationSpecifier(TPResult::False, 115 &InvalidAsDeclaration); 116 if (TPR != TPResult::Ambiguous) 117 return TPR != TPResult::False; // Returns true for TPResult::True or 118 // TPResult::Error. 119 120 // FIXME: TryParseSimpleDeclaration doesn't look past the first initializer, 121 // and so gets some cases wrong. We can't carry on if we've already seen 122 // something which makes this statement invalid as a declaration in this case, 123 // since it can cause us to misparse valid code. Revisit this once 124 // TryParseInitDeclaratorList is fixed. 125 if (InvalidAsDeclaration) 126 return false; 127 128 // FIXME: Add statistics about the number of ambiguous statements encountered 129 // and how they were resolved (number of declarations+number of expressions). 130 131 // Ok, we have a simple-type-specifier/typename-specifier followed by a '(', 132 // or an identifier which doesn't resolve as anything. We need tentative 133 // parsing... 134 135 { 136 RevertingTentativeParsingAction PA(*this); 137 TPR = TryParseSimpleDeclaration(AllowForRangeDecl); 138 } 139 140 // In case of an error, let the declaration parsing code handle it. 141 if (TPR == TPResult::Error) 142 return true; 143 144 // Declarations take precedence over expressions. 145 if (TPR == TPResult::Ambiguous) 146 TPR = TPResult::True; 147 148 assert(TPR == TPResult::True || TPR == TPResult::False); 149 return TPR == TPResult::True; 150 } 151 152 /// Try to consume a token sequence that we've already identified as 153 /// (potentially) starting a decl-specifier. 154 Parser::TPResult Parser::TryConsumeDeclarationSpecifier() { 155 switch (Tok.getKind()) { 156 case tok::kw__Atomic: 157 if (NextToken().isNot(tok::l_paren)) { 158 ConsumeToken(); 159 break; 160 } 161 LLVM_FALLTHROUGH; 162 case tok::kw_typeof: 163 case tok::kw___attribute: 164 case tok::kw___underlying_type: { 165 ConsumeToken(); 166 if (Tok.isNot(tok::l_paren)) 167 return TPResult::Error; 168 ConsumeParen(); 169 if (!SkipUntil(tok::r_paren)) 170 return TPResult::Error; 171 break; 172 } 173 174 case tok::kw_class: 175 case tok::kw_struct: 176 case tok::kw_union: 177 case tok::kw___interface: 178 case tok::kw_enum: 179 // elaborated-type-specifier: 180 // class-key attribute-specifier-seq[opt] 181 // nested-name-specifier[opt] identifier 182 // class-key nested-name-specifier[opt] template[opt] simple-template-id 183 // enum nested-name-specifier[opt] identifier 184 // 185 // FIXME: We don't support class-specifiers nor enum-specifiers here. 186 ConsumeToken(); 187 188 // Skip attributes. 189 if (!TrySkipAttributes()) 190 return TPResult::Error; 191 192 if (TryAnnotateOptionalCXXScopeToken()) 193 return TPResult::Error; 194 if (Tok.is(tok::annot_cxxscope)) 195 ConsumeAnnotationToken(); 196 if (Tok.is(tok::identifier)) 197 ConsumeToken(); 198 else if (Tok.is(tok::annot_template_id)) 199 ConsumeAnnotationToken(); 200 else 201 return TPResult::Error; 202 break; 203 204 case tok::annot_cxxscope: 205 ConsumeAnnotationToken(); 206 LLVM_FALLTHROUGH; 207 default: 208 ConsumeAnyToken(); 209 210 if (getLangOpts().ObjC && Tok.is(tok::less)) 211 return TryParseProtocolQualifiers(); 212 break; 213 } 214 215 return TPResult::Ambiguous; 216 } 217 218 /// simple-declaration: 219 /// decl-specifier-seq init-declarator-list[opt] ';' 220 /// 221 /// (if AllowForRangeDecl specified) 222 /// for ( for-range-declaration : for-range-initializer ) statement 223 /// for-range-declaration: 224 /// attribute-specifier-seqopt type-specifier-seq declarator 225 /// 226 Parser::TPResult Parser::TryParseSimpleDeclaration(bool AllowForRangeDecl) { 227 if (TryConsumeDeclarationSpecifier() == TPResult::Error) 228 return TPResult::Error; 229 230 // Two decl-specifiers in a row conclusively disambiguate this as being a 231 // simple-declaration. Don't bother calling isCXXDeclarationSpecifier in the 232 // overwhelmingly common case that the next token is a '('. 233 if (Tok.isNot(tok::l_paren)) { 234 TPResult TPR = isCXXDeclarationSpecifier(); 235 if (TPR == TPResult::Ambiguous) 236 return TPResult::True; 237 if (TPR == TPResult::True || TPR == TPResult::Error) 238 return TPR; 239 assert(TPR == TPResult::False); 240 } 241 242 TPResult TPR = TryParseInitDeclaratorList(); 243 if (TPR != TPResult::Ambiguous) 244 return TPR; 245 246 if (Tok.isNot(tok::semi) && (!AllowForRangeDecl || Tok.isNot(tok::colon))) 247 return TPResult::False; 248 249 return TPResult::Ambiguous; 250 } 251 252 /// Tentatively parse an init-declarator-list in order to disambiguate it from 253 /// an expression. 254 /// 255 /// init-declarator-list: 256 /// init-declarator 257 /// init-declarator-list ',' init-declarator 258 /// 259 /// init-declarator: 260 /// declarator initializer[opt] 261 /// [GNU] declarator simple-asm-expr[opt] attributes[opt] initializer[opt] 262 /// 263 /// initializer: 264 /// brace-or-equal-initializer 265 /// '(' expression-list ')' 266 /// 267 /// brace-or-equal-initializer: 268 /// '=' initializer-clause 269 /// [C++11] braced-init-list 270 /// 271 /// initializer-clause: 272 /// assignment-expression 273 /// braced-init-list 274 /// 275 /// braced-init-list: 276 /// '{' initializer-list ','[opt] '}' 277 /// '{' '}' 278 /// 279 Parser::TPResult Parser::TryParseInitDeclaratorList() { 280 while (1) { 281 // declarator 282 TPResult TPR = TryParseDeclarator(false/*mayBeAbstract*/); 283 if (TPR != TPResult::Ambiguous) 284 return TPR; 285 286 // [GNU] simple-asm-expr[opt] attributes[opt] 287 if (Tok.isOneOf(tok::kw_asm, tok::kw___attribute)) 288 return TPResult::True; 289 290 // initializer[opt] 291 if (Tok.is(tok::l_paren)) { 292 // Parse through the parens. 293 ConsumeParen(); 294 if (!SkipUntil(tok::r_paren, StopAtSemi)) 295 return TPResult::Error; 296 } else if (Tok.is(tok::l_brace)) { 297 // A left-brace here is sufficient to disambiguate the parse; an 298 // expression can never be followed directly by a braced-init-list. 299 return TPResult::True; 300 } else if (Tok.is(tok::equal) || isTokIdentifier_in()) { 301 // MSVC and g++ won't examine the rest of declarators if '=' is 302 // encountered; they just conclude that we have a declaration. 303 // EDG parses the initializer completely, which is the proper behavior 304 // for this case. 305 // 306 // At present, Clang follows MSVC and g++, since the parser does not have 307 // the ability to parse an expression fully without recording the 308 // results of that parse. 309 // FIXME: Handle this case correctly. 310 // 311 // Also allow 'in' after an Objective-C declaration as in: 312 // for (int (^b)(void) in array). Ideally this should be done in the 313 // context of parsing for-init-statement of a foreach statement only. But, 314 // in any other context 'in' is invalid after a declaration and parser 315 // issues the error regardless of outcome of this decision. 316 // FIXME: Change if above assumption does not hold. 317 return TPResult::True; 318 } 319 320 if (!TryConsumeToken(tok::comma)) 321 break; 322 } 323 324 return TPResult::Ambiguous; 325 } 326 327 struct Parser::ConditionDeclarationOrInitStatementState { 328 Parser &P; 329 bool CanBeExpression = true; 330 bool CanBeCondition = true; 331 bool CanBeInitStatement; 332 bool CanBeForRangeDecl; 333 334 ConditionDeclarationOrInitStatementState(Parser &P, bool CanBeInitStatement, 335 bool CanBeForRangeDecl) 336 : P(P), CanBeInitStatement(CanBeInitStatement), 337 CanBeForRangeDecl(CanBeForRangeDecl) {} 338 339 bool resolved() { 340 return CanBeExpression + CanBeCondition + CanBeInitStatement + 341 CanBeForRangeDecl < 2; 342 } 343 344 void markNotExpression() { 345 CanBeExpression = false; 346 347 if (!resolved()) { 348 // FIXME: Unify the parsing codepaths for condition variables and 349 // simple-declarations so that we don't need to eagerly figure out which 350 // kind we have here. (Just parse init-declarators until we reach a 351 // semicolon or right paren.) 352 RevertingTentativeParsingAction PA(P); 353 if (CanBeForRangeDecl) { 354 // Skip until we hit a ')', ';', or a ':' with no matching '?'. 355 // The final case is a for range declaration, the rest are not. 356 while (true) { 357 unsigned QuestionColonDepth = 0; 358 P.SkipUntil({tok::r_paren, tok::semi, tok::question, tok::colon}, 359 StopBeforeMatch); 360 if (P.Tok.is(tok::question)) 361 ++QuestionColonDepth; 362 else if (P.Tok.is(tok::colon)) { 363 if (QuestionColonDepth) 364 --QuestionColonDepth; 365 else { 366 CanBeCondition = CanBeInitStatement = false; 367 return; 368 } 369 } else { 370 CanBeForRangeDecl = false; 371 break; 372 } 373 P.ConsumeToken(); 374 } 375 } else { 376 // Just skip until we hit a ')' or ';'. 377 P.SkipUntil(tok::r_paren, tok::semi, StopBeforeMatch); 378 } 379 if (P.Tok.isNot(tok::r_paren)) 380 CanBeCondition = CanBeForRangeDecl = false; 381 if (P.Tok.isNot(tok::semi)) 382 CanBeInitStatement = false; 383 } 384 } 385 386 bool markNotCondition() { 387 CanBeCondition = false; 388 return resolved(); 389 } 390 391 bool markNotForRangeDecl() { 392 CanBeForRangeDecl = false; 393 return resolved(); 394 } 395 396 bool update(TPResult IsDecl) { 397 switch (IsDecl) { 398 case TPResult::True: 399 markNotExpression(); 400 assert(resolved() && "can't continue after tentative parsing bails out"); 401 break; 402 case TPResult::False: 403 CanBeCondition = CanBeInitStatement = CanBeForRangeDecl = false; 404 break; 405 case TPResult::Ambiguous: 406 break; 407 case TPResult::Error: 408 CanBeExpression = CanBeCondition = CanBeInitStatement = 409 CanBeForRangeDecl = false; 410 break; 411 } 412 return resolved(); 413 } 414 415 ConditionOrInitStatement result() const { 416 assert(CanBeExpression + CanBeCondition + CanBeInitStatement + 417 CanBeForRangeDecl < 2 && 418 "result called but not yet resolved"); 419 if (CanBeExpression) 420 return ConditionOrInitStatement::Expression; 421 if (CanBeCondition) 422 return ConditionOrInitStatement::ConditionDecl; 423 if (CanBeInitStatement) 424 return ConditionOrInitStatement::InitStmtDecl; 425 if (CanBeForRangeDecl) 426 return ConditionOrInitStatement::ForRangeDecl; 427 return ConditionOrInitStatement::Error; 428 } 429 }; 430 431 /// Disambiguates between a declaration in a condition, a 432 /// simple-declaration in an init-statement, and an expression for 433 /// a condition of a if/switch statement. 434 /// 435 /// condition: 436 /// expression 437 /// type-specifier-seq declarator '=' assignment-expression 438 /// [C++11] type-specifier-seq declarator '=' initializer-clause 439 /// [C++11] type-specifier-seq declarator braced-init-list 440 /// [GNU] type-specifier-seq declarator simple-asm-expr[opt] attributes[opt] 441 /// '=' assignment-expression 442 /// simple-declaration: 443 /// decl-specifier-seq init-declarator-list[opt] ';' 444 /// 445 /// Note that, unlike isCXXSimpleDeclaration, we must disambiguate all the way 446 /// to the ';' to disambiguate cases like 'int(x))' (an expression) from 447 /// 'int(x);' (a simple-declaration in an init-statement). 448 Parser::ConditionOrInitStatement 449 Parser::isCXXConditionDeclarationOrInitStatement(bool CanBeInitStatement, 450 bool CanBeForRangeDecl) { 451 ConditionDeclarationOrInitStatementState State(*this, CanBeInitStatement, 452 CanBeForRangeDecl); 453 454 if (State.update(isCXXDeclarationSpecifier())) 455 return State.result(); 456 457 // It might be a declaration; we need tentative parsing. 458 RevertingTentativeParsingAction PA(*this); 459 460 // FIXME: A tag definition unambiguously tells us this is an init-statement. 461 if (State.update(TryConsumeDeclarationSpecifier())) 462 return State.result(); 463 assert(Tok.is(tok::l_paren) && "Expected '('"); 464 465 while (true) { 466 // Consume a declarator. 467 if (State.update(TryParseDeclarator(false/*mayBeAbstract*/))) 468 return State.result(); 469 470 // Attributes, asm label, or an initializer imply this is not an expression. 471 // FIXME: Disambiguate properly after an = instead of assuming that it's a 472 // valid declaration. 473 if (Tok.isOneOf(tok::equal, tok::kw_asm, tok::kw___attribute) || 474 (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace))) { 475 State.markNotExpression(); 476 return State.result(); 477 } 478 479 // A colon here identifies a for-range declaration. 480 if (State.CanBeForRangeDecl && Tok.is(tok::colon)) 481 return ConditionOrInitStatement::ForRangeDecl; 482 483 // At this point, it can't be a condition any more, because a condition 484 // must have a brace-or-equal-initializer. 485 if (State.markNotCondition()) 486 return State.result(); 487 488 // Likewise, it can't be a for-range declaration any more. 489 if (State.markNotForRangeDecl()) 490 return State.result(); 491 492 // A parenthesized initializer could be part of an expression or a 493 // simple-declaration. 494 if (Tok.is(tok::l_paren)) { 495 ConsumeParen(); 496 SkipUntil(tok::r_paren, StopAtSemi); 497 } 498 499 if (!TryConsumeToken(tok::comma)) 500 break; 501 } 502 503 // We reached the end. If it can now be some kind of decl, then it is. 504 if (State.CanBeCondition && Tok.is(tok::r_paren)) 505 return ConditionOrInitStatement::ConditionDecl; 506 else if (State.CanBeInitStatement && Tok.is(tok::semi)) 507 return ConditionOrInitStatement::InitStmtDecl; 508 else 509 return ConditionOrInitStatement::Expression; 510 } 511 512 /// Determine whether the next set of tokens contains a type-id. 513 /// 514 /// The context parameter states what context we're parsing right 515 /// now, which affects how this routine copes with the token 516 /// following the type-id. If the context is TypeIdInParens, we have 517 /// already parsed the '(' and we will cease lookahead when we hit 518 /// the corresponding ')'. If the context is 519 /// TypeIdAsTemplateArgument, we've already parsed the '<' or ',' 520 /// before this template argument, and will cease lookahead when we 521 /// hit a '>', '>>' (in C++0x), or ','; or, in C++0x, an ellipsis immediately 522 /// preceding such. Returns true for a type-id and false for an expression. 523 /// If during the disambiguation process a parsing error is encountered, 524 /// the function returns true to let the declaration parsing code handle it. 525 /// 526 /// type-id: 527 /// type-specifier-seq abstract-declarator[opt] 528 /// 529 bool Parser::isCXXTypeId(TentativeCXXTypeIdContext Context, bool &isAmbiguous) { 530 531 isAmbiguous = false; 532 533 // C++ 8.2p2: 534 // The ambiguity arising from the similarity between a function-style cast and 535 // a type-id can occur in different contexts. The ambiguity appears as a 536 // choice between a function-style cast expression and a declaration of a 537 // type. The resolution is that any construct that could possibly be a type-id 538 // in its syntactic context shall be considered a type-id. 539 540 TPResult TPR = isCXXDeclarationSpecifier(); 541 if (TPR != TPResult::Ambiguous) 542 return TPR != TPResult::False; // Returns true for TPResult::True or 543 // TPResult::Error. 544 545 // FIXME: Add statistics about the number of ambiguous statements encountered 546 // and how they were resolved (number of declarations+number of expressions). 547 548 // Ok, we have a simple-type-specifier/typename-specifier followed by a '('. 549 // We need tentative parsing... 550 551 RevertingTentativeParsingAction PA(*this); 552 553 // type-specifier-seq 554 TryConsumeDeclarationSpecifier(); 555 assert(Tok.is(tok::l_paren) && "Expected '('"); 556 557 // declarator 558 TPR = TryParseDeclarator(true/*mayBeAbstract*/, false/*mayHaveIdentifier*/); 559 560 // In case of an error, let the declaration parsing code handle it. 561 if (TPR == TPResult::Error) 562 TPR = TPResult::True; 563 564 if (TPR == TPResult::Ambiguous) { 565 // We are supposed to be inside parens, so if after the abstract declarator 566 // we encounter a ')' this is a type-id, otherwise it's an expression. 567 if (Context == TypeIdInParens && Tok.is(tok::r_paren)) { 568 TPR = TPResult::True; 569 isAmbiguous = true; 570 571 // We are supposed to be inside a template argument, so if after 572 // the abstract declarator we encounter a '>', '>>' (in C++0x), or 573 // ','; or, in C++0x, an ellipsis immediately preceding such, this 574 // is a type-id. Otherwise, it's an expression. 575 } else if (Context == TypeIdAsTemplateArgument && 576 (Tok.isOneOf(tok::greater, tok::comma) || 577 (getLangOpts().CPlusPlus11 && 578 (Tok.isOneOf(tok::greatergreater, 579 tok::greatergreatergreater) || 580 (Tok.is(tok::ellipsis) && 581 NextToken().isOneOf(tok::greater, tok::greatergreater, 582 tok::greatergreatergreater, 583 tok::comma)))))) { 584 TPR = TPResult::True; 585 isAmbiguous = true; 586 587 } else 588 TPR = TPResult::False; 589 } 590 591 assert(TPR == TPResult::True || TPR == TPResult::False); 592 return TPR == TPResult::True; 593 } 594 595 /// Returns true if this is a C++11 attribute-specifier. Per 596 /// C++11 [dcl.attr.grammar]p6, two consecutive left square bracket tokens 597 /// always introduce an attribute. In Objective-C++11, this rule does not 598 /// apply if either '[' begins a message-send. 599 /// 600 /// If Disambiguate is true, we try harder to determine whether a '[[' starts 601 /// an attribute-specifier, and return CAK_InvalidAttributeSpecifier if not. 602 /// 603 /// If OuterMightBeMessageSend is true, we assume the outer '[' is either an 604 /// Obj-C message send or the start of an attribute. Otherwise, we assume it 605 /// is not an Obj-C message send. 606 /// 607 /// C++11 [dcl.attr.grammar]: 608 /// 609 /// attribute-specifier: 610 /// '[' '[' attribute-list ']' ']' 611 /// alignment-specifier 612 /// 613 /// attribute-list: 614 /// attribute[opt] 615 /// attribute-list ',' attribute[opt] 616 /// attribute '...' 617 /// attribute-list ',' attribute '...' 618 /// 619 /// attribute: 620 /// attribute-token attribute-argument-clause[opt] 621 /// 622 /// attribute-token: 623 /// identifier 624 /// identifier '::' identifier 625 /// 626 /// attribute-argument-clause: 627 /// '(' balanced-token-seq ')' 628 Parser::CXX11AttributeKind 629 Parser::isCXX11AttributeSpecifier(bool Disambiguate, 630 bool OuterMightBeMessageSend) { 631 if (Tok.is(tok::kw_alignas)) 632 return CAK_AttributeSpecifier; 633 634 if (Tok.isNot(tok::l_square) || NextToken().isNot(tok::l_square)) 635 return CAK_NotAttributeSpecifier; 636 637 // No tentative parsing if we don't need to look for ']]' or a lambda. 638 if (!Disambiguate && !getLangOpts().ObjC) 639 return CAK_AttributeSpecifier; 640 641 // '[[using ns: ...]]' is an attribute. 642 if (GetLookAheadToken(2).is(tok::kw_using)) 643 return CAK_AttributeSpecifier; 644 645 RevertingTentativeParsingAction PA(*this); 646 647 // Opening brackets were checked for above. 648 ConsumeBracket(); 649 650 if (!getLangOpts().ObjC) { 651 ConsumeBracket(); 652 653 bool IsAttribute = SkipUntil(tok::r_square); 654 IsAttribute &= Tok.is(tok::r_square); 655 656 return IsAttribute ? CAK_AttributeSpecifier : CAK_InvalidAttributeSpecifier; 657 } 658 659 // In Obj-C++11, we need to distinguish four situations: 660 // 1a) int x[[attr]]; C++11 attribute. 661 // 1b) [[attr]]; C++11 statement attribute. 662 // 2) int x[[obj](){ return 1; }()]; Lambda in array size/index. 663 // 3a) int x[[obj get]]; Message send in array size/index. 664 // 3b) [[Class alloc] init]; Message send in message send. 665 // 4) [[obj]{ return self; }() doStuff]; Lambda in message send. 666 // (1) is an attribute, (2) is ill-formed, and (3) and (4) are accepted. 667 668 // Check to see if this is a lambda-expression. 669 // FIXME: If this disambiguation is too slow, fold the tentative lambda parse 670 // into the tentative attribute parse below. 671 { 672 RevertingTentativeParsingAction LambdaTPA(*this); 673 LambdaIntroducer Intro; 674 LambdaIntroducerTentativeParse Tentative; 675 if (ParseLambdaIntroducer(Intro, &Tentative)) { 676 // We hit a hard error after deciding this was not an attribute. 677 // FIXME: Don't parse and annotate expressions when disambiguating 678 // against an attribute. 679 return CAK_NotAttributeSpecifier; 680 } 681 682 switch (Tentative) { 683 case LambdaIntroducerTentativeParse::MessageSend: 684 // Case 3: The inner construct is definitely a message send, so the 685 // outer construct is definitely not an attribute. 686 return CAK_NotAttributeSpecifier; 687 688 case LambdaIntroducerTentativeParse::Success: 689 case LambdaIntroducerTentativeParse::Incomplete: 690 // This is a lambda-introducer or attribute-specifier. 691 if (Tok.is(tok::r_square)) 692 // Case 1: C++11 attribute. 693 return CAK_AttributeSpecifier; 694 695 if (OuterMightBeMessageSend) 696 // Case 4: Lambda in message send. 697 return CAK_NotAttributeSpecifier; 698 699 // Case 2: Lambda in array size / index. 700 return CAK_InvalidAttributeSpecifier; 701 702 case LambdaIntroducerTentativeParse::Invalid: 703 // No idea what this is; we couldn't parse it as a lambda-introducer. 704 // Might still be an attribute-specifier or a message send. 705 break; 706 } 707 } 708 709 ConsumeBracket(); 710 711 // If we don't have a lambda-introducer, then we have an attribute or a 712 // message-send. 713 bool IsAttribute = true; 714 while (Tok.isNot(tok::r_square)) { 715 if (Tok.is(tok::comma)) { 716 // Case 1: Stray commas can only occur in attributes. 717 return CAK_AttributeSpecifier; 718 } 719 720 // Parse the attribute-token, if present. 721 // C++11 [dcl.attr.grammar]: 722 // If a keyword or an alternative token that satisfies the syntactic 723 // requirements of an identifier is contained in an attribute-token, 724 // it is considered an identifier. 725 SourceLocation Loc; 726 if (!TryParseCXX11AttributeIdentifier(Loc)) { 727 IsAttribute = false; 728 break; 729 } 730 if (Tok.is(tok::coloncolon)) { 731 ConsumeToken(); 732 if (!TryParseCXX11AttributeIdentifier(Loc)) { 733 IsAttribute = false; 734 break; 735 } 736 } 737 738 // Parse the attribute-argument-clause, if present. 739 if (Tok.is(tok::l_paren)) { 740 ConsumeParen(); 741 if (!SkipUntil(tok::r_paren)) { 742 IsAttribute = false; 743 break; 744 } 745 } 746 747 TryConsumeToken(tok::ellipsis); 748 749 if (!TryConsumeToken(tok::comma)) 750 break; 751 } 752 753 // An attribute must end ']]'. 754 if (IsAttribute) { 755 if (Tok.is(tok::r_square)) { 756 ConsumeBracket(); 757 IsAttribute = Tok.is(tok::r_square); 758 } else { 759 IsAttribute = false; 760 } 761 } 762 763 if (IsAttribute) 764 // Case 1: C++11 statement attribute. 765 return CAK_AttributeSpecifier; 766 767 // Case 3: Message send. 768 return CAK_NotAttributeSpecifier; 769 } 770 771 bool Parser::TrySkipAttributes() { 772 while (Tok.isOneOf(tok::l_square, tok::kw___attribute, tok::kw___declspec, 773 tok::kw_alignas)) { 774 if (Tok.is(tok::l_square)) { 775 ConsumeBracket(); 776 if (Tok.isNot(tok::l_square)) 777 return false; 778 ConsumeBracket(); 779 if (!SkipUntil(tok::r_square) || Tok.isNot(tok::r_square)) 780 return false; 781 // Note that explicitly checking for `[[` and `]]` allows to fail as 782 // expected in the case of the Objective-C message send syntax. 783 ConsumeBracket(); 784 } else { 785 ConsumeToken(); 786 if (Tok.isNot(tok::l_paren)) 787 return false; 788 ConsumeParen(); 789 if (!SkipUntil(tok::r_paren)) 790 return false; 791 } 792 } 793 794 return true; 795 } 796 797 Parser::TPResult Parser::TryParsePtrOperatorSeq() { 798 while (true) { 799 if (TryAnnotateOptionalCXXScopeToken(true)) 800 return TPResult::Error; 801 802 if (Tok.isOneOf(tok::star, tok::amp, tok::caret, tok::ampamp) || 803 (Tok.is(tok::annot_cxxscope) && NextToken().is(tok::star))) { 804 // ptr-operator 805 ConsumeAnyToken(); 806 807 // Skip attributes. 808 if (!TrySkipAttributes()) 809 return TPResult::Error; 810 811 while (Tok.isOneOf(tok::kw_const, tok::kw_volatile, tok::kw_restrict, 812 tok::kw__Nonnull, tok::kw__Nullable, 813 tok::kw__Null_unspecified, tok::kw__Atomic)) 814 ConsumeToken(); 815 } else { 816 return TPResult::True; 817 } 818 } 819 } 820 821 /// operator-function-id: 822 /// 'operator' operator 823 /// 824 /// operator: one of 825 /// new delete new[] delete[] + - * / % ^ [...] 826 /// 827 /// conversion-function-id: 828 /// 'operator' conversion-type-id 829 /// 830 /// conversion-type-id: 831 /// type-specifier-seq conversion-declarator[opt] 832 /// 833 /// conversion-declarator: 834 /// ptr-operator conversion-declarator[opt] 835 /// 836 /// literal-operator-id: 837 /// 'operator' string-literal identifier 838 /// 'operator' user-defined-string-literal 839 Parser::TPResult Parser::TryParseOperatorId() { 840 assert(Tok.is(tok::kw_operator)); 841 ConsumeToken(); 842 843 // Maybe this is an operator-function-id. 844 switch (Tok.getKind()) { 845 case tok::kw_new: case tok::kw_delete: 846 ConsumeToken(); 847 if (Tok.is(tok::l_square) && NextToken().is(tok::r_square)) { 848 ConsumeBracket(); 849 ConsumeBracket(); 850 } 851 return TPResult::True; 852 853 #define OVERLOADED_OPERATOR(Name, Spelling, Token, Unary, Binary, MemOnly) \ 854 case tok::Token: 855 #define OVERLOADED_OPERATOR_MULTI(Name, Spelling, Unary, Binary, MemOnly) 856 #include "clang/Basic/OperatorKinds.def" 857 ConsumeToken(); 858 return TPResult::True; 859 860 case tok::l_square: 861 if (NextToken().is(tok::r_square)) { 862 ConsumeBracket(); 863 ConsumeBracket(); 864 return TPResult::True; 865 } 866 break; 867 868 case tok::l_paren: 869 if (NextToken().is(tok::r_paren)) { 870 ConsumeParen(); 871 ConsumeParen(); 872 return TPResult::True; 873 } 874 break; 875 876 default: 877 break; 878 } 879 880 // Maybe this is a literal-operator-id. 881 if (getLangOpts().CPlusPlus11 && isTokenStringLiteral()) { 882 bool FoundUDSuffix = false; 883 do { 884 FoundUDSuffix |= Tok.hasUDSuffix(); 885 ConsumeStringToken(); 886 } while (isTokenStringLiteral()); 887 888 if (!FoundUDSuffix) { 889 if (Tok.is(tok::identifier)) 890 ConsumeToken(); 891 else 892 return TPResult::Error; 893 } 894 return TPResult::True; 895 } 896 897 // Maybe this is a conversion-function-id. 898 bool AnyDeclSpecifiers = false; 899 while (true) { 900 TPResult TPR = isCXXDeclarationSpecifier(); 901 if (TPR == TPResult::Error) 902 return TPR; 903 if (TPR == TPResult::False) { 904 if (!AnyDeclSpecifiers) 905 return TPResult::Error; 906 break; 907 } 908 if (TryConsumeDeclarationSpecifier() == TPResult::Error) 909 return TPResult::Error; 910 AnyDeclSpecifiers = true; 911 } 912 return TryParsePtrOperatorSeq(); 913 } 914 915 /// declarator: 916 /// direct-declarator 917 /// ptr-operator declarator 918 /// 919 /// direct-declarator: 920 /// declarator-id 921 /// direct-declarator '(' parameter-declaration-clause ')' 922 /// cv-qualifier-seq[opt] exception-specification[opt] 923 /// direct-declarator '[' constant-expression[opt] ']' 924 /// '(' declarator ')' 925 /// [GNU] '(' attributes declarator ')' 926 /// 927 /// abstract-declarator: 928 /// ptr-operator abstract-declarator[opt] 929 /// direct-abstract-declarator 930 /// 931 /// direct-abstract-declarator: 932 /// direct-abstract-declarator[opt] 933 /// '(' parameter-declaration-clause ')' cv-qualifier-seq[opt] 934 /// exception-specification[opt] 935 /// direct-abstract-declarator[opt] '[' constant-expression[opt] ']' 936 /// '(' abstract-declarator ')' 937 /// [C++0x] ... 938 /// 939 /// ptr-operator: 940 /// '*' cv-qualifier-seq[opt] 941 /// '&' 942 /// [C++0x] '&&' [TODO] 943 /// '::'[opt] nested-name-specifier '*' cv-qualifier-seq[opt] 944 /// 945 /// cv-qualifier-seq: 946 /// cv-qualifier cv-qualifier-seq[opt] 947 /// 948 /// cv-qualifier: 949 /// 'const' 950 /// 'volatile' 951 /// 952 /// declarator-id: 953 /// '...'[opt] id-expression 954 /// 955 /// id-expression: 956 /// unqualified-id 957 /// qualified-id [TODO] 958 /// 959 /// unqualified-id: 960 /// identifier 961 /// operator-function-id 962 /// conversion-function-id 963 /// literal-operator-id 964 /// '~' class-name [TODO] 965 /// '~' decltype-specifier [TODO] 966 /// template-id [TODO] 967 /// 968 Parser::TPResult Parser::TryParseDeclarator(bool mayBeAbstract, 969 bool mayHaveIdentifier, 970 bool mayHaveDirectInit) { 971 // declarator: 972 // direct-declarator 973 // ptr-operator declarator 974 if (TryParsePtrOperatorSeq() == TPResult::Error) 975 return TPResult::Error; 976 977 // direct-declarator: 978 // direct-abstract-declarator: 979 if (Tok.is(tok::ellipsis)) 980 ConsumeToken(); 981 982 if ((Tok.isOneOf(tok::identifier, tok::kw_operator) || 983 (Tok.is(tok::annot_cxxscope) && (NextToken().is(tok::identifier) || 984 NextToken().is(tok::kw_operator)))) && 985 mayHaveIdentifier) { 986 // declarator-id 987 if (Tok.is(tok::annot_cxxscope)) { 988 CXXScopeSpec SS; 989 Actions.RestoreNestedNameSpecifierAnnotation( 990 Tok.getAnnotationValue(), Tok.getAnnotationRange(), SS); 991 if (SS.isInvalid()) 992 return TPResult::Error; 993 ConsumeAnnotationToken(); 994 } else if (Tok.is(tok::identifier)) { 995 TentativelyDeclaredIdentifiers.push_back(Tok.getIdentifierInfo()); 996 } 997 if (Tok.is(tok::kw_operator)) { 998 if (TryParseOperatorId() == TPResult::Error) 999 return TPResult::Error; 1000 } else 1001 ConsumeToken(); 1002 } else if (Tok.is(tok::l_paren)) { 1003 ConsumeParen(); 1004 if (mayBeAbstract && 1005 (Tok.is(tok::r_paren) || // 'int()' is a function. 1006 // 'int(...)' is a function. 1007 (Tok.is(tok::ellipsis) && NextToken().is(tok::r_paren)) || 1008 isDeclarationSpecifier())) { // 'int(int)' is a function. 1009 // '(' parameter-declaration-clause ')' cv-qualifier-seq[opt] 1010 // exception-specification[opt] 1011 TPResult TPR = TryParseFunctionDeclarator(); 1012 if (TPR != TPResult::Ambiguous) 1013 return TPR; 1014 } else { 1015 // '(' declarator ')' 1016 // '(' attributes declarator ')' 1017 // '(' abstract-declarator ')' 1018 if (Tok.isOneOf(tok::kw___attribute, tok::kw___declspec, tok::kw___cdecl, 1019 tok::kw___stdcall, tok::kw___fastcall, tok::kw___thiscall, 1020 tok::kw___regcall, tok::kw___vectorcall)) 1021 return TPResult::True; // attributes indicate declaration 1022 TPResult TPR = TryParseDeclarator(mayBeAbstract, mayHaveIdentifier); 1023 if (TPR != TPResult::Ambiguous) 1024 return TPR; 1025 if (Tok.isNot(tok::r_paren)) 1026 return TPResult::False; 1027 ConsumeParen(); 1028 } 1029 } else if (!mayBeAbstract) { 1030 return TPResult::False; 1031 } 1032 1033 if (mayHaveDirectInit) 1034 return TPResult::Ambiguous; 1035 1036 while (1) { 1037 TPResult TPR(TPResult::Ambiguous); 1038 1039 if (Tok.is(tok::l_paren)) { 1040 // Check whether we have a function declarator or a possible ctor-style 1041 // initializer that follows the declarator. Note that ctor-style 1042 // initializers are not possible in contexts where abstract declarators 1043 // are allowed. 1044 if (!mayBeAbstract && !isCXXFunctionDeclarator()) 1045 break; 1046 1047 // direct-declarator '(' parameter-declaration-clause ')' 1048 // cv-qualifier-seq[opt] exception-specification[opt] 1049 ConsumeParen(); 1050 TPR = TryParseFunctionDeclarator(); 1051 } else if (Tok.is(tok::l_square)) { 1052 // direct-declarator '[' constant-expression[opt] ']' 1053 // direct-abstract-declarator[opt] '[' constant-expression[opt] ']' 1054 TPR = TryParseBracketDeclarator(); 1055 } else if (Tok.is(tok::kw_requires)) { 1056 // declarator requires-clause 1057 // A requires clause indicates a function declaration. 1058 TPR = TPResult::True; 1059 } else { 1060 break; 1061 } 1062 1063 if (TPR != TPResult::Ambiguous) 1064 return TPR; 1065 } 1066 1067 return TPResult::Ambiguous; 1068 } 1069 1070 Parser::TPResult 1071 Parser::isExpressionOrTypeSpecifierSimple(tok::TokenKind Kind) { 1072 switch (Kind) { 1073 // Obviously starts an expression. 1074 case tok::numeric_constant: 1075 case tok::char_constant: 1076 case tok::wide_char_constant: 1077 case tok::utf8_char_constant: 1078 case tok::utf16_char_constant: 1079 case tok::utf32_char_constant: 1080 case tok::string_literal: 1081 case tok::wide_string_literal: 1082 case tok::utf8_string_literal: 1083 case tok::utf16_string_literal: 1084 case tok::utf32_string_literal: 1085 case tok::l_square: 1086 case tok::l_paren: 1087 case tok::amp: 1088 case tok::ampamp: 1089 case tok::star: 1090 case tok::plus: 1091 case tok::plusplus: 1092 case tok::minus: 1093 case tok::minusminus: 1094 case tok::tilde: 1095 case tok::exclaim: 1096 case tok::kw_sizeof: 1097 case tok::kw___func__: 1098 case tok::kw_const_cast: 1099 case tok::kw_delete: 1100 case tok::kw_dynamic_cast: 1101 case tok::kw_false: 1102 case tok::kw_new: 1103 case tok::kw_operator: 1104 case tok::kw_reinterpret_cast: 1105 case tok::kw_static_cast: 1106 case tok::kw_this: 1107 case tok::kw_throw: 1108 case tok::kw_true: 1109 case tok::kw_typeid: 1110 case tok::kw_alignof: 1111 case tok::kw_noexcept: 1112 case tok::kw_nullptr: 1113 case tok::kw__Alignof: 1114 case tok::kw___null: 1115 case tok::kw___alignof: 1116 case tok::kw___builtin_choose_expr: 1117 case tok::kw___builtin_offsetof: 1118 case tok::kw___builtin_va_arg: 1119 case tok::kw___imag: 1120 case tok::kw___real: 1121 case tok::kw___FUNCTION__: 1122 case tok::kw___FUNCDNAME__: 1123 case tok::kw___FUNCSIG__: 1124 case tok::kw_L__FUNCTION__: 1125 case tok::kw_L__FUNCSIG__: 1126 case tok::kw___PRETTY_FUNCTION__: 1127 case tok::kw___uuidof: 1128 case tok::kw___builtin_unique_stable_name: 1129 #define TYPE_TRAIT(N,Spelling,K) \ 1130 case tok::kw_##Spelling: 1131 #include "clang/Basic/TokenKinds.def" 1132 return TPResult::True; 1133 1134 // Obviously starts a type-specifier-seq: 1135 case tok::kw_char: 1136 case tok::kw_const: 1137 case tok::kw_double: 1138 case tok::kw__Float16: 1139 case tok::kw___float128: 1140 case tok::kw_enum: 1141 case tok::kw_half: 1142 case tok::kw_float: 1143 case tok::kw_int: 1144 case tok::kw__ExtInt: 1145 case tok::kw_long: 1146 case tok::kw___int64: 1147 case tok::kw___int128: 1148 case tok::kw_restrict: 1149 case tok::kw_short: 1150 case tok::kw_signed: 1151 case tok::kw_struct: 1152 case tok::kw_union: 1153 case tok::kw_unsigned: 1154 case tok::kw_void: 1155 case tok::kw_volatile: 1156 case tok::kw__Bool: 1157 case tok::kw__Complex: 1158 case tok::kw_class: 1159 case tok::kw_typename: 1160 case tok::kw_wchar_t: 1161 case tok::kw_char8_t: 1162 case tok::kw_char16_t: 1163 case tok::kw_char32_t: 1164 case tok::kw__Decimal32: 1165 case tok::kw__Decimal64: 1166 case tok::kw__Decimal128: 1167 case tok::kw___interface: 1168 case tok::kw___thread: 1169 case tok::kw_thread_local: 1170 case tok::kw__Thread_local: 1171 case tok::kw_typeof: 1172 case tok::kw___underlying_type: 1173 case tok::kw___cdecl: 1174 case tok::kw___stdcall: 1175 case tok::kw___fastcall: 1176 case tok::kw___thiscall: 1177 case tok::kw___regcall: 1178 case tok::kw___vectorcall: 1179 case tok::kw___unaligned: 1180 case tok::kw___vector: 1181 case tok::kw___pixel: 1182 case tok::kw___bool: 1183 case tok::kw__Atomic: 1184 #define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t: 1185 #include "clang/Basic/OpenCLImageTypes.def" 1186 case tok::kw___unknown_anytype: 1187 return TPResult::False; 1188 1189 default: 1190 break; 1191 } 1192 1193 return TPResult::Ambiguous; 1194 } 1195 1196 bool Parser::isTentativelyDeclared(IdentifierInfo *II) { 1197 return std::find(TentativelyDeclaredIdentifiers.begin(), 1198 TentativelyDeclaredIdentifiers.end(), II) 1199 != TentativelyDeclaredIdentifiers.end(); 1200 } 1201 1202 namespace { 1203 class TentativeParseCCC final : public CorrectionCandidateCallback { 1204 public: 1205 TentativeParseCCC(const Token &Next) { 1206 WantRemainingKeywords = false; 1207 WantTypeSpecifiers = Next.isOneOf(tok::l_paren, tok::r_paren, tok::greater, 1208 tok::l_brace, tok::identifier); 1209 } 1210 1211 bool ValidateCandidate(const TypoCorrection &Candidate) override { 1212 // Reject any candidate that only resolves to instance members since they 1213 // aren't viable as standalone identifiers instead of member references. 1214 if (Candidate.isResolved() && !Candidate.isKeyword() && 1215 llvm::all_of(Candidate, 1216 [](NamedDecl *ND) { return ND->isCXXInstanceMember(); })) 1217 return false; 1218 1219 return CorrectionCandidateCallback::ValidateCandidate(Candidate); 1220 } 1221 1222 std::unique_ptr<CorrectionCandidateCallback> clone() override { 1223 return std::make_unique<TentativeParseCCC>(*this); 1224 } 1225 }; 1226 } 1227 /// isCXXDeclarationSpecifier - Returns TPResult::True if it is a declaration 1228 /// specifier, TPResult::False if it is not, TPResult::Ambiguous if it could 1229 /// be either a decl-specifier or a function-style cast, and TPResult::Error 1230 /// if a parsing error was found and reported. 1231 /// 1232 /// If InvalidAsDeclSpec is not null, some cases that would be ill-formed as 1233 /// declaration specifiers but possibly valid as some other kind of construct 1234 /// return TPResult::Ambiguous instead of TPResult::False. When this happens, 1235 /// the intent is to keep trying to disambiguate, on the basis that we might 1236 /// find a better reason to treat this construct as a declaration later on. 1237 /// When this happens and the name could possibly be valid in some other 1238 /// syntactic context, *InvalidAsDeclSpec is set to 'true'. The current cases 1239 /// that trigger this are: 1240 /// 1241 /// * When parsing X::Y (with no 'typename') where X is dependent 1242 /// * When parsing X<Y> where X is undeclared 1243 /// 1244 /// decl-specifier: 1245 /// storage-class-specifier 1246 /// type-specifier 1247 /// function-specifier 1248 /// 'friend' 1249 /// 'typedef' 1250 /// [C++11] 'constexpr' 1251 /// [C++20] 'consteval' 1252 /// [GNU] attributes declaration-specifiers[opt] 1253 /// 1254 /// storage-class-specifier: 1255 /// 'register' 1256 /// 'static' 1257 /// 'extern' 1258 /// 'mutable' 1259 /// 'auto' 1260 /// [GNU] '__thread' 1261 /// [C++11] 'thread_local' 1262 /// [C11] '_Thread_local' 1263 /// 1264 /// function-specifier: 1265 /// 'inline' 1266 /// 'virtual' 1267 /// 'explicit' 1268 /// 1269 /// typedef-name: 1270 /// identifier 1271 /// 1272 /// type-specifier: 1273 /// simple-type-specifier 1274 /// class-specifier 1275 /// enum-specifier 1276 /// elaborated-type-specifier 1277 /// typename-specifier 1278 /// cv-qualifier 1279 /// 1280 /// simple-type-specifier: 1281 /// '::'[opt] nested-name-specifier[opt] type-name 1282 /// '::'[opt] nested-name-specifier 'template' 1283 /// simple-template-id [TODO] 1284 /// 'char' 1285 /// 'wchar_t' 1286 /// 'bool' 1287 /// 'short' 1288 /// 'int' 1289 /// 'long' 1290 /// 'signed' 1291 /// 'unsigned' 1292 /// 'float' 1293 /// 'double' 1294 /// 'void' 1295 /// [GNU] typeof-specifier 1296 /// [GNU] '_Complex' 1297 /// [C++11] 'auto' 1298 /// [GNU] '__auto_type' 1299 /// [C++11] 'decltype' ( expression ) 1300 /// [C++1y] 'decltype' ( 'auto' ) 1301 /// 1302 /// type-name: 1303 /// class-name 1304 /// enum-name 1305 /// typedef-name 1306 /// 1307 /// elaborated-type-specifier: 1308 /// class-key '::'[opt] nested-name-specifier[opt] identifier 1309 /// class-key '::'[opt] nested-name-specifier[opt] 'template'[opt] 1310 /// simple-template-id 1311 /// 'enum' '::'[opt] nested-name-specifier[opt] identifier 1312 /// 1313 /// enum-name: 1314 /// identifier 1315 /// 1316 /// enum-specifier: 1317 /// 'enum' identifier[opt] '{' enumerator-list[opt] '}' 1318 /// 'enum' identifier[opt] '{' enumerator-list ',' '}' 1319 /// 1320 /// class-specifier: 1321 /// class-head '{' member-specification[opt] '}' 1322 /// 1323 /// class-head: 1324 /// class-key identifier[opt] base-clause[opt] 1325 /// class-key nested-name-specifier identifier base-clause[opt] 1326 /// class-key nested-name-specifier[opt] simple-template-id 1327 /// base-clause[opt] 1328 /// 1329 /// class-key: 1330 /// 'class' 1331 /// 'struct' 1332 /// 'union' 1333 /// 1334 /// cv-qualifier: 1335 /// 'const' 1336 /// 'volatile' 1337 /// [GNU] restrict 1338 /// 1339 Parser::TPResult 1340 Parser::isCXXDeclarationSpecifier(Parser::TPResult BracedCastResult, 1341 bool *InvalidAsDeclSpec) { 1342 auto IsPlaceholderSpecifier = [&] (TemplateIdAnnotation *TemplateId, 1343 int Lookahead) { 1344 // We have a placeholder-constraint (we check for 'auto' or 'decltype' to 1345 // distinguish 'C<int>;' from 'C<int> auto c = 1;') 1346 return TemplateId->Kind == TNK_Concept_template && 1347 GetLookAheadToken(Lookahead + 1).isOneOf(tok::kw_auto, tok::kw_decltype, 1348 // If we have an identifier here, the user probably forgot the 1349 // 'auto' in the placeholder constraint, e.g. 'C<int> x = 2;' 1350 // This will be diagnosed nicely later, so disambiguate as a 1351 // declaration. 1352 tok::identifier); 1353 }; 1354 switch (Tok.getKind()) { 1355 case tok::identifier: { 1356 // Check for need to substitute AltiVec __vector keyword 1357 // for "vector" identifier. 1358 if (TryAltiVecVectorToken()) 1359 return TPResult::True; 1360 1361 const Token &Next = NextToken(); 1362 // In 'foo bar', 'foo' is always a type name outside of Objective-C. 1363 if (!getLangOpts().ObjC && Next.is(tok::identifier)) 1364 return TPResult::True; 1365 1366 if (Next.isNot(tok::coloncolon) && Next.isNot(tok::less)) { 1367 // Determine whether this is a valid expression. If not, we will hit 1368 // a parse error one way or another. In that case, tell the caller that 1369 // this is ambiguous. Typo-correct to type and expression keywords and 1370 // to types and identifiers, in order to try to recover from errors. 1371 TentativeParseCCC CCC(Next); 1372 switch (TryAnnotateName(&CCC)) { 1373 case ANK_Error: 1374 return TPResult::Error; 1375 case ANK_TentativeDecl: 1376 return TPResult::False; 1377 case ANK_TemplateName: 1378 // In C++17, this could be a type template for class template argument 1379 // deduction. Try to form a type annotation for it. If we're in a 1380 // template template argument, we'll undo this when checking the 1381 // validity of the argument. 1382 if (getLangOpts().CPlusPlus17) { 1383 if (TryAnnotateTypeOrScopeToken()) 1384 return TPResult::Error; 1385 if (Tok.isNot(tok::identifier)) 1386 break; 1387 } 1388 1389 // A bare type template-name which can't be a template template 1390 // argument is an error, and was probably intended to be a type. 1391 return GreaterThanIsOperator ? TPResult::True : TPResult::False; 1392 case ANK_Unresolved: 1393 return InvalidAsDeclSpec ? TPResult::Ambiguous : TPResult::False; 1394 case ANK_Success: 1395 break; 1396 } 1397 assert(Tok.isNot(tok::identifier) && 1398 "TryAnnotateName succeeded without producing an annotation"); 1399 } else { 1400 // This might possibly be a type with a dependent scope specifier and 1401 // a missing 'typename' keyword. Don't use TryAnnotateName in this case, 1402 // since it will annotate as a primary expression, and we want to use the 1403 // "missing 'typename'" logic. 1404 if (TryAnnotateTypeOrScopeToken()) 1405 return TPResult::Error; 1406 // If annotation failed, assume it's a non-type. 1407 // FIXME: If this happens due to an undeclared identifier, treat it as 1408 // ambiguous. 1409 if (Tok.is(tok::identifier)) 1410 return TPResult::False; 1411 } 1412 1413 // We annotated this token as something. Recurse to handle whatever we got. 1414 return isCXXDeclarationSpecifier(BracedCastResult, InvalidAsDeclSpec); 1415 } 1416 1417 case tok::kw_typename: // typename T::type 1418 // Annotate typenames and C++ scope specifiers. If we get one, just 1419 // recurse to handle whatever we get. 1420 if (TryAnnotateTypeOrScopeToken()) 1421 return TPResult::Error; 1422 return isCXXDeclarationSpecifier(BracedCastResult, InvalidAsDeclSpec); 1423 1424 case tok::coloncolon: { // ::foo::bar 1425 const Token &Next = NextToken(); 1426 if (Next.isOneOf(tok::kw_new, // ::new 1427 tok::kw_delete)) // ::delete 1428 return TPResult::False; 1429 LLVM_FALLTHROUGH; 1430 } 1431 case tok::kw___super: 1432 case tok::kw_decltype: 1433 // Annotate typenames and C++ scope specifiers. If we get one, just 1434 // recurse to handle whatever we get. 1435 if (TryAnnotateTypeOrScopeToken()) 1436 return TPResult::Error; 1437 return isCXXDeclarationSpecifier(BracedCastResult, InvalidAsDeclSpec); 1438 1439 // decl-specifier: 1440 // storage-class-specifier 1441 // type-specifier 1442 // function-specifier 1443 // 'friend' 1444 // 'typedef' 1445 // 'constexpr' 1446 case tok::kw_friend: 1447 case tok::kw_typedef: 1448 case tok::kw_constexpr: 1449 case tok::kw_consteval: 1450 case tok::kw_constinit: 1451 // storage-class-specifier 1452 case tok::kw_register: 1453 case tok::kw_static: 1454 case tok::kw_extern: 1455 case tok::kw_mutable: 1456 case tok::kw_auto: 1457 case tok::kw___thread: 1458 case tok::kw_thread_local: 1459 case tok::kw__Thread_local: 1460 // function-specifier 1461 case tok::kw_inline: 1462 case tok::kw_virtual: 1463 case tok::kw_explicit: 1464 1465 // Modules 1466 case tok::kw___module_private__: 1467 1468 // Debugger support 1469 case tok::kw___unknown_anytype: 1470 1471 // type-specifier: 1472 // simple-type-specifier 1473 // class-specifier 1474 // enum-specifier 1475 // elaborated-type-specifier 1476 // typename-specifier 1477 // cv-qualifier 1478 1479 // class-specifier 1480 // elaborated-type-specifier 1481 case tok::kw_class: 1482 case tok::kw_struct: 1483 case tok::kw_union: 1484 case tok::kw___interface: 1485 // enum-specifier 1486 case tok::kw_enum: 1487 // cv-qualifier 1488 case tok::kw_const: 1489 case tok::kw_volatile: 1490 return TPResult::True; 1491 1492 // OpenCL address space qualifiers 1493 case tok::kw_private: 1494 if (!getLangOpts().OpenCL) 1495 return TPResult::False; 1496 LLVM_FALLTHROUGH; 1497 case tok::kw___private: 1498 case tok::kw___local: 1499 case tok::kw___global: 1500 case tok::kw___constant: 1501 case tok::kw___generic: 1502 // OpenCL access qualifiers 1503 case tok::kw___read_only: 1504 case tok::kw___write_only: 1505 case tok::kw___read_write: 1506 // OpenCL pipe 1507 case tok::kw_pipe: 1508 1509 // GNU 1510 case tok::kw_restrict: 1511 case tok::kw__Complex: 1512 case tok::kw___attribute: 1513 case tok::kw___auto_type: 1514 return TPResult::True; 1515 1516 // Microsoft 1517 case tok::kw___declspec: 1518 case tok::kw___cdecl: 1519 case tok::kw___stdcall: 1520 case tok::kw___fastcall: 1521 case tok::kw___thiscall: 1522 case tok::kw___regcall: 1523 case tok::kw___vectorcall: 1524 case tok::kw___w64: 1525 case tok::kw___sptr: 1526 case tok::kw___uptr: 1527 case tok::kw___ptr64: 1528 case tok::kw___ptr32: 1529 case tok::kw___forceinline: 1530 case tok::kw___unaligned: 1531 case tok::kw__Nonnull: 1532 case tok::kw__Nullable: 1533 case tok::kw__Null_unspecified: 1534 case tok::kw___kindof: 1535 return TPResult::True; 1536 1537 // Borland 1538 case tok::kw___pascal: 1539 return TPResult::True; 1540 1541 // AltiVec 1542 case tok::kw___vector: 1543 return TPResult::True; 1544 1545 case tok::annot_template_id: { 1546 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok); 1547 // If lookup for the template-name found nothing, don't assume we have a 1548 // definitive disambiguation result yet. 1549 if ((TemplateId->hasInvalidName() || 1550 TemplateId->Kind == TNK_Undeclared_template) && 1551 InvalidAsDeclSpec) { 1552 // 'template-id(' can be a valid expression but not a valid decl spec if 1553 // the template-name is not declared, but we don't consider this to be a 1554 // definitive disambiguation. In any other context, it's an error either 1555 // way. 1556 *InvalidAsDeclSpec = NextToken().is(tok::l_paren); 1557 return TPResult::Ambiguous; 1558 } 1559 if (TemplateId->hasInvalidName()) 1560 return TPResult::Error; 1561 if (IsPlaceholderSpecifier(TemplateId, /*Lookahead=*/0)) 1562 return TPResult::True; 1563 if (TemplateId->Kind != TNK_Type_template) 1564 return TPResult::False; 1565 CXXScopeSpec SS; 1566 AnnotateTemplateIdTokenAsType(SS); 1567 assert(Tok.is(tok::annot_typename)); 1568 goto case_typename; 1569 } 1570 1571 case tok::annot_cxxscope: // foo::bar or ::foo::bar, but already parsed 1572 // We've already annotated a scope; try to annotate a type. 1573 if (TryAnnotateTypeOrScopeToken()) 1574 return TPResult::Error; 1575 if (!Tok.is(tok::annot_typename)) { 1576 if (Tok.is(tok::annot_cxxscope) && 1577 NextToken().is(tok::annot_template_id)) { 1578 TemplateIdAnnotation *TemplateId = 1579 takeTemplateIdAnnotation(NextToken()); 1580 if (TemplateId->hasInvalidName()) { 1581 if (InvalidAsDeclSpec) { 1582 *InvalidAsDeclSpec = NextToken().is(tok::l_paren); 1583 return TPResult::Ambiguous; 1584 } 1585 return TPResult::Error; 1586 } 1587 if (IsPlaceholderSpecifier(TemplateId, /*Lookahead=*/1)) 1588 return TPResult::True; 1589 } 1590 // If the next token is an identifier or a type qualifier, then this 1591 // can't possibly be a valid expression either. 1592 if (Tok.is(tok::annot_cxxscope) && NextToken().is(tok::identifier)) { 1593 CXXScopeSpec SS; 1594 Actions.RestoreNestedNameSpecifierAnnotation(Tok.getAnnotationValue(), 1595 Tok.getAnnotationRange(), 1596 SS); 1597 if (SS.getScopeRep() && SS.getScopeRep()->isDependent()) { 1598 RevertingTentativeParsingAction PA(*this); 1599 ConsumeAnnotationToken(); 1600 ConsumeToken(); 1601 bool isIdentifier = Tok.is(tok::identifier); 1602 TPResult TPR = TPResult::False; 1603 if (!isIdentifier) 1604 TPR = isCXXDeclarationSpecifier(BracedCastResult, 1605 InvalidAsDeclSpec); 1606 1607 if (isIdentifier || 1608 TPR == TPResult::True || TPR == TPResult::Error) 1609 return TPResult::Error; 1610 1611 if (InvalidAsDeclSpec) { 1612 // We can't tell whether this is a missing 'typename' or a valid 1613 // expression. 1614 *InvalidAsDeclSpec = true; 1615 return TPResult::Ambiguous; 1616 } else { 1617 // In MS mode, if InvalidAsDeclSpec is not provided, and the tokens 1618 // are or the form *) or &) *> or &> &&>, this can't be an expression. 1619 // The typename must be missing. 1620 if (getLangOpts().MSVCCompat) { 1621 if (((Tok.is(tok::amp) || Tok.is(tok::star)) && 1622 (NextToken().is(tok::r_paren) || 1623 NextToken().is(tok::greater))) || 1624 (Tok.is(tok::ampamp) && NextToken().is(tok::greater))) 1625 return TPResult::True; 1626 } 1627 } 1628 } else { 1629 // Try to resolve the name. If it doesn't exist, assume it was 1630 // intended to name a type and keep disambiguating. 1631 switch (TryAnnotateName()) { 1632 case ANK_Error: 1633 return TPResult::Error; 1634 case ANK_TentativeDecl: 1635 return TPResult::False; 1636 case ANK_TemplateName: 1637 // In C++17, this could be a type template for class template 1638 // argument deduction. 1639 if (getLangOpts().CPlusPlus17) { 1640 if (TryAnnotateTypeOrScopeToken()) 1641 return TPResult::Error; 1642 if (Tok.isNot(tok::identifier)) 1643 break; 1644 } 1645 1646 // A bare type template-name which can't be a template template 1647 // argument is an error, and was probably intended to be a type. 1648 // In C++17, this could be class template argument deduction. 1649 return (getLangOpts().CPlusPlus17 || GreaterThanIsOperator) 1650 ? TPResult::True 1651 : TPResult::False; 1652 case ANK_Unresolved: 1653 return InvalidAsDeclSpec ? TPResult::Ambiguous : TPResult::False; 1654 case ANK_Success: 1655 break; 1656 } 1657 1658 // Annotated it, check again. 1659 assert(Tok.isNot(tok::annot_cxxscope) || 1660 NextToken().isNot(tok::identifier)); 1661 return isCXXDeclarationSpecifier(BracedCastResult, InvalidAsDeclSpec); 1662 } 1663 } 1664 return TPResult::False; 1665 } 1666 // If that succeeded, fallthrough into the generic simple-type-id case. 1667 LLVM_FALLTHROUGH; 1668 1669 // The ambiguity resides in a simple-type-specifier/typename-specifier 1670 // followed by a '('. The '(' could either be the start of: 1671 // 1672 // direct-declarator: 1673 // '(' declarator ')' 1674 // 1675 // direct-abstract-declarator: 1676 // '(' parameter-declaration-clause ')' cv-qualifier-seq[opt] 1677 // exception-specification[opt] 1678 // '(' abstract-declarator ')' 1679 // 1680 // or part of a function-style cast expression: 1681 // 1682 // simple-type-specifier '(' expression-list[opt] ')' 1683 // 1684 1685 // simple-type-specifier: 1686 1687 case tok::annot_typename: 1688 case_typename: 1689 // In Objective-C, we might have a protocol-qualified type. 1690 if (getLangOpts().ObjC && NextToken().is(tok::less)) { 1691 // Tentatively parse the protocol qualifiers. 1692 RevertingTentativeParsingAction PA(*this); 1693 ConsumeAnyToken(); // The type token 1694 1695 TPResult TPR = TryParseProtocolQualifiers(); 1696 bool isFollowedByParen = Tok.is(tok::l_paren); 1697 bool isFollowedByBrace = Tok.is(tok::l_brace); 1698 1699 if (TPR == TPResult::Error) 1700 return TPResult::Error; 1701 1702 if (isFollowedByParen) 1703 return TPResult::Ambiguous; 1704 1705 if (getLangOpts().CPlusPlus11 && isFollowedByBrace) 1706 return BracedCastResult; 1707 1708 return TPResult::True; 1709 } 1710 LLVM_FALLTHROUGH; 1711 1712 case tok::kw_char: 1713 case tok::kw_wchar_t: 1714 case tok::kw_char8_t: 1715 case tok::kw_char16_t: 1716 case tok::kw_char32_t: 1717 case tok::kw_bool: 1718 case tok::kw_short: 1719 case tok::kw_int: 1720 case tok::kw_long: 1721 case tok::kw___int64: 1722 case tok::kw___int128: 1723 case tok::kw_signed: 1724 case tok::kw_unsigned: 1725 case tok::kw_half: 1726 case tok::kw_float: 1727 case tok::kw_double: 1728 case tok::kw__Float16: 1729 case tok::kw___float128: 1730 case tok::kw_void: 1731 case tok::annot_decltype: 1732 #define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t: 1733 #include "clang/Basic/OpenCLImageTypes.def" 1734 if (NextToken().is(tok::l_paren)) 1735 return TPResult::Ambiguous; 1736 1737 // This is a function-style cast in all cases we disambiguate other than 1738 // one: 1739 // struct S { 1740 // enum E : int { a = 4 }; // enum 1741 // enum E : int { 4 }; // bit-field 1742 // }; 1743 if (getLangOpts().CPlusPlus11 && NextToken().is(tok::l_brace)) 1744 return BracedCastResult; 1745 1746 if (isStartOfObjCClassMessageMissingOpenBracket()) 1747 return TPResult::False; 1748 1749 return TPResult::True; 1750 1751 // GNU typeof support. 1752 case tok::kw_typeof: { 1753 if (NextToken().isNot(tok::l_paren)) 1754 return TPResult::True; 1755 1756 RevertingTentativeParsingAction PA(*this); 1757 1758 TPResult TPR = TryParseTypeofSpecifier(); 1759 bool isFollowedByParen = Tok.is(tok::l_paren); 1760 bool isFollowedByBrace = Tok.is(tok::l_brace); 1761 1762 if (TPR == TPResult::Error) 1763 return TPResult::Error; 1764 1765 if (isFollowedByParen) 1766 return TPResult::Ambiguous; 1767 1768 if (getLangOpts().CPlusPlus11 && isFollowedByBrace) 1769 return BracedCastResult; 1770 1771 return TPResult::True; 1772 } 1773 1774 // C++0x type traits support 1775 case tok::kw___underlying_type: 1776 return TPResult::True; 1777 1778 // C11 _Atomic 1779 case tok::kw__Atomic: 1780 return TPResult::True; 1781 1782 case tok::kw__ExtInt: { 1783 if (NextToken().isNot(tok::l_paren)) 1784 return TPResult::Error; 1785 RevertingTentativeParsingAction PA(*this); 1786 ConsumeToken(); 1787 ConsumeParen(); 1788 1789 if (!SkipUntil(tok::r_paren, StopAtSemi)) 1790 return TPResult::Error; 1791 1792 if (Tok.is(tok::l_paren)) 1793 return TPResult::Ambiguous; 1794 1795 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) 1796 return BracedCastResult; 1797 1798 return TPResult::True; 1799 } 1800 default: 1801 return TPResult::False; 1802 } 1803 } 1804 1805 bool Parser::isCXXDeclarationSpecifierAType() { 1806 switch (Tok.getKind()) { 1807 // typename-specifier 1808 case tok::annot_decltype: 1809 case tok::annot_template_id: 1810 case tok::annot_typename: 1811 case tok::kw_typeof: 1812 case tok::kw___underlying_type: 1813 return true; 1814 1815 // elaborated-type-specifier 1816 case tok::kw_class: 1817 case tok::kw_struct: 1818 case tok::kw_union: 1819 case tok::kw___interface: 1820 case tok::kw_enum: 1821 return true; 1822 1823 // simple-type-specifier 1824 case tok::kw_char: 1825 case tok::kw_wchar_t: 1826 case tok::kw_char8_t: 1827 case tok::kw_char16_t: 1828 case tok::kw_char32_t: 1829 case tok::kw_bool: 1830 case tok::kw_short: 1831 case tok::kw_int: 1832 case tok::kw__ExtInt: 1833 case tok::kw_long: 1834 case tok::kw___int64: 1835 case tok::kw___int128: 1836 case tok::kw_signed: 1837 case tok::kw_unsigned: 1838 case tok::kw_half: 1839 case tok::kw_float: 1840 case tok::kw_double: 1841 case tok::kw__Float16: 1842 case tok::kw___float128: 1843 case tok::kw_void: 1844 case tok::kw___unknown_anytype: 1845 case tok::kw___auto_type: 1846 #define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t: 1847 #include "clang/Basic/OpenCLImageTypes.def" 1848 return true; 1849 1850 case tok::kw_auto: 1851 return getLangOpts().CPlusPlus11; 1852 1853 case tok::kw__Atomic: 1854 // "_Atomic foo" 1855 return NextToken().is(tok::l_paren); 1856 1857 default: 1858 return false; 1859 } 1860 } 1861 1862 /// [GNU] typeof-specifier: 1863 /// 'typeof' '(' expressions ')' 1864 /// 'typeof' '(' type-name ')' 1865 /// 1866 Parser::TPResult Parser::TryParseTypeofSpecifier() { 1867 assert(Tok.is(tok::kw_typeof) && "Expected 'typeof'!"); 1868 ConsumeToken(); 1869 1870 assert(Tok.is(tok::l_paren) && "Expected '('"); 1871 // Parse through the parens after 'typeof'. 1872 ConsumeParen(); 1873 if (!SkipUntil(tok::r_paren, StopAtSemi)) 1874 return TPResult::Error; 1875 1876 return TPResult::Ambiguous; 1877 } 1878 1879 /// [ObjC] protocol-qualifiers: 1880 //// '<' identifier-list '>' 1881 Parser::TPResult Parser::TryParseProtocolQualifiers() { 1882 assert(Tok.is(tok::less) && "Expected '<' for qualifier list"); 1883 ConsumeToken(); 1884 do { 1885 if (Tok.isNot(tok::identifier)) 1886 return TPResult::Error; 1887 ConsumeToken(); 1888 1889 if (Tok.is(tok::comma)) { 1890 ConsumeToken(); 1891 continue; 1892 } 1893 1894 if (Tok.is(tok::greater)) { 1895 ConsumeToken(); 1896 return TPResult::Ambiguous; 1897 } 1898 } while (false); 1899 1900 return TPResult::Error; 1901 } 1902 1903 /// isCXXFunctionDeclarator - Disambiguates between a function declarator or 1904 /// a constructor-style initializer, when parsing declaration statements. 1905 /// Returns true for function declarator and false for constructor-style 1906 /// initializer. 1907 /// If during the disambiguation process a parsing error is encountered, 1908 /// the function returns true to let the declaration parsing code handle it. 1909 /// 1910 /// '(' parameter-declaration-clause ')' cv-qualifier-seq[opt] 1911 /// exception-specification[opt] 1912 /// 1913 bool Parser::isCXXFunctionDeclarator(bool *IsAmbiguous) { 1914 1915 // C++ 8.2p1: 1916 // The ambiguity arising from the similarity between a function-style cast and 1917 // a declaration mentioned in 6.8 can also occur in the context of a 1918 // declaration. In that context, the choice is between a function declaration 1919 // with a redundant set of parentheses around a parameter name and an object 1920 // declaration with a function-style cast as the initializer. Just as for the 1921 // ambiguities mentioned in 6.8, the resolution is to consider any construct 1922 // that could possibly be a declaration a declaration. 1923 1924 RevertingTentativeParsingAction PA(*this); 1925 1926 ConsumeParen(); 1927 bool InvalidAsDeclaration = false; 1928 TPResult TPR = TryParseParameterDeclarationClause(&InvalidAsDeclaration); 1929 if (TPR == TPResult::Ambiguous) { 1930 if (Tok.isNot(tok::r_paren)) 1931 TPR = TPResult::False; 1932 else { 1933 const Token &Next = NextToken(); 1934 if (Next.isOneOf(tok::amp, tok::ampamp, tok::kw_const, tok::kw_volatile, 1935 tok::kw_throw, tok::kw_noexcept, tok::l_square, 1936 tok::l_brace, tok::kw_try, tok::equal, tok::arrow) || 1937 isCXX11VirtSpecifier(Next)) 1938 // The next token cannot appear after a constructor-style initializer, 1939 // and can appear next in a function definition. This must be a function 1940 // declarator. 1941 TPR = TPResult::True; 1942 else if (InvalidAsDeclaration) 1943 // Use the absence of 'typename' as a tie-breaker. 1944 TPR = TPResult::False; 1945 } 1946 } 1947 1948 if (IsAmbiguous && TPR == TPResult::Ambiguous) 1949 *IsAmbiguous = true; 1950 1951 // In case of an error, let the declaration parsing code handle it. 1952 return TPR != TPResult::False; 1953 } 1954 1955 /// parameter-declaration-clause: 1956 /// parameter-declaration-list[opt] '...'[opt] 1957 /// parameter-declaration-list ',' '...' 1958 /// 1959 /// parameter-declaration-list: 1960 /// parameter-declaration 1961 /// parameter-declaration-list ',' parameter-declaration 1962 /// 1963 /// parameter-declaration: 1964 /// attribute-specifier-seq[opt] decl-specifier-seq declarator attributes[opt] 1965 /// attribute-specifier-seq[opt] decl-specifier-seq declarator attributes[opt] 1966 /// '=' assignment-expression 1967 /// attribute-specifier-seq[opt] decl-specifier-seq abstract-declarator[opt] 1968 /// attributes[opt] 1969 /// attribute-specifier-seq[opt] decl-specifier-seq abstract-declarator[opt] 1970 /// attributes[opt] '=' assignment-expression 1971 /// 1972 Parser::TPResult 1973 Parser::TryParseParameterDeclarationClause(bool *InvalidAsDeclaration, 1974 bool VersusTemplateArgument) { 1975 1976 if (Tok.is(tok::r_paren)) 1977 return TPResult::Ambiguous; 1978 1979 // parameter-declaration-list[opt] '...'[opt] 1980 // parameter-declaration-list ',' '...' 1981 // 1982 // parameter-declaration-list: 1983 // parameter-declaration 1984 // parameter-declaration-list ',' parameter-declaration 1985 // 1986 while (1) { 1987 // '...'[opt] 1988 if (Tok.is(tok::ellipsis)) { 1989 ConsumeToken(); 1990 if (Tok.is(tok::r_paren)) 1991 return TPResult::True; // '...)' is a sign of a function declarator. 1992 else 1993 return TPResult::False; 1994 } 1995 1996 // An attribute-specifier-seq here is a sign of a function declarator. 1997 if (isCXX11AttributeSpecifier(/*Disambiguate*/false, 1998 /*OuterMightBeMessageSend*/true)) 1999 return TPResult::True; 2000 2001 ParsedAttributes attrs(AttrFactory); 2002 MaybeParseMicrosoftAttributes(attrs); 2003 2004 // decl-specifier-seq 2005 // A parameter-declaration's initializer must be preceded by an '=', so 2006 // decl-specifier-seq '{' is not a parameter in C++11. 2007 TPResult TPR = isCXXDeclarationSpecifier(TPResult::False, 2008 InvalidAsDeclaration); 2009 // A declaration-specifier (not followed by '(' or '{') means this can't be 2010 // an expression, but it could still be a template argument. 2011 if (TPR != TPResult::Ambiguous && 2012 !(VersusTemplateArgument && TPR == TPResult::True)) 2013 return TPR; 2014 2015 bool SeenType = false; 2016 do { 2017 SeenType |= isCXXDeclarationSpecifierAType(); 2018 if (TryConsumeDeclarationSpecifier() == TPResult::Error) 2019 return TPResult::Error; 2020 2021 // If we see a parameter name, this can't be a template argument. 2022 if (SeenType && Tok.is(tok::identifier)) 2023 return TPResult::True; 2024 2025 TPR = isCXXDeclarationSpecifier(TPResult::False, 2026 InvalidAsDeclaration); 2027 if (TPR == TPResult::Error) 2028 return TPR; 2029 2030 // Two declaration-specifiers means this can't be an expression. 2031 if (TPR == TPResult::True && !VersusTemplateArgument) 2032 return TPR; 2033 } while (TPR != TPResult::False); 2034 2035 // declarator 2036 // abstract-declarator[opt] 2037 TPR = TryParseDeclarator(true/*mayBeAbstract*/); 2038 if (TPR != TPResult::Ambiguous) 2039 return TPR; 2040 2041 // [GNU] attributes[opt] 2042 if (Tok.is(tok::kw___attribute)) 2043 return TPResult::True; 2044 2045 // If we're disambiguating a template argument in a default argument in 2046 // a class definition versus a parameter declaration, an '=' here 2047 // disambiguates the parse one way or the other. 2048 // If this is a parameter, it must have a default argument because 2049 // (a) the previous parameter did, and 2050 // (b) this must be the first declaration of the function, so we can't 2051 // inherit any default arguments from elsewhere. 2052 // FIXME: If we reach a ')' without consuming any '>'s, then this must 2053 // also be a function parameter (that's missing its default argument). 2054 if (VersusTemplateArgument) 2055 return Tok.is(tok::equal) ? TPResult::True : TPResult::False; 2056 2057 if (Tok.is(tok::equal)) { 2058 // '=' assignment-expression 2059 // Parse through assignment-expression. 2060 if (!SkipUntil(tok::comma, tok::r_paren, StopAtSemi | StopBeforeMatch)) 2061 return TPResult::Error; 2062 } 2063 2064 if (Tok.is(tok::ellipsis)) { 2065 ConsumeToken(); 2066 if (Tok.is(tok::r_paren)) 2067 return TPResult::True; // '...)' is a sign of a function declarator. 2068 else 2069 return TPResult::False; 2070 } 2071 2072 if (!TryConsumeToken(tok::comma)) 2073 break; 2074 } 2075 2076 return TPResult::Ambiguous; 2077 } 2078 2079 /// TryParseFunctionDeclarator - We parsed a '(' and we want to try to continue 2080 /// parsing as a function declarator. 2081 /// If TryParseFunctionDeclarator fully parsed the function declarator, it will 2082 /// return TPResult::Ambiguous, otherwise it will return either False() or 2083 /// Error(). 2084 /// 2085 /// '(' parameter-declaration-clause ')' cv-qualifier-seq[opt] 2086 /// exception-specification[opt] 2087 /// 2088 /// exception-specification: 2089 /// 'throw' '(' type-id-list[opt] ')' 2090 /// 2091 Parser::TPResult Parser::TryParseFunctionDeclarator() { 2092 // The '(' is already parsed. 2093 2094 TPResult TPR = TryParseParameterDeclarationClause(); 2095 if (TPR == TPResult::Ambiguous && Tok.isNot(tok::r_paren)) 2096 TPR = TPResult::False; 2097 2098 if (TPR == TPResult::False || TPR == TPResult::Error) 2099 return TPR; 2100 2101 // Parse through the parens. 2102 if (!SkipUntil(tok::r_paren, StopAtSemi)) 2103 return TPResult::Error; 2104 2105 // cv-qualifier-seq 2106 while (Tok.isOneOf(tok::kw_const, tok::kw_volatile, tok::kw___unaligned, 2107 tok::kw_restrict)) 2108 ConsumeToken(); 2109 2110 // ref-qualifier[opt] 2111 if (Tok.isOneOf(tok::amp, tok::ampamp)) 2112 ConsumeToken(); 2113 2114 // exception-specification 2115 if (Tok.is(tok::kw_throw)) { 2116 ConsumeToken(); 2117 if (Tok.isNot(tok::l_paren)) 2118 return TPResult::Error; 2119 2120 // Parse through the parens after 'throw'. 2121 ConsumeParen(); 2122 if (!SkipUntil(tok::r_paren, StopAtSemi)) 2123 return TPResult::Error; 2124 } 2125 if (Tok.is(tok::kw_noexcept)) { 2126 ConsumeToken(); 2127 // Possibly an expression as well. 2128 if (Tok.is(tok::l_paren)) { 2129 // Find the matching rparen. 2130 ConsumeParen(); 2131 if (!SkipUntil(tok::r_paren, StopAtSemi)) 2132 return TPResult::Error; 2133 } 2134 } 2135 2136 return TPResult::Ambiguous; 2137 } 2138 2139 /// '[' constant-expression[opt] ']' 2140 /// 2141 Parser::TPResult Parser::TryParseBracketDeclarator() { 2142 ConsumeBracket(); 2143 2144 // A constant-expression cannot begin with a '{', but the 2145 // expr-or-braced-init-list of a postfix-expression can. 2146 if (Tok.is(tok::l_brace)) 2147 return TPResult::False; 2148 2149 if (!SkipUntil(tok::r_square, tok::comma, StopAtSemi | StopBeforeMatch)) 2150 return TPResult::Error; 2151 2152 // If we hit a comma before the ']', this is not a constant-expression, 2153 // but might still be the expr-or-braced-init-list of a postfix-expression. 2154 if (Tok.isNot(tok::r_square)) 2155 return TPResult::False; 2156 2157 ConsumeBracket(); 2158 return TPResult::Ambiguous; 2159 } 2160 2161 /// Determine whether we might be looking at the '<' template-argument-list '>' 2162 /// of a template-id or simple-template-id, rather than a less-than comparison. 2163 /// This will often fail and produce an ambiguity, but should never be wrong 2164 /// if it returns True or False. 2165 Parser::TPResult Parser::isTemplateArgumentList(unsigned TokensToSkip) { 2166 if (!TokensToSkip) { 2167 if (Tok.isNot(tok::less)) 2168 return TPResult::False; 2169 if (NextToken().is(tok::greater)) 2170 return TPResult::True; 2171 } 2172 2173 RevertingTentativeParsingAction PA(*this); 2174 2175 while (TokensToSkip) { 2176 ConsumeAnyToken(); 2177 --TokensToSkip; 2178 } 2179 2180 if (!TryConsumeToken(tok::less)) 2181 return TPResult::False; 2182 2183 // We can't do much to tell an expression apart from a template-argument, 2184 // but one good distinguishing factor is that a "decl-specifier" not 2185 // followed by '(' or '{' can't appear in an expression. 2186 bool InvalidAsTemplateArgumentList = false; 2187 if (isCXXDeclarationSpecifier(TPResult::False, 2188 &InvalidAsTemplateArgumentList) == 2189 TPResult::True) 2190 return TPResult::True; 2191 if (InvalidAsTemplateArgumentList) 2192 return TPResult::False; 2193 2194 // FIXME: In many contexts, X<thing1, Type> can only be a 2195 // template-argument-list. But that's not true in general: 2196 // 2197 // using b = int; 2198 // void f() { 2199 // int a = A<B, b, c = C>D; // OK, declares b, not a template-id. 2200 // 2201 // X<Y<0, int> // ', int>' might be end of X's template argument list 2202 // 2203 // We might be able to disambiguate a few more cases if we're careful. 2204 2205 // A template-argument-list must be terminated by a '>'. 2206 if (SkipUntil({tok::greater, tok::greatergreater, tok::greatergreatergreater}, 2207 StopAtSemi | StopBeforeMatch)) 2208 return TPResult::Ambiguous; 2209 return TPResult::False; 2210 } 2211 2212 /// Determine whether we might be looking at the '(' of a C++20 explicit(bool) 2213 /// in an earlier language mode. 2214 Parser::TPResult Parser::isExplicitBool() { 2215 assert(Tok.is(tok::l_paren) && "expected to be looking at a '(' token"); 2216 2217 RevertingTentativeParsingAction PA(*this); 2218 ConsumeParen(); 2219 2220 // We can only have 'explicit' on a constructor, conversion function, or 2221 // deduction guide. The declarator of a deduction guide cannot be 2222 // parenthesized, so we know this isn't a deduction guide. So the only 2223 // thing we need to check for is some number of parens followed by either 2224 // the current class name or 'operator'. 2225 while (Tok.is(tok::l_paren)) 2226 ConsumeParen(); 2227 2228 if (TryAnnotateOptionalCXXScopeToken()) 2229 return TPResult::Error; 2230 2231 // Class-scope constructor and conversion function names can't really be 2232 // qualified, but we get better diagnostics if we assume they can be. 2233 CXXScopeSpec SS; 2234 if (Tok.is(tok::annot_cxxscope)) { 2235 Actions.RestoreNestedNameSpecifierAnnotation(Tok.getAnnotationValue(), 2236 Tok.getAnnotationRange(), 2237 SS); 2238 ConsumeAnnotationToken(); 2239 } 2240 2241 // 'explicit(operator' might be explicit(bool) or the declaration of a 2242 // conversion function, but it's probably a conversion function. 2243 if (Tok.is(tok::kw_operator)) 2244 return TPResult::Ambiguous; 2245 2246 // If this can't be a constructor name, it can only be explicit(bool). 2247 if (Tok.isNot(tok::identifier) && Tok.isNot(tok::annot_template_id)) 2248 return TPResult::True; 2249 if (!Actions.isCurrentClassName(Tok.is(tok::identifier) 2250 ? *Tok.getIdentifierInfo() 2251 : *takeTemplateIdAnnotation(Tok)->Name, 2252 getCurScope(), &SS)) 2253 return TPResult::True; 2254 // Formally, we must have a right-paren after the constructor name to match 2255 // the grammar for a constructor. But clang permits a parenthesized 2256 // constructor declarator, so also allow a constructor declarator to follow 2257 // with no ')' token after the constructor name. 2258 if (!NextToken().is(tok::r_paren) && 2259 !isConstructorDeclarator(/*Unqualified=*/SS.isEmpty(), 2260 /*DeductionGuide=*/false)) 2261 return TPResult::True; 2262 2263 // Might be explicit(bool) or a parenthesized constructor name. 2264 return TPResult::Ambiguous; 2265 } 2266