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