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