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