1 //===--- ParseTentative.cpp - Ambiguity Resolution Parsing ----------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file implements the tentative parsing portions of the Parser 11 // interfaces, for ambiguity resolution. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #include "clang/Parse/Parser.h" 16 #include "clang/Parse/ParseDiagnostic.h" 17 #include "clang/Sema/ParsedTemplate.h" 18 using namespace clang; 19 20 /// isCXXDeclarationStatement - C++-specialized function that disambiguates 21 /// between a declaration or an expression statement, when parsing function 22 /// bodies. Returns true for declaration, false for expression. 23 /// 24 /// declaration-statement: 25 /// block-declaration 26 /// 27 /// block-declaration: 28 /// simple-declaration 29 /// asm-definition 30 /// namespace-alias-definition 31 /// using-declaration 32 /// using-directive 33 /// [C++0x] static_assert-declaration 34 /// 35 /// asm-definition: 36 /// 'asm' '(' string-literal ')' ';' 37 /// 38 /// namespace-alias-definition: 39 /// 'namespace' identifier = qualified-namespace-specifier ';' 40 /// 41 /// using-declaration: 42 /// 'using' typename[opt] '::'[opt] nested-name-specifier 43 /// unqualified-id ';' 44 /// 'using' '::' unqualified-id ; 45 /// 46 /// using-directive: 47 /// 'using' 'namespace' '::'[opt] nested-name-specifier[opt] 48 /// namespace-name ';' 49 /// 50 bool Parser::isCXXDeclarationStatement() { 51 switch (Tok.getKind()) { 52 // asm-definition 53 case tok::kw_asm: 54 // namespace-alias-definition 55 case tok::kw_namespace: 56 // using-declaration 57 // using-directive 58 case tok::kw_using: 59 // static_assert-declaration 60 case tok::kw_static_assert: 61 case tok::kw__Static_assert: 62 return true; 63 // simple-declaration 64 default: 65 return isCXXSimpleDeclaration(/*AllowForRangeDecl=*/false); 66 } 67 } 68 69 /// isCXXSimpleDeclaration - C++-specialized function that disambiguates 70 /// between a simple-declaration or an expression-statement. 71 /// If during the disambiguation process a parsing error is encountered, 72 /// the function returns true to let the declaration parsing code handle it. 73 /// Returns false if the statement is disambiguated as expression. 74 /// 75 /// simple-declaration: 76 /// decl-specifier-seq init-declarator-list[opt] ';' 77 /// 78 /// (if AllowForRangeDecl specified) 79 /// for ( for-range-declaration : for-range-initializer ) statement 80 /// for-range-declaration: 81 /// attribute-specifier-seqopt type-specifier-seq declarator 82 bool Parser::isCXXSimpleDeclaration(bool AllowForRangeDecl) { 83 // C++ 6.8p1: 84 // There is an ambiguity in the grammar involving expression-statements and 85 // declarations: An expression-statement with a function-style explicit type 86 // conversion (5.2.3) as its leftmost subexpression can be indistinguishable 87 // from a declaration where the first declarator starts with a '('. In those 88 // cases the statement is a declaration. [Note: To disambiguate, the whole 89 // statement might have to be examined to determine if it is an 90 // expression-statement or a declaration]. 91 92 // C++ 6.8p3: 93 // The disambiguation is purely syntactic; that is, the meaning of the names 94 // occurring in such a statement, beyond whether they are type-names or not, 95 // is not generally used in or changed by the disambiguation. Class 96 // templates are instantiated as necessary to determine if a qualified name 97 // is a type-name. Disambiguation precedes parsing, and a statement 98 // disambiguated as a declaration may be an ill-formed declaration. 99 100 // We don't have to parse all of the decl-specifier-seq part. There's only 101 // an ambiguity if the first decl-specifier is 102 // simple-type-specifier/typename-specifier followed by a '(', which may 103 // indicate a function-style cast expression. 104 // isCXXDeclarationSpecifier will return TPResult::Ambiguous() only in such 105 // a case. 106 107 bool InvalidAsDeclaration = false; 108 TPResult TPR = isCXXDeclarationSpecifier(TPResult::False(), 109 &InvalidAsDeclaration); 110 if (TPR != TPResult::Ambiguous()) 111 return TPR != TPResult::False(); // Returns true for TPResult::True() or 112 // TPResult::Error(). 113 114 // FIXME: TryParseSimpleDeclaration doesn't look past the first initializer, 115 // and so gets some cases wrong. We can't carry on if we've already seen 116 // something which makes this statement invalid as a declaration in this case, 117 // since it can cause us to misparse valid code. Revisit this once 118 // TryParseInitDeclaratorList is fixed. 119 if (InvalidAsDeclaration) 120 return false; 121 122 // FIXME: Add statistics about the number of ambiguous statements encountered 123 // and how they were resolved (number of declarations+number of expressions). 124 125 // Ok, we have a simple-type-specifier/typename-specifier followed by a '(', 126 // or an identifier which doesn't resolve as anything. We need tentative 127 // parsing... 128 129 TentativeParsingAction PA(*this); 130 TPR = TryParseSimpleDeclaration(AllowForRangeDecl); 131 PA.Revert(); 132 133 // In case of an error, let the declaration parsing code handle it. 134 if (TPR == TPResult::Error()) 135 return true; 136 137 // Declarations take precedence over expressions. 138 if (TPR == TPResult::Ambiguous()) 139 TPR = TPResult::True(); 140 141 assert(TPR == TPResult::True() || TPR == TPResult::False()); 142 return TPR == TPResult::True(); 143 } 144 145 /// simple-declaration: 146 /// decl-specifier-seq init-declarator-list[opt] ';' 147 /// 148 /// (if AllowForRangeDecl specified) 149 /// for ( for-range-declaration : for-range-initializer ) statement 150 /// for-range-declaration: 151 /// attribute-specifier-seqopt type-specifier-seq declarator 152 /// 153 Parser::TPResult Parser::TryParseSimpleDeclaration(bool AllowForRangeDecl) { 154 if (Tok.is(tok::kw_typeof)) 155 TryParseTypeofSpecifier(); 156 else { 157 if (Tok.is(tok::annot_cxxscope)) 158 ConsumeToken(); 159 ConsumeToken(); 160 161 if (getLangOpts().ObjC1 && Tok.is(tok::less)) 162 TryParseProtocolQualifiers(); 163 } 164 165 // Two decl-specifiers in a row conclusively disambiguate this as being a 166 // simple-declaration. Don't bother calling isCXXDeclarationSpecifier in the 167 // overwhelmingly common case that the next token is a '('. 168 if (Tok.isNot(tok::l_paren)) { 169 TPResult TPR = isCXXDeclarationSpecifier(); 170 if (TPR == TPResult::Ambiguous()) 171 return TPResult::True(); 172 if (TPR == TPResult::True() || TPR == TPResult::Error()) 173 return TPR; 174 assert(TPR == TPResult::False()); 175 } 176 177 TPResult TPR = TryParseInitDeclaratorList(); 178 if (TPR != TPResult::Ambiguous()) 179 return TPR; 180 181 if (Tok.isNot(tok::semi) && (!AllowForRangeDecl || Tok.isNot(tok::colon))) 182 return TPResult::False(); 183 184 return TPResult::Ambiguous(); 185 } 186 187 /// Tentatively parse an init-declarator-list in order to disambiguate it from 188 /// an expression. 189 /// 190 /// init-declarator-list: 191 /// init-declarator 192 /// init-declarator-list ',' init-declarator 193 /// 194 /// init-declarator: 195 /// declarator initializer[opt] 196 /// [GNU] declarator simple-asm-expr[opt] attributes[opt] initializer[opt] 197 /// 198 /// initializer: 199 /// brace-or-equal-initializer 200 /// '(' expression-list ')' 201 /// 202 /// brace-or-equal-initializer: 203 /// '=' initializer-clause 204 /// [C++11] braced-init-list 205 /// 206 /// initializer-clause: 207 /// assignment-expression 208 /// braced-init-list 209 /// 210 /// braced-init-list: 211 /// '{' initializer-list ','[opt] '}' 212 /// '{' '}' 213 /// 214 Parser::TPResult Parser::TryParseInitDeclaratorList() { 215 while (1) { 216 // declarator 217 TPResult TPR = TryParseDeclarator(false/*mayBeAbstract*/); 218 if (TPR != TPResult::Ambiguous()) 219 return TPR; 220 221 // [GNU] simple-asm-expr[opt] attributes[opt] 222 if (Tok.is(tok::kw_asm) || Tok.is(tok::kw___attribute)) 223 return TPResult::True(); 224 225 // initializer[opt] 226 if (Tok.is(tok::l_paren)) { 227 // Parse through the parens. 228 ConsumeParen(); 229 if (!SkipUntil(tok::r_paren)) 230 return TPResult::Error(); 231 } else if (Tok.is(tok::l_brace)) { 232 // A left-brace here is sufficient to disambiguate the parse; an 233 // expression can never be followed directly by a braced-init-list. 234 return TPResult::True(); 235 } else if (Tok.is(tok::equal) || isTokIdentifier_in()) { 236 // MSVC and g++ won't examine the rest of declarators if '=' is 237 // encountered; they just conclude that we have a declaration. 238 // EDG parses the initializer completely, which is the proper behavior 239 // for this case. 240 // 241 // At present, Clang follows MSVC and g++, since the parser does not have 242 // the ability to parse an expression fully without recording the 243 // results of that parse. 244 // Also allow 'in' after on objective-c declaration as in: 245 // for (int (^b)(void) in array). Ideally this should be done in the 246 // context of parsing for-init-statement of a foreach statement only. But, 247 // in any other context 'in' is invalid after a declaration and parser 248 // issues the error regardless of outcome of this decision. 249 // FIXME. Change if above assumption does not hold. 250 return TPResult::True(); 251 } 252 253 if (Tok.isNot(tok::comma)) 254 break; 255 ConsumeToken(); // the comma. 256 } 257 258 return TPResult::Ambiguous(); 259 } 260 261 /// isCXXConditionDeclaration - Disambiguates between a declaration or an 262 /// expression for a condition of a if/switch/while/for statement. 263 /// If during the disambiguation process a parsing error is encountered, 264 /// the function returns true to let the declaration parsing code handle it. 265 /// 266 /// condition: 267 /// expression 268 /// type-specifier-seq declarator '=' assignment-expression 269 /// [C++11] type-specifier-seq declarator '=' initializer-clause 270 /// [C++11] type-specifier-seq declarator braced-init-list 271 /// [GNU] type-specifier-seq declarator simple-asm-expr[opt] attributes[opt] 272 /// '=' assignment-expression 273 /// 274 bool Parser::isCXXConditionDeclaration() { 275 TPResult TPR = isCXXDeclarationSpecifier(); 276 if (TPR != TPResult::Ambiguous()) 277 return TPR != TPResult::False(); // Returns true for TPResult::True() or 278 // TPResult::Error(). 279 280 // FIXME: Add statistics about the number of ambiguous statements encountered 281 // and how they were resolved (number of declarations+number of expressions). 282 283 // Ok, we have a simple-type-specifier/typename-specifier followed by a '('. 284 // We need tentative parsing... 285 286 TentativeParsingAction PA(*this); 287 288 // type-specifier-seq 289 if (Tok.is(tok::kw_typeof)) 290 TryParseTypeofSpecifier(); 291 else { 292 ConsumeToken(); 293 294 if (getLangOpts().ObjC1 && Tok.is(tok::less)) 295 TryParseProtocolQualifiers(); 296 } 297 assert(Tok.is(tok::l_paren) && "Expected '('"); 298 299 // declarator 300 TPR = TryParseDeclarator(false/*mayBeAbstract*/); 301 302 // In case of an error, let the declaration parsing code handle it. 303 if (TPR == TPResult::Error()) 304 TPR = TPResult::True(); 305 306 if (TPR == TPResult::Ambiguous()) { 307 // '=' 308 // [GNU] simple-asm-expr[opt] attributes[opt] 309 if (Tok.is(tok::equal) || 310 Tok.is(tok::kw_asm) || Tok.is(tok::kw___attribute)) 311 TPR = TPResult::True(); 312 else if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) 313 TPR = TPResult::True(); 314 else 315 TPR = TPResult::False(); 316 } 317 318 PA.Revert(); 319 320 assert(TPR == TPResult::True() || TPR == TPResult::False()); 321 return TPR == TPResult::True(); 322 } 323 324 /// \brief Determine whether the next set of tokens contains a type-id. 325 /// 326 /// The context parameter states what context we're parsing right 327 /// now, which affects how this routine copes with the token 328 /// following the type-id. If the context is TypeIdInParens, we have 329 /// already parsed the '(' and we will cease lookahead when we hit 330 /// the corresponding ')'. If the context is 331 /// TypeIdAsTemplateArgument, we've already parsed the '<' or ',' 332 /// before this template argument, and will cease lookahead when we 333 /// hit a '>', '>>' (in C++0x), or ','. Returns true for a type-id 334 /// and false for an expression. If during the disambiguation 335 /// process a parsing error is encountered, the function returns 336 /// true to let the declaration parsing code handle it. 337 /// 338 /// type-id: 339 /// type-specifier-seq abstract-declarator[opt] 340 /// 341 bool Parser::isCXXTypeId(TentativeCXXTypeIdContext Context, bool &isAmbiguous) { 342 343 isAmbiguous = false; 344 345 // C++ 8.2p2: 346 // The ambiguity arising from the similarity between a function-style cast and 347 // a type-id can occur in different contexts. The ambiguity appears as a 348 // choice between a function-style cast expression and a declaration of a 349 // type. The resolution is that any construct that could possibly be a type-id 350 // in its syntactic context shall be considered a type-id. 351 352 TPResult TPR = isCXXDeclarationSpecifier(); 353 if (TPR != TPResult::Ambiguous()) 354 return TPR != TPResult::False(); // Returns true for TPResult::True() or 355 // TPResult::Error(). 356 357 // FIXME: Add statistics about the number of ambiguous statements encountered 358 // and how they were resolved (number of declarations+number of expressions). 359 360 // Ok, we have a simple-type-specifier/typename-specifier followed by a '('. 361 // We need tentative parsing... 362 363 TentativeParsingAction PA(*this); 364 365 // type-specifier-seq 366 if (Tok.is(tok::kw_typeof)) 367 TryParseTypeofSpecifier(); 368 else { 369 ConsumeToken(); 370 371 if (getLangOpts().ObjC1 && Tok.is(tok::less)) 372 TryParseProtocolQualifiers(); 373 } 374 375 assert(Tok.is(tok::l_paren) && "Expected '('"); 376 377 // declarator 378 TPR = TryParseDeclarator(true/*mayBeAbstract*/, false/*mayHaveIdentifier*/); 379 380 // In case of an error, let the declaration parsing code handle it. 381 if (TPR == TPResult::Error()) 382 TPR = TPResult::True(); 383 384 if (TPR == TPResult::Ambiguous()) { 385 // We are supposed to be inside parens, so if after the abstract declarator 386 // we encounter a ')' this is a type-id, otherwise it's an expression. 387 if (Context == TypeIdInParens && Tok.is(tok::r_paren)) { 388 TPR = TPResult::True(); 389 isAmbiguous = true; 390 391 // We are supposed to be inside a template argument, so if after 392 // the abstract declarator we encounter a '>', '>>' (in C++0x), or 393 // ',', this is a type-id. Otherwise, it's an expression. 394 } else if (Context == TypeIdAsTemplateArgument && 395 (Tok.is(tok::greater) || Tok.is(tok::comma) || 396 (getLangOpts().CPlusPlus11 && Tok.is(tok::greatergreater)))) { 397 TPR = TPResult::True(); 398 isAmbiguous = true; 399 400 } else 401 TPR = TPResult::False(); 402 } 403 404 PA.Revert(); 405 406 assert(TPR == TPResult::True() || TPR == TPResult::False()); 407 return TPR == TPResult::True(); 408 } 409 410 /// \brief Returns true if this is a C++11 attribute-specifier. Per 411 /// C++11 [dcl.attr.grammar]p6, two consecutive left square bracket tokens 412 /// always introduce an attribute. In Objective-C++11, this rule does not 413 /// apply if either '[' begins a message-send. 414 /// 415 /// If Disambiguate is true, we try harder to determine whether a '[[' starts 416 /// an attribute-specifier, and return CAK_InvalidAttributeSpecifier if not. 417 /// 418 /// If OuterMightBeMessageSend is true, we assume the outer '[' is either an 419 /// Obj-C message send or the start of an attribute. Otherwise, we assume it 420 /// is not an Obj-C message send. 421 /// 422 /// C++11 [dcl.attr.grammar]: 423 /// 424 /// attribute-specifier: 425 /// '[' '[' attribute-list ']' ']' 426 /// alignment-specifier 427 /// 428 /// attribute-list: 429 /// attribute[opt] 430 /// attribute-list ',' attribute[opt] 431 /// attribute '...' 432 /// attribute-list ',' attribute '...' 433 /// 434 /// attribute: 435 /// attribute-token attribute-argument-clause[opt] 436 /// 437 /// attribute-token: 438 /// identifier 439 /// identifier '::' identifier 440 /// 441 /// attribute-argument-clause: 442 /// '(' balanced-token-seq ')' 443 Parser::CXX11AttributeKind 444 Parser::isCXX11AttributeSpecifier(bool Disambiguate, 445 bool OuterMightBeMessageSend) { 446 if (Tok.is(tok::kw_alignas)) 447 return CAK_AttributeSpecifier; 448 449 if (Tok.isNot(tok::l_square) || NextToken().isNot(tok::l_square)) 450 return CAK_NotAttributeSpecifier; 451 452 // No tentative parsing if we don't need to look for ']]' or a lambda. 453 if (!Disambiguate && !getLangOpts().ObjC1) 454 return CAK_AttributeSpecifier; 455 456 TentativeParsingAction PA(*this); 457 458 // Opening brackets were checked for above. 459 ConsumeBracket(); 460 461 // Outside Obj-C++11, treat anything with a matching ']]' as an attribute. 462 if (!getLangOpts().ObjC1) { 463 ConsumeBracket(); 464 465 bool IsAttribute = SkipUntil(tok::r_square, false); 466 IsAttribute &= Tok.is(tok::r_square); 467 468 PA.Revert(); 469 470 return IsAttribute ? CAK_AttributeSpecifier : CAK_InvalidAttributeSpecifier; 471 } 472 473 // In Obj-C++11, we need to distinguish four situations: 474 // 1a) int x[[attr]]; C++11 attribute. 475 // 1b) [[attr]]; C++11 statement attribute. 476 // 2) int x[[obj](){ return 1; }()]; Lambda in array size/index. 477 // 3a) int x[[obj get]]; Message send in array size/index. 478 // 3b) [[Class alloc] init]; Message send in message send. 479 // 4) [[obj]{ return self; }() doStuff]; Lambda in message send. 480 // (1) is an attribute, (2) is ill-formed, and (3) and (4) are accepted. 481 482 // If we have a lambda-introducer, then this is definitely not a message send. 483 // FIXME: If this disambiguation is too slow, fold the tentative lambda parse 484 // into the tentative attribute parse below. 485 LambdaIntroducer Intro; 486 if (!TryParseLambdaIntroducer(Intro)) { 487 // A lambda cannot end with ']]', and an attribute must. 488 bool IsAttribute = Tok.is(tok::r_square); 489 490 PA.Revert(); 491 492 if (IsAttribute) 493 // Case 1: C++11 attribute. 494 return CAK_AttributeSpecifier; 495 496 if (OuterMightBeMessageSend) 497 // Case 4: Lambda in message send. 498 return CAK_NotAttributeSpecifier; 499 500 // Case 2: Lambda in array size / index. 501 return CAK_InvalidAttributeSpecifier; 502 } 503 504 ConsumeBracket(); 505 506 // If we don't have a lambda-introducer, then we have an attribute or a 507 // message-send. 508 bool IsAttribute = true; 509 while (Tok.isNot(tok::r_square)) { 510 if (Tok.is(tok::comma)) { 511 // Case 1: Stray commas can only occur in attributes. 512 PA.Revert(); 513 return CAK_AttributeSpecifier; 514 } 515 516 // Parse the attribute-token, if present. 517 // C++11 [dcl.attr.grammar]: 518 // If a keyword or an alternative token that satisfies the syntactic 519 // requirements of an identifier is contained in an attribute-token, 520 // it is considered an identifier. 521 SourceLocation Loc; 522 if (!TryParseCXX11AttributeIdentifier(Loc)) { 523 IsAttribute = false; 524 break; 525 } 526 if (Tok.is(tok::coloncolon)) { 527 ConsumeToken(); 528 if (!TryParseCXX11AttributeIdentifier(Loc)) { 529 IsAttribute = false; 530 break; 531 } 532 } 533 534 // Parse the attribute-argument-clause, if present. 535 if (Tok.is(tok::l_paren)) { 536 ConsumeParen(); 537 if (!SkipUntil(tok::r_paren, false)) { 538 IsAttribute = false; 539 break; 540 } 541 } 542 543 if (Tok.is(tok::ellipsis)) 544 ConsumeToken(); 545 546 if (Tok.isNot(tok::comma)) 547 break; 548 549 ConsumeToken(); 550 } 551 552 // An attribute must end ']]'. 553 if (IsAttribute) { 554 if (Tok.is(tok::r_square)) { 555 ConsumeBracket(); 556 IsAttribute = Tok.is(tok::r_square); 557 } else { 558 IsAttribute = false; 559 } 560 } 561 562 PA.Revert(); 563 564 if (IsAttribute) 565 // Case 1: C++11 statement attribute. 566 return CAK_AttributeSpecifier; 567 568 // Case 3: Message send. 569 return CAK_NotAttributeSpecifier; 570 } 571 572 /// declarator: 573 /// direct-declarator 574 /// ptr-operator declarator 575 /// 576 /// direct-declarator: 577 /// declarator-id 578 /// direct-declarator '(' parameter-declaration-clause ')' 579 /// cv-qualifier-seq[opt] exception-specification[opt] 580 /// direct-declarator '[' constant-expression[opt] ']' 581 /// '(' declarator ')' 582 /// [GNU] '(' attributes declarator ')' 583 /// 584 /// abstract-declarator: 585 /// ptr-operator abstract-declarator[opt] 586 /// direct-abstract-declarator 587 /// ... 588 /// 589 /// direct-abstract-declarator: 590 /// direct-abstract-declarator[opt] 591 /// '(' parameter-declaration-clause ')' cv-qualifier-seq[opt] 592 /// exception-specification[opt] 593 /// direct-abstract-declarator[opt] '[' constant-expression[opt] ']' 594 /// '(' abstract-declarator ')' 595 /// 596 /// ptr-operator: 597 /// '*' cv-qualifier-seq[opt] 598 /// '&' 599 /// [C++0x] '&&' [TODO] 600 /// '::'[opt] nested-name-specifier '*' cv-qualifier-seq[opt] 601 /// 602 /// cv-qualifier-seq: 603 /// cv-qualifier cv-qualifier-seq[opt] 604 /// 605 /// cv-qualifier: 606 /// 'const' 607 /// 'volatile' 608 /// 609 /// declarator-id: 610 /// '...'[opt] id-expression 611 /// 612 /// id-expression: 613 /// unqualified-id 614 /// qualified-id [TODO] 615 /// 616 /// unqualified-id: 617 /// identifier 618 /// operator-function-id [TODO] 619 /// conversion-function-id [TODO] 620 /// '~' class-name [TODO] 621 /// template-id [TODO] 622 /// 623 Parser::TPResult Parser::TryParseDeclarator(bool mayBeAbstract, 624 bool mayHaveIdentifier) { 625 // declarator: 626 // direct-declarator 627 // ptr-operator declarator 628 629 while (1) { 630 if (Tok.is(tok::coloncolon) || Tok.is(tok::identifier)) 631 if (TryAnnotateCXXScopeToken(true)) 632 return TPResult::Error(); 633 634 if (Tok.is(tok::star) || Tok.is(tok::amp) || Tok.is(tok::caret) || 635 Tok.is(tok::ampamp) || 636 (Tok.is(tok::annot_cxxscope) && NextToken().is(tok::star))) { 637 // ptr-operator 638 ConsumeToken(); 639 while (Tok.is(tok::kw_const) || 640 Tok.is(tok::kw_volatile) || 641 Tok.is(tok::kw_restrict)) 642 ConsumeToken(); 643 } else { 644 break; 645 } 646 } 647 648 // direct-declarator: 649 // direct-abstract-declarator: 650 if (Tok.is(tok::ellipsis)) 651 ConsumeToken(); 652 653 if ((Tok.is(tok::identifier) || 654 (Tok.is(tok::annot_cxxscope) && NextToken().is(tok::identifier))) && 655 mayHaveIdentifier) { 656 // declarator-id 657 if (Tok.is(tok::annot_cxxscope)) 658 ConsumeToken(); 659 else 660 TentativelyDeclaredIdentifiers.push_back(Tok.getIdentifierInfo()); 661 ConsumeToken(); 662 } else if (Tok.is(tok::l_paren)) { 663 ConsumeParen(); 664 if (mayBeAbstract && 665 (Tok.is(tok::r_paren) || // 'int()' is a function. 666 // 'int(...)' is a function. 667 (Tok.is(tok::ellipsis) && NextToken().is(tok::r_paren)) || 668 isDeclarationSpecifier())) { // 'int(int)' is a function. 669 // '(' parameter-declaration-clause ')' cv-qualifier-seq[opt] 670 // exception-specification[opt] 671 TPResult TPR = TryParseFunctionDeclarator(); 672 if (TPR != TPResult::Ambiguous()) 673 return TPR; 674 } else { 675 // '(' declarator ')' 676 // '(' attributes declarator ')' 677 // '(' abstract-declarator ')' 678 if (Tok.is(tok::kw___attribute) || 679 Tok.is(tok::kw___declspec) || 680 Tok.is(tok::kw___cdecl) || 681 Tok.is(tok::kw___stdcall) || 682 Tok.is(tok::kw___fastcall) || 683 Tok.is(tok::kw___thiscall) || 684 Tok.is(tok::kw___unaligned)) 685 return TPResult::True(); // attributes indicate declaration 686 TPResult TPR = TryParseDeclarator(mayBeAbstract, mayHaveIdentifier); 687 if (TPR != TPResult::Ambiguous()) 688 return TPR; 689 if (Tok.isNot(tok::r_paren)) 690 return TPResult::False(); 691 ConsumeParen(); 692 } 693 } else if (!mayBeAbstract) { 694 return TPResult::False(); 695 } 696 697 while (1) { 698 TPResult TPR(TPResult::Ambiguous()); 699 700 // abstract-declarator: ... 701 if (Tok.is(tok::ellipsis)) 702 ConsumeToken(); 703 704 if (Tok.is(tok::l_paren)) { 705 // Check whether we have a function declarator or a possible ctor-style 706 // initializer that follows the declarator. Note that ctor-style 707 // initializers are not possible in contexts where abstract declarators 708 // are allowed. 709 if (!mayBeAbstract && !isCXXFunctionDeclarator()) 710 break; 711 712 // direct-declarator '(' parameter-declaration-clause ')' 713 // cv-qualifier-seq[opt] exception-specification[opt] 714 ConsumeParen(); 715 TPR = TryParseFunctionDeclarator(); 716 } else if (Tok.is(tok::l_square)) { 717 // direct-declarator '[' constant-expression[opt] ']' 718 // direct-abstract-declarator[opt] '[' constant-expression[opt] ']' 719 TPR = TryParseBracketDeclarator(); 720 } else { 721 break; 722 } 723 724 if (TPR != TPResult::Ambiguous()) 725 return TPR; 726 } 727 728 return TPResult::Ambiguous(); 729 } 730 731 Parser::TPResult 732 Parser::isExpressionOrTypeSpecifierSimple(tok::TokenKind Kind) { 733 switch (Kind) { 734 // Obviously starts an expression. 735 case tok::numeric_constant: 736 case tok::char_constant: 737 case tok::wide_char_constant: 738 case tok::utf16_char_constant: 739 case tok::utf32_char_constant: 740 case tok::string_literal: 741 case tok::wide_string_literal: 742 case tok::utf8_string_literal: 743 case tok::utf16_string_literal: 744 case tok::utf32_string_literal: 745 case tok::l_square: 746 case tok::l_paren: 747 case tok::amp: 748 case tok::ampamp: 749 case tok::star: 750 case tok::plus: 751 case tok::plusplus: 752 case tok::minus: 753 case tok::minusminus: 754 case tok::tilde: 755 case tok::exclaim: 756 case tok::kw_sizeof: 757 case tok::kw___func__: 758 case tok::kw_const_cast: 759 case tok::kw_delete: 760 case tok::kw_dynamic_cast: 761 case tok::kw_false: 762 case tok::kw_new: 763 case tok::kw_operator: 764 case tok::kw_reinterpret_cast: 765 case tok::kw_static_cast: 766 case tok::kw_this: 767 case tok::kw_throw: 768 case tok::kw_true: 769 case tok::kw_typeid: 770 case tok::kw_alignof: 771 case tok::kw_noexcept: 772 case tok::kw_nullptr: 773 case tok::kw__Alignof: 774 case tok::kw___null: 775 case tok::kw___alignof: 776 case tok::kw___builtin_choose_expr: 777 case tok::kw___builtin_offsetof: 778 case tok::kw___builtin_types_compatible_p: 779 case tok::kw___builtin_va_arg: 780 case tok::kw___imag: 781 case tok::kw___real: 782 case tok::kw___FUNCTION__: 783 case tok::kw_L__FUNCTION__: 784 case tok::kw___PRETTY_FUNCTION__: 785 case tok::kw___has_nothrow_assign: 786 case tok::kw___has_nothrow_copy: 787 case tok::kw___has_nothrow_constructor: 788 case tok::kw___has_trivial_assign: 789 case tok::kw___has_trivial_copy: 790 case tok::kw___has_trivial_constructor: 791 case tok::kw___has_trivial_destructor: 792 case tok::kw___has_virtual_destructor: 793 case tok::kw___is_abstract: 794 case tok::kw___is_base_of: 795 case tok::kw___is_class: 796 case tok::kw___is_convertible_to: 797 case tok::kw___is_empty: 798 case tok::kw___is_enum: 799 case tok::kw___is_interface_class: 800 case tok::kw___is_final: 801 case tok::kw___is_literal: 802 case tok::kw___is_literal_type: 803 case tok::kw___is_pod: 804 case tok::kw___is_polymorphic: 805 case tok::kw___is_trivial: 806 case tok::kw___is_trivially_assignable: 807 case tok::kw___is_trivially_constructible: 808 case tok::kw___is_trivially_copyable: 809 case tok::kw___is_union: 810 case tok::kw___uuidof: 811 return TPResult::True(); 812 813 // Obviously starts a type-specifier-seq: 814 case tok::kw_char: 815 case tok::kw_const: 816 case tok::kw_double: 817 case tok::kw_enum: 818 case tok::kw_half: 819 case tok::kw_float: 820 case tok::kw_int: 821 case tok::kw_long: 822 case tok::kw___int64: 823 case tok::kw___int128: 824 case tok::kw_restrict: 825 case tok::kw_short: 826 case tok::kw_signed: 827 case tok::kw_struct: 828 case tok::kw_union: 829 case tok::kw_unsigned: 830 case tok::kw_void: 831 case tok::kw_volatile: 832 case tok::kw__Bool: 833 case tok::kw__Complex: 834 case tok::kw_class: 835 case tok::kw_typename: 836 case tok::kw_wchar_t: 837 case tok::kw_char16_t: 838 case tok::kw_char32_t: 839 case tok::kw___underlying_type: 840 case tok::kw__Decimal32: 841 case tok::kw__Decimal64: 842 case tok::kw__Decimal128: 843 case tok::kw___thread: 844 case tok::kw_thread_local: 845 case tok::kw__Thread_local: 846 case tok::kw_typeof: 847 case tok::kw___cdecl: 848 case tok::kw___stdcall: 849 case tok::kw___fastcall: 850 case tok::kw___thiscall: 851 case tok::kw___unaligned: 852 case tok::kw___vector: 853 case tok::kw___pixel: 854 case tok::kw__Atomic: 855 case tok::kw_image1d_t: 856 case tok::kw_image1d_array_t: 857 case tok::kw_image1d_buffer_t: 858 case tok::kw_image2d_t: 859 case tok::kw_image2d_array_t: 860 case tok::kw_image3d_t: 861 case tok::kw_sampler_t: 862 case tok::kw_event_t: 863 case tok::kw___unknown_anytype: 864 return TPResult::False(); 865 866 default: 867 break; 868 } 869 870 return TPResult::Ambiguous(); 871 } 872 873 bool Parser::isTentativelyDeclared(IdentifierInfo *II) { 874 return std::find(TentativelyDeclaredIdentifiers.begin(), 875 TentativelyDeclaredIdentifiers.end(), II) 876 != TentativelyDeclaredIdentifiers.end(); 877 } 878 879 /// isCXXDeclarationSpecifier - Returns TPResult::True() if it is a declaration 880 /// specifier, TPResult::False() if it is not, TPResult::Ambiguous() if it could 881 /// be either a decl-specifier or a function-style cast, and TPResult::Error() 882 /// if a parsing error was found and reported. 883 /// 884 /// If HasMissingTypename is provided, a name with a dependent scope specifier 885 /// will be treated as ambiguous if the 'typename' keyword is missing. If this 886 /// happens, *HasMissingTypename will be set to 'true'. This will also be used 887 /// as an indicator that undeclared identifiers (which will trigger a later 888 /// parse error) should be treated as types. Returns TPResult::Ambiguous() in 889 /// such cases. 890 /// 891 /// decl-specifier: 892 /// storage-class-specifier 893 /// type-specifier 894 /// function-specifier 895 /// 'friend' 896 /// 'typedef' 897 /// [C++11] 'constexpr' 898 /// [GNU] attributes declaration-specifiers[opt] 899 /// 900 /// storage-class-specifier: 901 /// 'register' 902 /// 'static' 903 /// 'extern' 904 /// 'mutable' 905 /// 'auto' 906 /// [GNU] '__thread' 907 /// [C++11] 'thread_local' 908 /// [C11] '_Thread_local' 909 /// 910 /// function-specifier: 911 /// 'inline' 912 /// 'virtual' 913 /// 'explicit' 914 /// 915 /// typedef-name: 916 /// identifier 917 /// 918 /// type-specifier: 919 /// simple-type-specifier 920 /// class-specifier 921 /// enum-specifier 922 /// elaborated-type-specifier 923 /// typename-specifier 924 /// cv-qualifier 925 /// 926 /// simple-type-specifier: 927 /// '::'[opt] nested-name-specifier[opt] type-name 928 /// '::'[opt] nested-name-specifier 'template' 929 /// simple-template-id [TODO] 930 /// 'char' 931 /// 'wchar_t' 932 /// 'bool' 933 /// 'short' 934 /// 'int' 935 /// 'long' 936 /// 'signed' 937 /// 'unsigned' 938 /// 'float' 939 /// 'double' 940 /// 'void' 941 /// [GNU] typeof-specifier 942 /// [GNU] '_Complex' 943 /// [C++11] 'auto' 944 /// [C++11] 'decltype' ( expression ) 945 /// [C++1y] 'decltype' ( 'auto' ) 946 /// 947 /// type-name: 948 /// class-name 949 /// enum-name 950 /// typedef-name 951 /// 952 /// elaborated-type-specifier: 953 /// class-key '::'[opt] nested-name-specifier[opt] identifier 954 /// class-key '::'[opt] nested-name-specifier[opt] 'template'[opt] 955 /// simple-template-id 956 /// 'enum' '::'[opt] nested-name-specifier[opt] identifier 957 /// 958 /// enum-name: 959 /// identifier 960 /// 961 /// enum-specifier: 962 /// 'enum' identifier[opt] '{' enumerator-list[opt] '}' 963 /// 'enum' identifier[opt] '{' enumerator-list ',' '}' 964 /// 965 /// class-specifier: 966 /// class-head '{' member-specification[opt] '}' 967 /// 968 /// class-head: 969 /// class-key identifier[opt] base-clause[opt] 970 /// class-key nested-name-specifier identifier base-clause[opt] 971 /// class-key nested-name-specifier[opt] simple-template-id 972 /// base-clause[opt] 973 /// 974 /// class-key: 975 /// 'class' 976 /// 'struct' 977 /// 'union' 978 /// 979 /// cv-qualifier: 980 /// 'const' 981 /// 'volatile' 982 /// [GNU] restrict 983 /// 984 Parser::TPResult 985 Parser::isCXXDeclarationSpecifier(Parser::TPResult BracedCastResult, 986 bool *HasMissingTypename) { 987 switch (Tok.getKind()) { 988 case tok::identifier: { 989 // Check for need to substitute AltiVec __vector keyword 990 // for "vector" identifier. 991 if (TryAltiVecVectorToken()) 992 return TPResult::True(); 993 994 const Token &Next = NextToken(); 995 // In 'foo bar', 'foo' is always a type name outside of Objective-C. 996 if (!getLangOpts().ObjC1 && Next.is(tok::identifier)) 997 return TPResult::True(); 998 999 if (Next.isNot(tok::coloncolon) && Next.isNot(tok::less)) { 1000 // Determine whether this is a valid expression. If not, we will hit 1001 // a parse error one way or another. In that case, tell the caller that 1002 // this is ambiguous. Typo-correct to type and expression keywords and 1003 // to types and identifiers, in order to try to recover from errors. 1004 CorrectionCandidateCallback TypoCorrection; 1005 TypoCorrection.WantRemainingKeywords = false; 1006 TypoCorrection.WantTypeSpecifiers = Next.isNot(tok::arrow); 1007 switch (TryAnnotateName(false /* no nested name specifier */, 1008 &TypoCorrection)) { 1009 case ANK_Error: 1010 return TPResult::Error(); 1011 case ANK_TentativeDecl: 1012 return TPResult::False(); 1013 case ANK_TemplateName: 1014 // A bare type template-name which can't be a template template 1015 // argument is an error, and was probably intended to be a type. 1016 return GreaterThanIsOperator ? TPResult::True() : TPResult::False(); 1017 case ANK_Unresolved: 1018 return HasMissingTypename ? TPResult::Ambiguous() : TPResult::False(); 1019 case ANK_Success: 1020 break; 1021 } 1022 assert(Tok.isNot(tok::identifier) && 1023 "TryAnnotateName succeeded without producing an annotation"); 1024 } else { 1025 // This might possibly be a type with a dependent scope specifier and 1026 // a missing 'typename' keyword. Don't use TryAnnotateName in this case, 1027 // since it will annotate as a primary expression, and we want to use the 1028 // "missing 'typename'" logic. 1029 if (TryAnnotateTypeOrScopeToken()) 1030 return TPResult::Error(); 1031 // If annotation failed, assume it's a non-type. 1032 // FIXME: If this happens due to an undeclared identifier, treat it as 1033 // ambiguous. 1034 if (Tok.is(tok::identifier)) 1035 return TPResult::False(); 1036 } 1037 1038 // We annotated this token as something. Recurse to handle whatever we got. 1039 return isCXXDeclarationSpecifier(BracedCastResult, HasMissingTypename); 1040 } 1041 1042 case tok::kw_typename: // typename T::type 1043 // Annotate typenames and C++ scope specifiers. If we get one, just 1044 // recurse to handle whatever we get. 1045 if (TryAnnotateTypeOrScopeToken()) 1046 return TPResult::Error(); 1047 return isCXXDeclarationSpecifier(BracedCastResult, HasMissingTypename); 1048 1049 case tok::coloncolon: { // ::foo::bar 1050 const Token &Next = NextToken(); 1051 if (Next.is(tok::kw_new) || // ::new 1052 Next.is(tok::kw_delete)) // ::delete 1053 return TPResult::False(); 1054 } 1055 // Fall through. 1056 case tok::kw_decltype: 1057 // Annotate typenames and C++ scope specifiers. If we get one, just 1058 // recurse to handle whatever we get. 1059 if (TryAnnotateTypeOrScopeToken()) 1060 return TPResult::Error(); 1061 return isCXXDeclarationSpecifier(BracedCastResult, HasMissingTypename); 1062 1063 // decl-specifier: 1064 // storage-class-specifier 1065 // type-specifier 1066 // function-specifier 1067 // 'friend' 1068 // 'typedef' 1069 // 'constexpr' 1070 case tok::kw_friend: 1071 case tok::kw_typedef: 1072 case tok::kw_constexpr: 1073 // storage-class-specifier 1074 case tok::kw_register: 1075 case tok::kw_static: 1076 case tok::kw_extern: 1077 case tok::kw_mutable: 1078 case tok::kw_auto: 1079 case tok::kw___thread: 1080 case tok::kw_thread_local: 1081 case tok::kw__Thread_local: 1082 // function-specifier 1083 case tok::kw_inline: 1084 case tok::kw_virtual: 1085 case tok::kw_explicit: 1086 1087 // Modules 1088 case tok::kw___module_private__: 1089 1090 // Debugger support 1091 case tok::kw___unknown_anytype: 1092 1093 // type-specifier: 1094 // simple-type-specifier 1095 // class-specifier 1096 // enum-specifier 1097 // elaborated-type-specifier 1098 // typename-specifier 1099 // cv-qualifier 1100 1101 // class-specifier 1102 // elaborated-type-specifier 1103 case tok::kw_class: 1104 case tok::kw_struct: 1105 case tok::kw_union: 1106 // enum-specifier 1107 case tok::kw_enum: 1108 // cv-qualifier 1109 case tok::kw_const: 1110 case tok::kw_volatile: 1111 1112 // GNU 1113 case tok::kw_restrict: 1114 case tok::kw__Complex: 1115 case tok::kw___attribute: 1116 return TPResult::True(); 1117 1118 // Microsoft 1119 case tok::kw___declspec: 1120 case tok::kw___cdecl: 1121 case tok::kw___stdcall: 1122 case tok::kw___fastcall: 1123 case tok::kw___thiscall: 1124 case tok::kw___w64: 1125 case tok::kw___sptr: 1126 case tok::kw___uptr: 1127 case tok::kw___ptr64: 1128 case tok::kw___ptr32: 1129 case tok::kw___forceinline: 1130 case tok::kw___unaligned: 1131 return TPResult::True(); 1132 1133 // Borland 1134 case tok::kw___pascal: 1135 return TPResult::True(); 1136 1137 // AltiVec 1138 case tok::kw___vector: 1139 return TPResult::True(); 1140 1141 case tok::annot_template_id: { 1142 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok); 1143 if (TemplateId->Kind != TNK_Type_template) 1144 return TPResult::False(); 1145 CXXScopeSpec SS; 1146 AnnotateTemplateIdTokenAsType(); 1147 assert(Tok.is(tok::annot_typename)); 1148 goto case_typename; 1149 } 1150 1151 case tok::annot_cxxscope: // foo::bar or ::foo::bar, but already parsed 1152 // We've already annotated a scope; try to annotate a type. 1153 if (TryAnnotateTypeOrScopeToken()) 1154 return TPResult::Error(); 1155 if (!Tok.is(tok::annot_typename)) { 1156 // If the next token is an identifier or a type qualifier, then this 1157 // can't possibly be a valid expression either. 1158 if (Tok.is(tok::annot_cxxscope) && NextToken().is(tok::identifier)) { 1159 CXXScopeSpec SS; 1160 Actions.RestoreNestedNameSpecifierAnnotation(Tok.getAnnotationValue(), 1161 Tok.getAnnotationRange(), 1162 SS); 1163 if (SS.getScopeRep() && SS.getScopeRep()->isDependent()) { 1164 TentativeParsingAction PA(*this); 1165 ConsumeToken(); 1166 ConsumeToken(); 1167 bool isIdentifier = Tok.is(tok::identifier); 1168 TPResult TPR = TPResult::False(); 1169 if (!isIdentifier) 1170 TPR = isCXXDeclarationSpecifier(BracedCastResult, 1171 HasMissingTypename); 1172 PA.Revert(); 1173 1174 if (isIdentifier || 1175 TPR == TPResult::True() || TPR == TPResult::Error()) 1176 return TPResult::Error(); 1177 1178 if (HasMissingTypename) { 1179 // We can't tell whether this is a missing 'typename' or a valid 1180 // expression. 1181 *HasMissingTypename = true; 1182 return TPResult::Ambiguous(); 1183 } 1184 } else { 1185 // Try to resolve the name. If it doesn't exist, assume it was 1186 // intended to name a type and keep disambiguating. 1187 switch (TryAnnotateName(false /* SS is not dependent */)) { 1188 case ANK_Error: 1189 return TPResult::Error(); 1190 case ANK_TentativeDecl: 1191 return TPResult::False(); 1192 case ANK_TemplateName: 1193 // A bare type template-name which can't be a template template 1194 // argument is an error, and was probably intended to be a type. 1195 return GreaterThanIsOperator ? TPResult::True() : TPResult::False(); 1196 case ANK_Unresolved: 1197 return HasMissingTypename ? TPResult::Ambiguous() 1198 : TPResult::False(); 1199 case ANK_Success: 1200 // Annotated it, check again. 1201 assert(Tok.isNot(tok::annot_cxxscope) || 1202 NextToken().isNot(tok::identifier)); 1203 return isCXXDeclarationSpecifier(BracedCastResult, 1204 HasMissingTypename); 1205 } 1206 } 1207 } 1208 return TPResult::False(); 1209 } 1210 // If that succeeded, fallthrough into the generic simple-type-id case. 1211 1212 // The ambiguity resides in a simple-type-specifier/typename-specifier 1213 // followed by a '('. The '(' could either be the start of: 1214 // 1215 // direct-declarator: 1216 // '(' declarator ')' 1217 // 1218 // direct-abstract-declarator: 1219 // '(' parameter-declaration-clause ')' cv-qualifier-seq[opt] 1220 // exception-specification[opt] 1221 // '(' abstract-declarator ')' 1222 // 1223 // or part of a function-style cast expression: 1224 // 1225 // simple-type-specifier '(' expression-list[opt] ')' 1226 // 1227 1228 // simple-type-specifier: 1229 1230 case tok::annot_typename: 1231 case_typename: 1232 // In Objective-C, we might have a protocol-qualified type. 1233 if (getLangOpts().ObjC1 && NextToken().is(tok::less)) { 1234 // Tentatively parse the 1235 TentativeParsingAction PA(*this); 1236 ConsumeToken(); // The type token 1237 1238 TPResult TPR = TryParseProtocolQualifiers(); 1239 bool isFollowedByParen = Tok.is(tok::l_paren); 1240 bool isFollowedByBrace = Tok.is(tok::l_brace); 1241 1242 PA.Revert(); 1243 1244 if (TPR == TPResult::Error()) 1245 return TPResult::Error(); 1246 1247 if (isFollowedByParen) 1248 return TPResult::Ambiguous(); 1249 1250 if (getLangOpts().CPlusPlus11 && isFollowedByBrace) 1251 return BracedCastResult; 1252 1253 return TPResult::True(); 1254 } 1255 1256 case tok::kw_char: 1257 case tok::kw_wchar_t: 1258 case tok::kw_char16_t: 1259 case tok::kw_char32_t: 1260 case tok::kw_bool: 1261 case tok::kw_short: 1262 case tok::kw_int: 1263 case tok::kw_long: 1264 case tok::kw___int64: 1265 case tok::kw___int128: 1266 case tok::kw_signed: 1267 case tok::kw_unsigned: 1268 case tok::kw_half: 1269 case tok::kw_float: 1270 case tok::kw_double: 1271 case tok::kw_void: 1272 case tok::annot_decltype: 1273 if (NextToken().is(tok::l_paren)) 1274 return TPResult::Ambiguous(); 1275 1276 // This is a function-style cast in all cases we disambiguate other than 1277 // one: 1278 // struct S { 1279 // enum E : int { a = 4 }; // enum 1280 // enum E : int { 4 }; // bit-field 1281 // }; 1282 if (getLangOpts().CPlusPlus11 && NextToken().is(tok::l_brace)) 1283 return BracedCastResult; 1284 1285 if (isStartOfObjCClassMessageMissingOpenBracket()) 1286 return TPResult::False(); 1287 1288 return TPResult::True(); 1289 1290 // GNU typeof support. 1291 case tok::kw_typeof: { 1292 if (NextToken().isNot(tok::l_paren)) 1293 return TPResult::True(); 1294 1295 TentativeParsingAction PA(*this); 1296 1297 TPResult TPR = TryParseTypeofSpecifier(); 1298 bool isFollowedByParen = Tok.is(tok::l_paren); 1299 bool isFollowedByBrace = Tok.is(tok::l_brace); 1300 1301 PA.Revert(); 1302 1303 if (TPR == TPResult::Error()) 1304 return TPResult::Error(); 1305 1306 if (isFollowedByParen) 1307 return TPResult::Ambiguous(); 1308 1309 if (getLangOpts().CPlusPlus11 && isFollowedByBrace) 1310 return BracedCastResult; 1311 1312 return TPResult::True(); 1313 } 1314 1315 // C++0x type traits support 1316 case tok::kw___underlying_type: 1317 return TPResult::True(); 1318 1319 // C11 _Atomic 1320 case tok::kw__Atomic: 1321 return TPResult::True(); 1322 1323 default: 1324 return TPResult::False(); 1325 } 1326 } 1327 1328 /// [GNU] typeof-specifier: 1329 /// 'typeof' '(' expressions ')' 1330 /// 'typeof' '(' type-name ')' 1331 /// 1332 Parser::TPResult Parser::TryParseTypeofSpecifier() { 1333 assert(Tok.is(tok::kw_typeof) && "Expected 'typeof'!"); 1334 ConsumeToken(); 1335 1336 assert(Tok.is(tok::l_paren) && "Expected '('"); 1337 // Parse through the parens after 'typeof'. 1338 ConsumeParen(); 1339 if (!SkipUntil(tok::r_paren)) 1340 return TPResult::Error(); 1341 1342 return TPResult::Ambiguous(); 1343 } 1344 1345 /// [ObjC] protocol-qualifiers: 1346 //// '<' identifier-list '>' 1347 Parser::TPResult Parser::TryParseProtocolQualifiers() { 1348 assert(Tok.is(tok::less) && "Expected '<' for qualifier list"); 1349 ConsumeToken(); 1350 do { 1351 if (Tok.isNot(tok::identifier)) 1352 return TPResult::Error(); 1353 ConsumeToken(); 1354 1355 if (Tok.is(tok::comma)) { 1356 ConsumeToken(); 1357 continue; 1358 } 1359 1360 if (Tok.is(tok::greater)) { 1361 ConsumeToken(); 1362 return TPResult::Ambiguous(); 1363 } 1364 } while (false); 1365 1366 return TPResult::Error(); 1367 } 1368 1369 Parser::TPResult 1370 Parser::TryParseDeclarationSpecifier(bool *HasMissingTypename) { 1371 TPResult TPR = isCXXDeclarationSpecifier(TPResult::False(), 1372 HasMissingTypename); 1373 if (TPR != TPResult::Ambiguous()) 1374 return TPR; 1375 1376 if (Tok.is(tok::kw_typeof)) 1377 TryParseTypeofSpecifier(); 1378 else { 1379 if (Tok.is(tok::annot_cxxscope)) 1380 ConsumeToken(); 1381 ConsumeToken(); 1382 1383 if (getLangOpts().ObjC1 && Tok.is(tok::less)) 1384 TryParseProtocolQualifiers(); 1385 } 1386 1387 return TPResult::Ambiguous(); 1388 } 1389 1390 /// isCXXFunctionDeclarator - Disambiguates between a function declarator or 1391 /// a constructor-style initializer, when parsing declaration statements. 1392 /// Returns true for function declarator and false for constructor-style 1393 /// initializer. 1394 /// If during the disambiguation process a parsing error is encountered, 1395 /// the function returns true to let the declaration parsing code handle it. 1396 /// 1397 /// '(' parameter-declaration-clause ')' cv-qualifier-seq[opt] 1398 /// exception-specification[opt] 1399 /// 1400 bool Parser::isCXXFunctionDeclarator(bool *IsAmbiguous) { 1401 1402 // C++ 8.2p1: 1403 // The ambiguity arising from the similarity between a function-style cast and 1404 // a declaration mentioned in 6.8 can also occur in the context of a 1405 // declaration. In that context, the choice is between a function declaration 1406 // with a redundant set of parentheses around a parameter name and an object 1407 // declaration with a function-style cast as the initializer. Just as for the 1408 // ambiguities mentioned in 6.8, the resolution is to consider any construct 1409 // that could possibly be a declaration a declaration. 1410 1411 TentativeParsingAction PA(*this); 1412 1413 ConsumeParen(); 1414 bool InvalidAsDeclaration = false; 1415 TPResult TPR = TryParseParameterDeclarationClause(&InvalidAsDeclaration); 1416 if (TPR == TPResult::Ambiguous()) { 1417 if (Tok.isNot(tok::r_paren)) 1418 TPR = TPResult::False(); 1419 else { 1420 const Token &Next = NextToken(); 1421 if (Next.is(tok::amp) || Next.is(tok::ampamp) || 1422 Next.is(tok::kw_const) || Next.is(tok::kw_volatile) || 1423 Next.is(tok::kw_throw) || Next.is(tok::kw_noexcept) || 1424 Next.is(tok::l_square) || isCXX11VirtSpecifier(Next) || 1425 Next.is(tok::l_brace) || Next.is(tok::kw_try) || 1426 Next.is(tok::equal) || Next.is(tok::arrow)) 1427 // The next token cannot appear after a constructor-style initializer, 1428 // and can appear next in a function definition. This must be a function 1429 // declarator. 1430 TPR = TPResult::True(); 1431 else if (InvalidAsDeclaration) 1432 // Use the absence of 'typename' as a tie-breaker. 1433 TPR = TPResult::False(); 1434 } 1435 } 1436 1437 PA.Revert(); 1438 1439 if (IsAmbiguous && TPR == TPResult::Ambiguous()) 1440 *IsAmbiguous = true; 1441 1442 // In case of an error, let the declaration parsing code handle it. 1443 return TPR != TPResult::False(); 1444 } 1445 1446 /// parameter-declaration-clause: 1447 /// parameter-declaration-list[opt] '...'[opt] 1448 /// parameter-declaration-list ',' '...' 1449 /// 1450 /// parameter-declaration-list: 1451 /// parameter-declaration 1452 /// parameter-declaration-list ',' parameter-declaration 1453 /// 1454 /// parameter-declaration: 1455 /// attribute-specifier-seq[opt] decl-specifier-seq declarator attributes[opt] 1456 /// attribute-specifier-seq[opt] decl-specifier-seq declarator attributes[opt] 1457 /// '=' assignment-expression 1458 /// attribute-specifier-seq[opt] decl-specifier-seq abstract-declarator[opt] 1459 /// attributes[opt] 1460 /// attribute-specifier-seq[opt] decl-specifier-seq abstract-declarator[opt] 1461 /// attributes[opt] '=' assignment-expression 1462 /// 1463 Parser::TPResult 1464 Parser::TryParseParameterDeclarationClause(bool *InvalidAsDeclaration) { 1465 1466 if (Tok.is(tok::r_paren)) 1467 return TPResult::Ambiguous(); 1468 1469 // parameter-declaration-list[opt] '...'[opt] 1470 // parameter-declaration-list ',' '...' 1471 // 1472 // parameter-declaration-list: 1473 // parameter-declaration 1474 // parameter-declaration-list ',' parameter-declaration 1475 // 1476 while (1) { 1477 // '...'[opt] 1478 if (Tok.is(tok::ellipsis)) { 1479 ConsumeToken(); 1480 if (Tok.is(tok::r_paren)) 1481 return TPResult::True(); // '...)' is a sign of a function declarator. 1482 else 1483 return TPResult::False(); 1484 } 1485 1486 // An attribute-specifier-seq here is a sign of a function declarator. 1487 if (isCXX11AttributeSpecifier(/*Disambiguate*/false, 1488 /*OuterMightBeMessageSend*/true)) 1489 return TPResult::True(); 1490 1491 ParsedAttributes attrs(AttrFactory); 1492 MaybeParseMicrosoftAttributes(attrs); 1493 1494 // decl-specifier-seq 1495 // A parameter-declaration's initializer must be preceded by an '=', so 1496 // decl-specifier-seq '{' is not a parameter in C++11. 1497 TPResult TPR = TryParseDeclarationSpecifier(InvalidAsDeclaration); 1498 if (TPR != TPResult::Ambiguous()) 1499 return TPR; 1500 1501 // declarator 1502 // abstract-declarator[opt] 1503 TPR = TryParseDeclarator(true/*mayBeAbstract*/); 1504 if (TPR != TPResult::Ambiguous()) 1505 return TPR; 1506 1507 // [GNU] attributes[opt] 1508 if (Tok.is(tok::kw___attribute)) 1509 return TPResult::True(); 1510 1511 if (Tok.is(tok::equal)) { 1512 // '=' assignment-expression 1513 // Parse through assignment-expression. 1514 if (!SkipUntil(tok::comma, tok::r_paren, true/*StopAtSemi*/, 1515 true/*DontConsume*/)) 1516 return TPResult::Error(); 1517 } 1518 1519 if (Tok.is(tok::ellipsis)) { 1520 ConsumeToken(); 1521 if (Tok.is(tok::r_paren)) 1522 return TPResult::True(); // '...)' is a sign of a function declarator. 1523 else 1524 return TPResult::False(); 1525 } 1526 1527 if (Tok.isNot(tok::comma)) 1528 break; 1529 ConsumeToken(); // the comma. 1530 } 1531 1532 return TPResult::Ambiguous(); 1533 } 1534 1535 /// TryParseFunctionDeclarator - We parsed a '(' and we want to try to continue 1536 /// parsing as a function declarator. 1537 /// If TryParseFunctionDeclarator fully parsed the function declarator, it will 1538 /// return TPResult::Ambiguous(), otherwise it will return either False() or 1539 /// Error(). 1540 /// 1541 /// '(' parameter-declaration-clause ')' cv-qualifier-seq[opt] 1542 /// exception-specification[opt] 1543 /// 1544 /// exception-specification: 1545 /// 'throw' '(' type-id-list[opt] ')' 1546 /// 1547 Parser::TPResult Parser::TryParseFunctionDeclarator() { 1548 1549 // The '(' is already parsed. 1550 1551 TPResult TPR = TryParseParameterDeclarationClause(); 1552 if (TPR == TPResult::Ambiguous() && Tok.isNot(tok::r_paren)) 1553 TPR = TPResult::False(); 1554 1555 if (TPR == TPResult::False() || TPR == TPResult::Error()) 1556 return TPR; 1557 1558 // Parse through the parens. 1559 if (!SkipUntil(tok::r_paren)) 1560 return TPResult::Error(); 1561 1562 // cv-qualifier-seq 1563 while (Tok.is(tok::kw_const) || 1564 Tok.is(tok::kw_volatile) || 1565 Tok.is(tok::kw_restrict) ) 1566 ConsumeToken(); 1567 1568 // ref-qualifier[opt] 1569 if (Tok.is(tok::amp) || Tok.is(tok::ampamp)) 1570 ConsumeToken(); 1571 1572 // exception-specification 1573 if (Tok.is(tok::kw_throw)) { 1574 ConsumeToken(); 1575 if (Tok.isNot(tok::l_paren)) 1576 return TPResult::Error(); 1577 1578 // Parse through the parens after 'throw'. 1579 ConsumeParen(); 1580 if (!SkipUntil(tok::r_paren)) 1581 return TPResult::Error(); 1582 } 1583 if (Tok.is(tok::kw_noexcept)) { 1584 ConsumeToken(); 1585 // Possibly an expression as well. 1586 if (Tok.is(tok::l_paren)) { 1587 // Find the matching rparen. 1588 ConsumeParen(); 1589 if (!SkipUntil(tok::r_paren)) 1590 return TPResult::Error(); 1591 } 1592 } 1593 1594 return TPResult::Ambiguous(); 1595 } 1596 1597 /// '[' constant-expression[opt] ']' 1598 /// 1599 Parser::TPResult Parser::TryParseBracketDeclarator() { 1600 ConsumeBracket(); 1601 if (!SkipUntil(tok::r_square)) 1602 return TPResult::Error(); 1603 1604 return TPResult::Ambiguous(); 1605 } 1606