ParseDecl.cpp revision 2786864406af0f3ec65b300675c6f3c809c22fd7
1//===--- ParseDecl.cpp - Declaration 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 Declaration portions of the Parser interfaces. 11// 12//===----------------------------------------------------------------------===// 13 14#include "clang/Parse/Parser.h" 15#include "clang/Parse/ParseDiagnostic.h" 16#include "clang/Sema/Scope.h" 17#include "clang/Sema/ParsedTemplate.h" 18#include "clang/Sema/PrettyDeclStackTrace.h" 19#include "RAIIObjectsForParser.h" 20#include "llvm/ADT/SmallSet.h" 21using namespace clang; 22 23//===----------------------------------------------------------------------===// 24// C99 6.7: Declarations. 25//===----------------------------------------------------------------------===// 26 27/// ParseTypeName 28/// type-name: [C99 6.7.6] 29/// specifier-qualifier-list abstract-declarator[opt] 30/// 31/// Called type-id in C++. 32TypeResult Parser::ParseTypeName(SourceRange *Range, 33 Declarator::TheContext Context) { 34 // Parse the common declaration-specifiers piece. 35 DeclSpec DS; 36 ParseSpecifierQualifierList(DS); 37 38 // Parse the abstract-declarator, if present. 39 Declarator DeclaratorInfo(DS, Context); 40 ParseDeclarator(DeclaratorInfo); 41 if (Range) 42 *Range = DeclaratorInfo.getSourceRange(); 43 44 if (DeclaratorInfo.isInvalidType()) 45 return true; 46 47 return Actions.ActOnTypeName(getCurScope(), DeclaratorInfo); 48} 49 50/// ParseGNUAttributes - Parse a non-empty attributes list. 51/// 52/// [GNU] attributes: 53/// attribute 54/// attributes attribute 55/// 56/// [GNU] attribute: 57/// '__attribute__' '(' '(' attribute-list ')' ')' 58/// 59/// [GNU] attribute-list: 60/// attrib 61/// attribute_list ',' attrib 62/// 63/// [GNU] attrib: 64/// empty 65/// attrib-name 66/// attrib-name '(' identifier ')' 67/// attrib-name '(' identifier ',' nonempty-expr-list ')' 68/// attrib-name '(' argument-expression-list [C99 6.5.2] ')' 69/// 70/// [GNU] attrib-name: 71/// identifier 72/// typespec 73/// typequal 74/// storageclass 75/// 76/// FIXME: The GCC grammar/code for this construct implies we need two 77/// token lookahead. Comment from gcc: "If they start with an identifier 78/// which is followed by a comma or close parenthesis, then the arguments 79/// start with that identifier; otherwise they are an expression list." 80/// 81/// At the moment, I am not doing 2 token lookahead. I am also unaware of 82/// any attributes that don't work (based on my limited testing). Most 83/// attributes are very simple in practice. Until we find a bug, I don't see 84/// a pressing need to implement the 2 token lookahead. 85 86void Parser::ParseGNUAttributes(ParsedAttributes &attrs, 87 SourceLocation *endLoc) { 88 assert(Tok.is(tok::kw___attribute) && "Not a GNU attribute list!"); 89 90 while (Tok.is(tok::kw___attribute)) { 91 ConsumeToken(); 92 if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after, 93 "attribute")) { 94 SkipUntil(tok::r_paren, true); // skip until ) or ; 95 return; 96 } 97 if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after, "(")) { 98 SkipUntil(tok::r_paren, true); // skip until ) or ; 99 return; 100 } 101 // Parse the attribute-list. e.g. __attribute__(( weak, alias("__f") )) 102 while (Tok.is(tok::identifier) || isDeclarationSpecifier() || 103 Tok.is(tok::comma)) { 104 105 if (Tok.is(tok::comma)) { 106 // allows for empty/non-empty attributes. ((__vector_size__(16),,,,)) 107 ConsumeToken(); 108 continue; 109 } 110 // we have an identifier or declaration specifier (const, int, etc.) 111 IdentifierInfo *AttrName = Tok.getIdentifierInfo(); 112 SourceLocation AttrNameLoc = ConsumeToken(); 113 114 // check if we have a "parameterized" attribute 115 if (Tok.is(tok::l_paren)) { 116 ConsumeParen(); // ignore the left paren loc for now 117 118 if (Tok.is(tok::identifier)) { 119 IdentifierInfo *ParmName = Tok.getIdentifierInfo(); 120 SourceLocation ParmLoc = ConsumeToken(); 121 122 if (Tok.is(tok::r_paren)) { 123 // __attribute__(( mode(byte) )) 124 ConsumeParen(); // ignore the right paren loc for now 125 attrs.add(AttrFactory.Create(AttrName, AttrNameLoc, 0, AttrNameLoc, 126 ParmName, ParmLoc, 0, 0)); 127 } else if (Tok.is(tok::comma)) { 128 ConsumeToken(); 129 // __attribute__(( format(printf, 1, 2) )) 130 ExprVector ArgExprs(Actions); 131 bool ArgExprsOk = true; 132 133 // now parse the non-empty comma separated list of expressions 134 while (1) { 135 ExprResult ArgExpr(ParseAssignmentExpression()); 136 if (ArgExpr.isInvalid()) { 137 ArgExprsOk = false; 138 SkipUntil(tok::r_paren); 139 break; 140 } else { 141 ArgExprs.push_back(ArgExpr.release()); 142 } 143 if (Tok.isNot(tok::comma)) 144 break; 145 ConsumeToken(); // Eat the comma, move to the next argument 146 } 147 if (ArgExprsOk && Tok.is(tok::r_paren)) { 148 ConsumeParen(); // ignore the right paren loc for now 149 attrs.add(AttrFactory.Create(AttrName, AttrNameLoc, 0, 150 AttrNameLoc, ParmName, ParmLoc, 151 ArgExprs.take(), ArgExprs.size())); 152 } 153 } 154 } else { // not an identifier 155 switch (Tok.getKind()) { 156 case tok::r_paren: 157 // parse a possibly empty comma separated list of expressions 158 // __attribute__(( nonnull() )) 159 ConsumeParen(); // ignore the right paren loc for now 160 attrs.add(AttrFactory.Create(AttrName, AttrNameLoc, 0, AttrNameLoc, 161 0, SourceLocation(), 0, 0)); 162 break; 163 case tok::kw_char: 164 case tok::kw_wchar_t: 165 case tok::kw_char16_t: 166 case tok::kw_char32_t: 167 case tok::kw_bool: 168 case tok::kw_short: 169 case tok::kw_int: 170 case tok::kw_long: 171 case tok::kw_signed: 172 case tok::kw_unsigned: 173 case tok::kw_float: 174 case tok::kw_double: 175 case tok::kw_void: 176 case tok::kw_typeof: { 177 AttributeList *attr 178 = AttrFactory.Create(AttrName, AttrNameLoc, 0, AttrNameLoc, 179 0, SourceLocation(), 0, 0); 180 attrs.add(attr); 181 if (attr->getKind() == AttributeList::AT_IBOutletCollection) 182 Diag(Tok, diag::err_iboutletcollection_builtintype); 183 // If it's a builtin type name, eat it and expect a rparen 184 // __attribute__(( vec_type_hint(char) )) 185 ConsumeToken(); 186 if (Tok.is(tok::r_paren)) 187 ConsumeParen(); 188 break; 189 } 190 default: 191 // __attribute__(( aligned(16) )) 192 ExprVector ArgExprs(Actions); 193 bool ArgExprsOk = true; 194 195 // now parse the list of expressions 196 while (1) { 197 ExprResult ArgExpr(ParseAssignmentExpression()); 198 if (ArgExpr.isInvalid()) { 199 ArgExprsOk = false; 200 SkipUntil(tok::r_paren); 201 break; 202 } else { 203 ArgExprs.push_back(ArgExpr.release()); 204 } 205 if (Tok.isNot(tok::comma)) 206 break; 207 ConsumeToken(); // Eat the comma, move to the next argument 208 } 209 // Match the ')'. 210 if (ArgExprsOk && Tok.is(tok::r_paren)) { 211 ConsumeParen(); // ignore the right paren loc for now 212 attrs.add(AttrFactory.Create(AttrName, AttrNameLoc, 0, 213 AttrNameLoc, 0, SourceLocation(), 214 ArgExprs.take(), ArgExprs.size())); 215 } 216 break; 217 } 218 } 219 } else { 220 attrs.add(AttrFactory.Create(AttrName, AttrNameLoc, 0, AttrNameLoc, 221 0, SourceLocation(), 0, 0)); 222 } 223 } 224 if (ExpectAndConsume(tok::r_paren, diag::err_expected_rparen)) 225 SkipUntil(tok::r_paren, false); 226 SourceLocation Loc = Tok.getLocation(); 227 if (ExpectAndConsume(tok::r_paren, diag::err_expected_rparen)) { 228 SkipUntil(tok::r_paren, false); 229 } 230 if (endLoc) 231 *endLoc = Loc; 232 } 233} 234 235/// ParseMicrosoftDeclSpec - Parse an __declspec construct 236/// 237/// [MS] decl-specifier: 238/// __declspec ( extended-decl-modifier-seq ) 239/// 240/// [MS] extended-decl-modifier-seq: 241/// extended-decl-modifier[opt] 242/// extended-decl-modifier extended-decl-modifier-seq 243 244void Parser::ParseMicrosoftDeclSpec(ParsedAttributes &attrs) { 245 assert(Tok.is(tok::kw___declspec) && "Not a declspec!"); 246 247 ConsumeToken(); 248 if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after, 249 "declspec")) { 250 SkipUntil(tok::r_paren, true); // skip until ) or ; 251 return; 252 } 253 while (Tok.getIdentifierInfo()) { 254 IdentifierInfo *AttrName = Tok.getIdentifierInfo(); 255 SourceLocation AttrNameLoc = ConsumeToken(); 256 if (Tok.is(tok::l_paren)) { 257 ConsumeParen(); 258 // FIXME: This doesn't parse __declspec(property(get=get_func_name)) 259 // correctly. 260 ExprResult ArgExpr(ParseAssignmentExpression()); 261 if (!ArgExpr.isInvalid()) { 262 Expr *ExprList = ArgExpr.take(); 263 attrs.add(AttrFactory.Create(AttrName, AttrNameLoc, 0, AttrNameLoc, 0, 264 SourceLocation(), &ExprList, 1, true)); 265 } 266 if (ExpectAndConsume(tok::r_paren, diag::err_expected_rparen)) 267 SkipUntil(tok::r_paren, false); 268 } else { 269 attrs.add(AttrFactory.Create(AttrName, AttrNameLoc, 0, AttrNameLoc, 270 0, SourceLocation(), 0, 0, true)); 271 } 272 } 273 if (ExpectAndConsume(tok::r_paren, diag::err_expected_rparen)) 274 SkipUntil(tok::r_paren, false); 275 return; 276} 277 278void Parser::ParseMicrosoftTypeAttributes(ParsedAttributes &attrs) { 279 // Treat these like attributes 280 // FIXME: Allow Sema to distinguish between these and real attributes! 281 while (Tok.is(tok::kw___fastcall) || Tok.is(tok::kw___stdcall) || 282 Tok.is(tok::kw___thiscall) || Tok.is(tok::kw___cdecl) || 283 Tok.is(tok::kw___ptr64) || Tok.is(tok::kw___w64)) { 284 IdentifierInfo *AttrName = Tok.getIdentifierInfo(); 285 SourceLocation AttrNameLoc = ConsumeToken(); 286 if (Tok.is(tok::kw___ptr64) || Tok.is(tok::kw___w64)) 287 // FIXME: Support these properly! 288 continue; 289 attrs.add(AttrFactory.Create(AttrName, AttrNameLoc, 0, AttrNameLoc, 0, 290 SourceLocation(), 0, 0, true)); 291 } 292} 293 294void Parser::ParseBorlandTypeAttributes(ParsedAttributes &attrs) { 295 // Treat these like attributes 296 while (Tok.is(tok::kw___pascal)) { 297 IdentifierInfo *AttrName = Tok.getIdentifierInfo(); 298 SourceLocation AttrNameLoc = ConsumeToken(); 299 attrs.add(AttrFactory.Create(AttrName, AttrNameLoc, 0, AttrNameLoc, 0, 300 SourceLocation(), 0, 0, true)); 301 } 302} 303 304void Parser::ParseOpenCLAttributes(ParsedAttributes &attrs) { 305 // Treat these like attributes 306 while (Tok.is(tok::kw___kernel)) { 307 SourceLocation AttrNameLoc = ConsumeToken(); 308 attrs.add(AttrFactory.Create(PP.getIdentifierInfo("opencl_kernel_function"), 309 AttrNameLoc, 0, AttrNameLoc, 0, 310 SourceLocation(), 0, 0, false)); 311 } 312} 313 314void Parser::DiagnoseProhibitedAttributes(ParsedAttributesWithRange &attrs) { 315 Diag(attrs.Range.getBegin(), diag::err_attributes_not_allowed) 316 << attrs.Range; 317} 318 319/// ParseDeclaration - Parse a full 'declaration', which consists of 320/// declaration-specifiers, some number of declarators, and a semicolon. 321/// 'Context' should be a Declarator::TheContext value. This returns the 322/// location of the semicolon in DeclEnd. 323/// 324/// declaration: [C99 6.7] 325/// block-declaration -> 326/// simple-declaration 327/// others [FIXME] 328/// [C++] template-declaration 329/// [C++] namespace-definition 330/// [C++] using-directive 331/// [C++] using-declaration 332/// [C++0x] static_assert-declaration 333/// others... [FIXME] 334/// 335Parser::DeclGroupPtrTy Parser::ParseDeclaration(StmtVector &Stmts, 336 unsigned Context, 337 SourceLocation &DeclEnd, 338 ParsedAttributesWithRange &attrs) { 339 ParenBraceBracketBalancer BalancerRAIIObj(*this); 340 341 Decl *SingleDecl = 0; 342 switch (Tok.getKind()) { 343 case tok::kw_template: 344 case tok::kw_export: 345 ProhibitAttributes(attrs); 346 SingleDecl = ParseDeclarationStartingWithTemplate(Context, DeclEnd); 347 break; 348 case tok::kw_inline: 349 // Could be the start of an inline namespace. Allowed as an ext in C++03. 350 if (getLang().CPlusPlus && NextToken().is(tok::kw_namespace)) { 351 ProhibitAttributes(attrs); 352 SourceLocation InlineLoc = ConsumeToken(); 353 SingleDecl = ParseNamespace(Context, DeclEnd, InlineLoc); 354 break; 355 } 356 return ParseSimpleDeclaration(Stmts, Context, DeclEnd, attrs, 357 true); 358 case tok::kw_namespace: 359 ProhibitAttributes(attrs); 360 SingleDecl = ParseNamespace(Context, DeclEnd); 361 break; 362 case tok::kw_using: 363 SingleDecl = ParseUsingDirectiveOrDeclaration(Context, ParsedTemplateInfo(), 364 DeclEnd, attrs); 365 break; 366 case tok::kw_static_assert: 367 ProhibitAttributes(attrs); 368 SingleDecl = ParseStaticAssertDeclaration(DeclEnd); 369 break; 370 default: 371 return ParseSimpleDeclaration(Stmts, Context, DeclEnd, attrs, true); 372 } 373 374 // This routine returns a DeclGroup, if the thing we parsed only contains a 375 // single decl, convert it now. 376 return Actions.ConvertDeclToDeclGroup(SingleDecl); 377} 378 379/// simple-declaration: [C99 6.7: declaration] [C++ 7p1: dcl.dcl] 380/// declaration-specifiers init-declarator-list[opt] ';' 381///[C90/C++]init-declarator-list ';' [TODO] 382/// [OMP] threadprivate-directive [TODO] 383/// 384/// If RequireSemi is false, this does not check for a ';' at the end of the 385/// declaration. If it is true, it checks for and eats it. 386Parser::DeclGroupPtrTy Parser::ParseSimpleDeclaration(StmtVector &Stmts, 387 unsigned Context, 388 SourceLocation &DeclEnd, 389 ParsedAttributes &attrs, 390 bool RequireSemi) { 391 // Parse the common declaration-specifiers piece. 392 ParsingDeclSpec DS(*this); 393 DS.takeAttributesFrom(attrs); 394 ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS_none, 395 getDeclSpecContextFromDeclaratorContext(Context)); 396 StmtResult R = Actions.ActOnVlaStmt(DS); 397 if (R.isUsable()) 398 Stmts.push_back(R.release()); 399 400 // C99 6.7.2.3p6: Handle "struct-or-union identifier;", "enum { X };" 401 // declaration-specifiers init-declarator-list[opt] ';' 402 if (Tok.is(tok::semi)) { 403 if (RequireSemi) ConsumeToken(); 404 Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS_none, 405 DS); 406 DS.complete(TheDecl); 407 return Actions.ConvertDeclToDeclGroup(TheDecl); 408 } 409 410 return ParseDeclGroup(DS, Context, /*FunctionDefs=*/ false, &DeclEnd); 411} 412 413/// ParseDeclGroup - Having concluded that this is either a function 414/// definition or a group of object declarations, actually parse the 415/// result. 416Parser::DeclGroupPtrTy Parser::ParseDeclGroup(ParsingDeclSpec &DS, 417 unsigned Context, 418 bool AllowFunctionDefinitions, 419 SourceLocation *DeclEnd) { 420 // Parse the first declarator. 421 ParsingDeclarator D(*this, DS, static_cast<Declarator::TheContext>(Context)); 422 ParseDeclarator(D); 423 424 // Bail out if the first declarator didn't seem well-formed. 425 if (!D.hasName() && !D.mayOmitIdentifier()) { 426 // Skip until ; or }. 427 SkipUntil(tok::r_brace, true, true); 428 if (Tok.is(tok::semi)) 429 ConsumeToken(); 430 return DeclGroupPtrTy(); 431 } 432 433 // Check to see if we have a function *definition* which must have a body. 434 if (AllowFunctionDefinitions && D.isFunctionDeclarator() && 435 // Look at the next token to make sure that this isn't a function 436 // declaration. We have to check this because __attribute__ might be the 437 // start of a function definition in GCC-extended K&R C. 438 !isDeclarationAfterDeclarator()) { 439 440 if (isStartOfFunctionDefinition(D)) { 441 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) { 442 Diag(Tok, diag::err_function_declared_typedef); 443 444 // Recover by treating the 'typedef' as spurious. 445 DS.ClearStorageClassSpecs(); 446 } 447 448 Decl *TheDecl = ParseFunctionDefinition(D); 449 return Actions.ConvertDeclToDeclGroup(TheDecl); 450 } 451 452 if (isDeclarationSpecifier()) { 453 // If there is an invalid declaration specifier right after the function 454 // prototype, then we must be in a missing semicolon case where this isn't 455 // actually a body. Just fall through into the code that handles it as a 456 // prototype, and let the top-level code handle the erroneous declspec 457 // where it would otherwise expect a comma or semicolon. 458 } else { 459 Diag(Tok, diag::err_expected_fn_body); 460 SkipUntil(tok::semi); 461 return DeclGroupPtrTy(); 462 } 463 } 464 465 llvm::SmallVector<Decl *, 8> DeclsInGroup; 466 Decl *FirstDecl = ParseDeclarationAfterDeclarator(D); 467 D.complete(FirstDecl); 468 if (FirstDecl) 469 DeclsInGroup.push_back(FirstDecl); 470 471 // If we don't have a comma, it is either the end of the list (a ';') or an 472 // error, bail out. 473 while (Tok.is(tok::comma)) { 474 // Consume the comma. 475 ConsumeToken(); 476 477 // Parse the next declarator. 478 D.clear(); 479 480 // Accept attributes in an init-declarator. In the first declarator in a 481 // declaration, these would be part of the declspec. In subsequent 482 // declarators, they become part of the declarator itself, so that they 483 // don't apply to declarators after *this* one. Examples: 484 // short __attribute__((common)) var; -> declspec 485 // short var __attribute__((common)); -> declarator 486 // short x, __attribute__((common)) var; -> declarator 487 MaybeParseGNUAttributes(D); 488 489 ParseDeclarator(D); 490 491 Decl *ThisDecl = ParseDeclarationAfterDeclarator(D); 492 D.complete(ThisDecl); 493 if (ThisDecl) 494 DeclsInGroup.push_back(ThisDecl); 495 } 496 497 if (DeclEnd) 498 *DeclEnd = Tok.getLocation(); 499 500 if (Context != Declarator::ForContext && 501 ExpectAndConsume(tok::semi, 502 Context == Declarator::FileContext 503 ? diag::err_invalid_token_after_toplevel_declarator 504 : diag::err_expected_semi_declaration)) { 505 // Okay, there was no semicolon and one was expected. If we see a 506 // declaration specifier, just assume it was missing and continue parsing. 507 // Otherwise things are very confused and we skip to recover. 508 if (!isDeclarationSpecifier()) { 509 SkipUntil(tok::r_brace, true, true); 510 if (Tok.is(tok::semi)) 511 ConsumeToken(); 512 } 513 } 514 515 return Actions.FinalizeDeclaratorGroup(getCurScope(), DS, 516 DeclsInGroup.data(), 517 DeclsInGroup.size()); 518} 519 520/// \brief Parse 'declaration' after parsing 'declaration-specifiers 521/// declarator'. This method parses the remainder of the declaration 522/// (including any attributes or initializer, among other things) and 523/// finalizes the declaration. 524/// 525/// init-declarator: [C99 6.7] 526/// declarator 527/// declarator '=' initializer 528/// [GNU] declarator simple-asm-expr[opt] attributes[opt] 529/// [GNU] declarator simple-asm-expr[opt] attributes[opt] '=' initializer 530/// [C++] declarator initializer[opt] 531/// 532/// [C++] initializer: 533/// [C++] '=' initializer-clause 534/// [C++] '(' expression-list ')' 535/// [C++0x] '=' 'default' [TODO] 536/// [C++0x] '=' 'delete' 537/// 538/// According to the standard grammar, =default and =delete are function 539/// definitions, but that definitely doesn't fit with the parser here. 540/// 541Decl *Parser::ParseDeclarationAfterDeclarator(Declarator &D, 542 const ParsedTemplateInfo &TemplateInfo) { 543 // If a simple-asm-expr is present, parse it. 544 if (Tok.is(tok::kw_asm)) { 545 SourceLocation Loc; 546 ExprResult AsmLabel(ParseSimpleAsm(&Loc)); 547 if (AsmLabel.isInvalid()) { 548 SkipUntil(tok::semi, true, true); 549 return 0; 550 } 551 552 D.setAsmLabel(AsmLabel.release()); 553 D.SetRangeEnd(Loc); 554 } 555 556 MaybeParseGNUAttributes(D); 557 558 // Inform the current actions module that we just parsed this declarator. 559 Decl *ThisDecl = 0; 560 switch (TemplateInfo.Kind) { 561 case ParsedTemplateInfo::NonTemplate: 562 ThisDecl = Actions.ActOnDeclarator(getCurScope(), D); 563 break; 564 565 case ParsedTemplateInfo::Template: 566 case ParsedTemplateInfo::ExplicitSpecialization: 567 ThisDecl = Actions.ActOnTemplateDeclarator(getCurScope(), 568 MultiTemplateParamsArg(Actions, 569 TemplateInfo.TemplateParams->data(), 570 TemplateInfo.TemplateParams->size()), 571 D); 572 break; 573 574 case ParsedTemplateInfo::ExplicitInstantiation: { 575 DeclResult ThisRes 576 = Actions.ActOnExplicitInstantiation(getCurScope(), 577 TemplateInfo.ExternLoc, 578 TemplateInfo.TemplateLoc, 579 D); 580 if (ThisRes.isInvalid()) { 581 SkipUntil(tok::semi, true, true); 582 return 0; 583 } 584 585 ThisDecl = ThisRes.get(); 586 break; 587 } 588 } 589 590 bool TypeContainsAuto = 591 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto; 592 593 // Parse declarator '=' initializer. 594 if (isTokenEqualOrMistypedEqualEqual( 595 diag::err_invalid_equalequal_after_declarator)) { 596 ConsumeToken(); 597 if (Tok.is(tok::kw_delete)) { 598 SourceLocation DelLoc = ConsumeToken(); 599 600 if (!getLang().CPlusPlus0x) 601 Diag(DelLoc, diag::warn_deleted_function_accepted_as_extension); 602 603 Actions.SetDeclDeleted(ThisDecl, DelLoc); 604 } else { 605 if (getLang().CPlusPlus && D.getCXXScopeSpec().isSet()) { 606 EnterScope(0); 607 Actions.ActOnCXXEnterDeclInitializer(getCurScope(), ThisDecl); 608 } 609 610 if (Tok.is(tok::code_completion)) { 611 Actions.CodeCompleteInitializer(getCurScope(), ThisDecl); 612 ConsumeCodeCompletionToken(); 613 SkipUntil(tok::comma, true, true); 614 return ThisDecl; 615 } 616 617 ExprResult Init(ParseInitializer()); 618 619 if (getLang().CPlusPlus && D.getCXXScopeSpec().isSet()) { 620 Actions.ActOnCXXExitDeclInitializer(getCurScope(), ThisDecl); 621 ExitScope(); 622 } 623 624 if (Init.isInvalid()) { 625 SkipUntil(tok::comma, true, true); 626 Actions.ActOnInitializerError(ThisDecl); 627 } else 628 Actions.AddInitializerToDecl(ThisDecl, Init.take(), 629 /*DirectInit=*/false, TypeContainsAuto); 630 } 631 } else if (Tok.is(tok::l_paren)) { 632 // Parse C++ direct initializer: '(' expression-list ')' 633 SourceLocation LParenLoc = ConsumeParen(); 634 ExprVector Exprs(Actions); 635 CommaLocsTy CommaLocs; 636 637 if (getLang().CPlusPlus && D.getCXXScopeSpec().isSet()) { 638 EnterScope(0); 639 Actions.ActOnCXXEnterDeclInitializer(getCurScope(), ThisDecl); 640 } 641 642 if (ParseExpressionList(Exprs, CommaLocs)) { 643 SkipUntil(tok::r_paren); 644 645 if (getLang().CPlusPlus && D.getCXXScopeSpec().isSet()) { 646 Actions.ActOnCXXExitDeclInitializer(getCurScope(), ThisDecl); 647 ExitScope(); 648 } 649 } else { 650 // Match the ')'. 651 SourceLocation RParenLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc); 652 653 assert(!Exprs.empty() && Exprs.size()-1 == CommaLocs.size() && 654 "Unexpected number of commas!"); 655 656 if (getLang().CPlusPlus && D.getCXXScopeSpec().isSet()) { 657 Actions.ActOnCXXExitDeclInitializer(getCurScope(), ThisDecl); 658 ExitScope(); 659 } 660 661 Actions.AddCXXDirectInitializerToDecl(ThisDecl, LParenLoc, 662 move_arg(Exprs), 663 RParenLoc, 664 TypeContainsAuto); 665 } 666 } else { 667 Actions.ActOnUninitializedDecl(ThisDecl, TypeContainsAuto); 668 } 669 670 Actions.FinalizeDeclaration(ThisDecl); 671 672 return ThisDecl; 673} 674 675/// ParseSpecifierQualifierList 676/// specifier-qualifier-list: 677/// type-specifier specifier-qualifier-list[opt] 678/// type-qualifier specifier-qualifier-list[opt] 679/// [GNU] attributes specifier-qualifier-list[opt] 680/// 681void Parser::ParseSpecifierQualifierList(DeclSpec &DS) { 682 /// specifier-qualifier-list is a subset of declaration-specifiers. Just 683 /// parse declaration-specifiers and complain about extra stuff. 684 ParseDeclarationSpecifiers(DS); 685 686 // Validate declspec for type-name. 687 unsigned Specs = DS.getParsedSpecifiers(); 688 if (Specs == DeclSpec::PQ_None && !DS.getNumProtocolQualifiers() && 689 !DS.hasAttributes()) 690 Diag(Tok, diag::err_typename_requires_specqual); 691 692 // Issue diagnostic and remove storage class if present. 693 if (Specs & DeclSpec::PQ_StorageClassSpecifier) { 694 if (DS.getStorageClassSpecLoc().isValid()) 695 Diag(DS.getStorageClassSpecLoc(),diag::err_typename_invalid_storageclass); 696 else 697 Diag(DS.getThreadSpecLoc(), diag::err_typename_invalid_storageclass); 698 DS.ClearStorageClassSpecs(); 699 } 700 701 // Issue diagnostic and remove function specfier if present. 702 if (Specs & DeclSpec::PQ_FunctionSpecifier) { 703 if (DS.isInlineSpecified()) 704 Diag(DS.getInlineSpecLoc(), diag::err_typename_invalid_functionspec); 705 if (DS.isVirtualSpecified()) 706 Diag(DS.getVirtualSpecLoc(), diag::err_typename_invalid_functionspec); 707 if (DS.isExplicitSpecified()) 708 Diag(DS.getExplicitSpecLoc(), diag::err_typename_invalid_functionspec); 709 DS.ClearFunctionSpecs(); 710 } 711} 712 713/// isValidAfterIdentifierInDeclaratorAfterDeclSpec - Return true if the 714/// specified token is valid after the identifier in a declarator which 715/// immediately follows the declspec. For example, these things are valid: 716/// 717/// int x [ 4]; // direct-declarator 718/// int x ( int y); // direct-declarator 719/// int(int x ) // direct-declarator 720/// int x ; // simple-declaration 721/// int x = 17; // init-declarator-list 722/// int x , y; // init-declarator-list 723/// int x __asm__ ("foo"); // init-declarator-list 724/// int x : 4; // struct-declarator 725/// int x { 5}; // C++'0x unified initializers 726/// 727/// This is not, because 'x' does not immediately follow the declspec (though 728/// ')' happens to be valid anyway). 729/// int (x) 730/// 731static bool isValidAfterIdentifierInDeclarator(const Token &T) { 732 return T.is(tok::l_square) || T.is(tok::l_paren) || T.is(tok::r_paren) || 733 T.is(tok::semi) || T.is(tok::comma) || T.is(tok::equal) || 734 T.is(tok::kw_asm) || T.is(tok::l_brace) || T.is(tok::colon); 735} 736 737 738/// ParseImplicitInt - This method is called when we have an non-typename 739/// identifier in a declspec (which normally terminates the decl spec) when 740/// the declspec has no type specifier. In this case, the declspec is either 741/// malformed or is "implicit int" (in K&R and C89). 742/// 743/// This method handles diagnosing this prettily and returns false if the 744/// declspec is done being processed. If it recovers and thinks there may be 745/// other pieces of declspec after it, it returns true. 746/// 747bool Parser::ParseImplicitInt(DeclSpec &DS, CXXScopeSpec *SS, 748 const ParsedTemplateInfo &TemplateInfo, 749 AccessSpecifier AS) { 750 assert(Tok.is(tok::identifier) && "should have identifier"); 751 752 SourceLocation Loc = Tok.getLocation(); 753 // If we see an identifier that is not a type name, we normally would 754 // parse it as the identifer being declared. However, when a typename 755 // is typo'd or the definition is not included, this will incorrectly 756 // parse the typename as the identifier name and fall over misparsing 757 // later parts of the diagnostic. 758 // 759 // As such, we try to do some look-ahead in cases where this would 760 // otherwise be an "implicit-int" case to see if this is invalid. For 761 // example: "static foo_t x = 4;" In this case, if we parsed foo_t as 762 // an identifier with implicit int, we'd get a parse error because the 763 // next token is obviously invalid for a type. Parse these as a case 764 // with an invalid type specifier. 765 assert(!DS.hasTypeSpecifier() && "Type specifier checked above"); 766 767 // Since we know that this either implicit int (which is rare) or an 768 // error, we'd do lookahead to try to do better recovery. 769 if (isValidAfterIdentifierInDeclarator(NextToken())) { 770 // If this token is valid for implicit int, e.g. "static x = 4", then 771 // we just avoid eating the identifier, so it will be parsed as the 772 // identifier in the declarator. 773 return false; 774 } 775 776 // Otherwise, if we don't consume this token, we are going to emit an 777 // error anyway. Try to recover from various common problems. Check 778 // to see if this was a reference to a tag name without a tag specified. 779 // This is a common problem in C (saying 'foo' instead of 'struct foo'). 780 // 781 // C++ doesn't need this, and isTagName doesn't take SS. 782 if (SS == 0) { 783 const char *TagName = 0; 784 tok::TokenKind TagKind = tok::unknown; 785 786 switch (Actions.isTagName(*Tok.getIdentifierInfo(), getCurScope())) { 787 default: break; 788 case DeclSpec::TST_enum: TagName="enum" ;TagKind=tok::kw_enum ;break; 789 case DeclSpec::TST_union: TagName="union" ;TagKind=tok::kw_union ;break; 790 case DeclSpec::TST_struct:TagName="struct";TagKind=tok::kw_struct;break; 791 case DeclSpec::TST_class: TagName="class" ;TagKind=tok::kw_class ;break; 792 } 793 794 if (TagName) { 795 Diag(Loc, diag::err_use_of_tag_name_without_tag) 796 << Tok.getIdentifierInfo() << TagName << getLang().CPlusPlus 797 << FixItHint::CreateInsertion(Tok.getLocation(),TagName); 798 799 // Parse this as a tag as if the missing tag were present. 800 if (TagKind == tok::kw_enum) 801 ParseEnumSpecifier(Loc, DS, TemplateInfo, AS); 802 else 803 ParseClassSpecifier(TagKind, Loc, DS, TemplateInfo, AS); 804 return true; 805 } 806 } 807 808 // This is almost certainly an invalid type name. Let the action emit a 809 // diagnostic and attempt to recover. 810 ParsedType T; 811 if (Actions.DiagnoseUnknownTypeName(*Tok.getIdentifierInfo(), Loc, 812 getCurScope(), SS, T)) { 813 // The action emitted a diagnostic, so we don't have to. 814 if (T) { 815 // The action has suggested that the type T could be used. Set that as 816 // the type in the declaration specifiers, consume the would-be type 817 // name token, and we're done. 818 const char *PrevSpec; 819 unsigned DiagID; 820 DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID, T); 821 DS.SetRangeEnd(Tok.getLocation()); 822 ConsumeToken(); 823 824 // There may be other declaration specifiers after this. 825 return true; 826 } 827 828 // Fall through; the action had no suggestion for us. 829 } else { 830 // The action did not emit a diagnostic, so emit one now. 831 SourceRange R; 832 if (SS) R = SS->getRange(); 833 Diag(Loc, diag::err_unknown_typename) << Tok.getIdentifierInfo() << R; 834 } 835 836 // Mark this as an error. 837 const char *PrevSpec; 838 unsigned DiagID; 839 DS.SetTypeSpecType(DeclSpec::TST_error, Loc, PrevSpec, DiagID); 840 DS.SetRangeEnd(Tok.getLocation()); 841 ConsumeToken(); 842 843 // TODO: Could inject an invalid typedef decl in an enclosing scope to 844 // avoid rippling error messages on subsequent uses of the same type, 845 // could be useful if #include was forgotten. 846 return false; 847} 848 849/// \brief Determine the declaration specifier context from the declarator 850/// context. 851/// 852/// \param Context the declarator context, which is one of the 853/// Declarator::TheContext enumerator values. 854Parser::DeclSpecContext 855Parser::getDeclSpecContextFromDeclaratorContext(unsigned Context) { 856 if (Context == Declarator::MemberContext) 857 return DSC_class; 858 if (Context == Declarator::FileContext) 859 return DSC_top_level; 860 return DSC_normal; 861} 862 863/// ParseDeclarationSpecifiers 864/// declaration-specifiers: [C99 6.7] 865/// storage-class-specifier declaration-specifiers[opt] 866/// type-specifier declaration-specifiers[opt] 867/// [C99] function-specifier declaration-specifiers[opt] 868/// [GNU] attributes declaration-specifiers[opt] 869/// 870/// storage-class-specifier: [C99 6.7.1] 871/// 'typedef' 872/// 'extern' 873/// 'static' 874/// 'auto' 875/// 'register' 876/// [C++] 'mutable' 877/// [GNU] '__thread' 878/// function-specifier: [C99 6.7.4] 879/// [C99] 'inline' 880/// [C++] 'virtual' 881/// [C++] 'explicit' 882/// [OpenCL] '__kernel' 883/// 'friend': [C++ dcl.friend] 884/// 'constexpr': [C++0x dcl.constexpr] 885 886/// 887void Parser::ParseDeclarationSpecifiers(DeclSpec &DS, 888 const ParsedTemplateInfo &TemplateInfo, 889 AccessSpecifier AS, 890 DeclSpecContext DSContext) { 891 DS.SetRangeStart(Tok.getLocation()); 892 DS.SetRangeEnd(Tok.getLocation()); 893 while (1) { 894 bool isInvalid = false; 895 const char *PrevSpec = 0; 896 unsigned DiagID = 0; 897 898 SourceLocation Loc = Tok.getLocation(); 899 900 switch (Tok.getKind()) { 901 default: 902 DoneWithDeclSpec: 903 // If this is not a declaration specifier token, we're done reading decl 904 // specifiers. First verify that DeclSpec's are consistent. 905 DS.Finish(Diags, PP); 906 return; 907 908 case tok::code_completion: { 909 Sema::ParserCompletionContext CCC = Sema::PCC_Namespace; 910 if (DS.hasTypeSpecifier()) { 911 bool AllowNonIdentifiers 912 = (getCurScope()->getFlags() & (Scope::ControlScope | 913 Scope::BlockScope | 914 Scope::TemplateParamScope | 915 Scope::FunctionPrototypeScope | 916 Scope::AtCatchScope)) == 0; 917 bool AllowNestedNameSpecifiers 918 = DSContext == DSC_top_level || 919 (DSContext == DSC_class && DS.isFriendSpecified()); 920 921 Actions.CodeCompleteDeclSpec(getCurScope(), DS, 922 AllowNonIdentifiers, 923 AllowNestedNameSpecifiers); 924 ConsumeCodeCompletionToken(); 925 return; 926 } 927 928 if (getCurScope()->getFnParent() || getCurScope()->getBlockParent()) 929 CCC = Sema::PCC_LocalDeclarationSpecifiers; 930 else if (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate) 931 CCC = DSContext == DSC_class? Sema::PCC_MemberTemplate 932 : Sema::PCC_Template; 933 else if (DSContext == DSC_class) 934 CCC = Sema::PCC_Class; 935 else if (ObjCImpDecl) 936 CCC = Sema::PCC_ObjCImplementation; 937 938 Actions.CodeCompleteOrdinaryName(getCurScope(), CCC); 939 ConsumeCodeCompletionToken(); 940 return; 941 } 942 943 case tok::coloncolon: // ::foo::bar 944 // C++ scope specifier. Annotate and loop, or bail out on error. 945 if (TryAnnotateCXXScopeToken(true)) { 946 if (!DS.hasTypeSpecifier()) 947 DS.SetTypeSpecError(); 948 goto DoneWithDeclSpec; 949 } 950 if (Tok.is(tok::coloncolon)) // ::new or ::delete 951 goto DoneWithDeclSpec; 952 continue; 953 954 case tok::annot_cxxscope: { 955 if (DS.hasTypeSpecifier()) 956 goto DoneWithDeclSpec; 957 958 CXXScopeSpec SS; 959 Actions.RestoreNestedNameSpecifierAnnotation(Tok.getAnnotationValue(), 960 Tok.getAnnotationRange(), 961 SS); 962 963 // We are looking for a qualified typename. 964 Token Next = NextToken(); 965 if (Next.is(tok::annot_template_id) && 966 static_cast<TemplateIdAnnotation *>(Next.getAnnotationValue()) 967 ->Kind == TNK_Type_template) { 968 // We have a qualified template-id, e.g., N::A<int> 969 970 // C++ [class.qual]p2: 971 // In a lookup in which the constructor is an acceptable lookup 972 // result and the nested-name-specifier nominates a class C: 973 // 974 // - if the name specified after the 975 // nested-name-specifier, when looked up in C, is the 976 // injected-class-name of C (Clause 9), or 977 // 978 // - if the name specified after the nested-name-specifier 979 // is the same as the identifier or the 980 // simple-template-id's template-name in the last 981 // component of the nested-name-specifier, 982 // 983 // the name is instead considered to name the constructor of 984 // class C. 985 // 986 // Thus, if the template-name is actually the constructor 987 // name, then the code is ill-formed; this interpretation is 988 // reinforced by the NAD status of core issue 635. 989 TemplateIdAnnotation *TemplateId 990 = static_cast<TemplateIdAnnotation *>(Next.getAnnotationValue()); 991 if ((DSContext == DSC_top_level || 992 (DSContext == DSC_class && DS.isFriendSpecified())) && 993 TemplateId->Name && 994 Actions.isCurrentClassName(*TemplateId->Name, getCurScope(), &SS)) { 995 if (isConstructorDeclarator()) { 996 // The user meant this to be an out-of-line constructor 997 // definition, but template arguments are not allowed 998 // there. Just allow this as a constructor; we'll 999 // complain about it later. 1000 goto DoneWithDeclSpec; 1001 } 1002 1003 // The user meant this to name a type, but it actually names 1004 // a constructor with some extraneous template 1005 // arguments. Complain, then parse it as a type as the user 1006 // intended. 1007 Diag(TemplateId->TemplateNameLoc, 1008 diag::err_out_of_line_template_id_names_constructor) 1009 << TemplateId->Name; 1010 } 1011 1012 DS.getTypeSpecScope() = SS; 1013 ConsumeToken(); // The C++ scope. 1014 assert(Tok.is(tok::annot_template_id) && 1015 "ParseOptionalCXXScopeSpecifier not working"); 1016 AnnotateTemplateIdTokenAsType(&SS); 1017 continue; 1018 } 1019 1020 if (Next.is(tok::annot_typename)) { 1021 DS.getTypeSpecScope() = SS; 1022 ConsumeToken(); // The C++ scope. 1023 if (Tok.getAnnotationValue()) { 1024 ParsedType T = getTypeAnnotation(Tok); 1025 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, 1026 Tok.getAnnotationEndLoc(), 1027 PrevSpec, DiagID, T); 1028 } 1029 else 1030 DS.SetTypeSpecError(); 1031 DS.SetRangeEnd(Tok.getAnnotationEndLoc()); 1032 ConsumeToken(); // The typename 1033 } 1034 1035 if (Next.isNot(tok::identifier)) 1036 goto DoneWithDeclSpec; 1037 1038 // If we're in a context where the identifier could be a class name, 1039 // check whether this is a constructor declaration. 1040 if ((DSContext == DSC_top_level || 1041 (DSContext == DSC_class && DS.isFriendSpecified())) && 1042 Actions.isCurrentClassName(*Next.getIdentifierInfo(), getCurScope(), 1043 &SS)) { 1044 if (isConstructorDeclarator()) 1045 goto DoneWithDeclSpec; 1046 1047 // As noted in C++ [class.qual]p2 (cited above), when the name 1048 // of the class is qualified in a context where it could name 1049 // a constructor, its a constructor name. However, we've 1050 // looked at the declarator, and the user probably meant this 1051 // to be a type. Complain that it isn't supposed to be treated 1052 // as a type, then proceed to parse it as a type. 1053 Diag(Next.getLocation(), diag::err_out_of_line_type_names_constructor) 1054 << Next.getIdentifierInfo(); 1055 } 1056 1057 ParsedType TypeRep = Actions.getTypeName(*Next.getIdentifierInfo(), 1058 Next.getLocation(), 1059 getCurScope(), &SS); 1060 1061 // If the referenced identifier is not a type, then this declspec is 1062 // erroneous: We already checked about that it has no type specifier, and 1063 // C++ doesn't have implicit int. Diagnose it as a typo w.r.t. to the 1064 // typename. 1065 if (TypeRep == 0) { 1066 ConsumeToken(); // Eat the scope spec so the identifier is current. 1067 if (ParseImplicitInt(DS, &SS, TemplateInfo, AS)) continue; 1068 goto DoneWithDeclSpec; 1069 } 1070 1071 DS.getTypeSpecScope() = SS; 1072 ConsumeToken(); // The C++ scope. 1073 1074 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, 1075 DiagID, TypeRep); 1076 if (isInvalid) 1077 break; 1078 1079 DS.SetRangeEnd(Tok.getLocation()); 1080 ConsumeToken(); // The typename. 1081 1082 continue; 1083 } 1084 1085 case tok::annot_typename: { 1086 if (Tok.getAnnotationValue()) { 1087 ParsedType T = getTypeAnnotation(Tok); 1088 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, 1089 DiagID, T); 1090 } else 1091 DS.SetTypeSpecError(); 1092 1093 if (isInvalid) 1094 break; 1095 1096 DS.SetRangeEnd(Tok.getAnnotationEndLoc()); 1097 ConsumeToken(); // The typename 1098 1099 // Objective-C supports syntax of the form 'id<proto1,proto2>' where 'id' 1100 // is a specific typedef and 'itf<proto1,proto2>' where 'itf' is an 1101 // Objective-C interface. 1102 if (Tok.is(tok::less) && getLang().ObjC1) 1103 ParseObjCProtocolQualifiers(DS); 1104 1105 continue; 1106 } 1107 1108 // typedef-name 1109 case tok::identifier: { 1110 // In C++, check to see if this is a scope specifier like foo::bar::, if 1111 // so handle it as such. This is important for ctor parsing. 1112 if (getLang().CPlusPlus) { 1113 if (TryAnnotateCXXScopeToken(true)) { 1114 if (!DS.hasTypeSpecifier()) 1115 DS.SetTypeSpecError(); 1116 goto DoneWithDeclSpec; 1117 } 1118 if (!Tok.is(tok::identifier)) 1119 continue; 1120 } 1121 1122 // This identifier can only be a typedef name if we haven't already seen 1123 // a type-specifier. Without this check we misparse: 1124 // typedef int X; struct Y { short X; }; as 'short int'. 1125 if (DS.hasTypeSpecifier()) 1126 goto DoneWithDeclSpec; 1127 1128 // Check for need to substitute AltiVec keyword tokens. 1129 if (TryAltiVecToken(DS, Loc, PrevSpec, DiagID, isInvalid)) 1130 break; 1131 1132 // It has to be available as a typedef too! 1133 ParsedType TypeRep = 1134 Actions.getTypeName(*Tok.getIdentifierInfo(), 1135 Tok.getLocation(), getCurScope()); 1136 1137 // If this is not a typedef name, don't parse it as part of the declspec, 1138 // it must be an implicit int or an error. 1139 if (!TypeRep) { 1140 if (ParseImplicitInt(DS, 0, TemplateInfo, AS)) continue; 1141 goto DoneWithDeclSpec; 1142 } 1143 1144 // If we're in a context where the identifier could be a class name, 1145 // check whether this is a constructor declaration. 1146 if (getLang().CPlusPlus && DSContext == DSC_class && 1147 Actions.isCurrentClassName(*Tok.getIdentifierInfo(), getCurScope()) && 1148 isConstructorDeclarator()) 1149 goto DoneWithDeclSpec; 1150 1151 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, 1152 DiagID, TypeRep); 1153 if (isInvalid) 1154 break; 1155 1156 DS.SetRangeEnd(Tok.getLocation()); 1157 ConsumeToken(); // The identifier 1158 1159 // Objective-C supports syntax of the form 'id<proto1,proto2>' where 'id' 1160 // is a specific typedef and 'itf<proto1,proto2>' where 'itf' is an 1161 // Objective-C interface. 1162 if (Tok.is(tok::less) && getLang().ObjC1) 1163 ParseObjCProtocolQualifiers(DS); 1164 1165 // Need to support trailing type qualifiers (e.g. "id<p> const"). 1166 // If a type specifier follows, it will be diagnosed elsewhere. 1167 continue; 1168 } 1169 1170 // type-name 1171 case tok::annot_template_id: { 1172 TemplateIdAnnotation *TemplateId 1173 = static_cast<TemplateIdAnnotation *>(Tok.getAnnotationValue()); 1174 if (TemplateId->Kind != TNK_Type_template) { 1175 // This template-id does not refer to a type name, so we're 1176 // done with the type-specifiers. 1177 goto DoneWithDeclSpec; 1178 } 1179 1180 // If we're in a context where the template-id could be a 1181 // constructor name or specialization, check whether this is a 1182 // constructor declaration. 1183 if (getLang().CPlusPlus && DSContext == DSC_class && 1184 Actions.isCurrentClassName(*TemplateId->Name, getCurScope()) && 1185 isConstructorDeclarator()) 1186 goto DoneWithDeclSpec; 1187 1188 // Turn the template-id annotation token into a type annotation 1189 // token, then try again to parse it as a type-specifier. 1190 AnnotateTemplateIdTokenAsType(); 1191 continue; 1192 } 1193 1194 // GNU attributes support. 1195 case tok::kw___attribute: 1196 ParseGNUAttributes(DS.getAttributes()); 1197 continue; 1198 1199 // Microsoft declspec support. 1200 case tok::kw___declspec: 1201 ParseMicrosoftDeclSpec(DS.getAttributes()); 1202 continue; 1203 1204 // Microsoft single token adornments. 1205 case tok::kw___forceinline: 1206 // FIXME: Add handling here! 1207 break; 1208 1209 case tok::kw___ptr64: 1210 case tok::kw___w64: 1211 case tok::kw___cdecl: 1212 case tok::kw___stdcall: 1213 case tok::kw___fastcall: 1214 case tok::kw___thiscall: 1215 ParseMicrosoftTypeAttributes(DS.getAttributes()); 1216 continue; 1217 1218 // Borland single token adornments. 1219 case tok::kw___pascal: 1220 ParseBorlandTypeAttributes(DS.getAttributes()); 1221 continue; 1222 1223 // OpenCL single token adornments. 1224 case tok::kw___kernel: 1225 ParseOpenCLAttributes(DS.getAttributes()); 1226 continue; 1227 1228 // storage-class-specifier 1229 case tok::kw_typedef: 1230 isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_typedef, Loc, PrevSpec, 1231 DiagID, getLang()); 1232 break; 1233 case tok::kw_extern: 1234 if (DS.isThreadSpecified()) 1235 Diag(Tok, diag::ext_thread_before) << "extern"; 1236 isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_extern, Loc, PrevSpec, 1237 DiagID, getLang()); 1238 break; 1239 case tok::kw___private_extern__: 1240 isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_private_extern, Loc, 1241 PrevSpec, DiagID, getLang()); 1242 break; 1243 case tok::kw_static: 1244 if (DS.isThreadSpecified()) 1245 Diag(Tok, diag::ext_thread_before) << "static"; 1246 isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_static, Loc, PrevSpec, 1247 DiagID, getLang()); 1248 break; 1249 case tok::kw_auto: 1250 if (getLang().CPlusPlus0x || getLang().ObjC2) { 1251 if (isKnownToBeTypeSpecifier(GetLookAheadToken(1))) { 1252 isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_auto, Loc, PrevSpec, 1253 DiagID, getLang()); 1254 if (!isInvalid) 1255 Diag(Tok, diag::auto_storage_class) 1256 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 1257 } 1258 else 1259 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_auto, Loc, PrevSpec, 1260 DiagID); 1261 } 1262 else 1263 isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_auto, Loc, PrevSpec, 1264 DiagID, getLang()); 1265 break; 1266 case tok::kw_register: 1267 isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_register, Loc, PrevSpec, 1268 DiagID, getLang()); 1269 break; 1270 case tok::kw_mutable: 1271 isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_mutable, Loc, PrevSpec, 1272 DiagID, getLang()); 1273 break; 1274 case tok::kw___thread: 1275 isInvalid = DS.SetStorageClassSpecThread(Loc, PrevSpec, DiagID); 1276 break; 1277 1278 // function-specifier 1279 case tok::kw_inline: 1280 isInvalid = DS.SetFunctionSpecInline(Loc, PrevSpec, DiagID); 1281 break; 1282 case tok::kw_virtual: 1283 isInvalid = DS.SetFunctionSpecVirtual(Loc, PrevSpec, DiagID); 1284 break; 1285 case tok::kw_explicit: 1286 isInvalid = DS.SetFunctionSpecExplicit(Loc, PrevSpec, DiagID); 1287 break; 1288 1289 // friend 1290 case tok::kw_friend: 1291 if (DSContext == DSC_class) 1292 isInvalid = DS.SetFriendSpec(Loc, PrevSpec, DiagID); 1293 else { 1294 PrevSpec = ""; // not actually used by the diagnostic 1295 DiagID = diag::err_friend_invalid_in_context; 1296 isInvalid = true; 1297 } 1298 break; 1299 1300 // constexpr 1301 case tok::kw_constexpr: 1302 isInvalid = DS.SetConstexprSpec(Loc, PrevSpec, DiagID); 1303 break; 1304 1305 // type-specifier 1306 case tok::kw_short: 1307 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_short, Loc, PrevSpec, 1308 DiagID); 1309 break; 1310 case tok::kw_long: 1311 if (DS.getTypeSpecWidth() != DeclSpec::TSW_long) 1312 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_long, Loc, PrevSpec, 1313 DiagID); 1314 else 1315 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec, 1316 DiagID); 1317 break; 1318 case tok::kw_signed: 1319 isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_signed, Loc, PrevSpec, 1320 DiagID); 1321 break; 1322 case tok::kw_unsigned: 1323 isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_unsigned, Loc, PrevSpec, 1324 DiagID); 1325 break; 1326 case tok::kw__Complex: 1327 isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_complex, Loc, PrevSpec, 1328 DiagID); 1329 break; 1330 case tok::kw__Imaginary: 1331 isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_imaginary, Loc, PrevSpec, 1332 DiagID); 1333 break; 1334 case tok::kw_void: 1335 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec, 1336 DiagID); 1337 break; 1338 case tok::kw_char: 1339 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec, 1340 DiagID); 1341 break; 1342 case tok::kw_int: 1343 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec, 1344 DiagID); 1345 break; 1346 case tok::kw_float: 1347 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec, 1348 DiagID); 1349 break; 1350 case tok::kw_double: 1351 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec, 1352 DiagID); 1353 break; 1354 case tok::kw_wchar_t: 1355 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec, 1356 DiagID); 1357 break; 1358 case tok::kw_char16_t: 1359 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char16, Loc, PrevSpec, 1360 DiagID); 1361 break; 1362 case tok::kw_char32_t: 1363 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char32, Loc, PrevSpec, 1364 DiagID); 1365 break; 1366 case tok::kw_bool: 1367 case tok::kw__Bool: 1368 if (Tok.is(tok::kw_bool) && 1369 DS.getTypeSpecType() != DeclSpec::TST_unspecified && 1370 DS.getStorageClassSpec() == DeclSpec::SCS_typedef) { 1371 PrevSpec = ""; // Not used by the diagnostic. 1372 DiagID = diag::err_bool_redeclaration; 1373 isInvalid = true; 1374 } else { 1375 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec, 1376 DiagID); 1377 } 1378 break; 1379 case tok::kw__Decimal32: 1380 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal32, Loc, PrevSpec, 1381 DiagID); 1382 break; 1383 case tok::kw__Decimal64: 1384 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal64, Loc, PrevSpec, 1385 DiagID); 1386 break; 1387 case tok::kw__Decimal128: 1388 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal128, Loc, PrevSpec, 1389 DiagID); 1390 break; 1391 case tok::kw___vector: 1392 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID); 1393 break; 1394 case tok::kw___pixel: 1395 isInvalid = DS.SetTypeAltiVecPixel(true, Loc, PrevSpec, DiagID); 1396 break; 1397 1398 // class-specifier: 1399 case tok::kw_class: 1400 case tok::kw_struct: 1401 case tok::kw_union: { 1402 tok::TokenKind Kind = Tok.getKind(); 1403 ConsumeToken(); 1404 ParseClassSpecifier(Kind, Loc, DS, TemplateInfo, AS); 1405 continue; 1406 } 1407 1408 // enum-specifier: 1409 case tok::kw_enum: 1410 ConsumeToken(); 1411 ParseEnumSpecifier(Loc, DS, TemplateInfo, AS); 1412 continue; 1413 1414 // cv-qualifier: 1415 case tok::kw_const: 1416 isInvalid = DS.SetTypeQual(DeclSpec::TQ_const, Loc, PrevSpec, DiagID, 1417 getLang()); 1418 break; 1419 case tok::kw_volatile: 1420 isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, DiagID, 1421 getLang()); 1422 break; 1423 case tok::kw_restrict: 1424 isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, DiagID, 1425 getLang()); 1426 break; 1427 1428 // C++ typename-specifier: 1429 case tok::kw_typename: 1430 if (TryAnnotateTypeOrScopeToken()) { 1431 DS.SetTypeSpecError(); 1432 goto DoneWithDeclSpec; 1433 } 1434 if (!Tok.is(tok::kw_typename)) 1435 continue; 1436 break; 1437 1438 // GNU typeof support. 1439 case tok::kw_typeof: 1440 ParseTypeofSpecifier(DS); 1441 continue; 1442 1443 case tok::kw_decltype: 1444 ParseDecltypeSpecifier(DS); 1445 continue; 1446 1447 case tok::less: 1448 // GCC ObjC supports types like "<SomeProtocol>" as a synonym for 1449 // "id<SomeProtocol>". This is hopelessly old fashioned and dangerous, 1450 // but we support it. 1451 if (DS.hasTypeSpecifier() || !getLang().ObjC1) 1452 goto DoneWithDeclSpec; 1453 1454 if (!ParseObjCProtocolQualifiers(DS)) 1455 Diag(Loc, diag::warn_objc_protocol_qualifier_missing_id) 1456 << FixItHint::CreateInsertion(Loc, "id") 1457 << SourceRange(Loc, DS.getSourceRange().getEnd()); 1458 1459 // Need to support trailing type qualifiers (e.g. "id<p> const"). 1460 // If a type specifier follows, it will be diagnosed elsewhere. 1461 continue; 1462 } 1463 // If the specifier wasn't legal, issue a diagnostic. 1464 if (isInvalid) { 1465 assert(PrevSpec && "Method did not return previous specifier!"); 1466 assert(DiagID); 1467 1468 if (DiagID == diag::ext_duplicate_declspec) 1469 Diag(Tok, DiagID) 1470 << PrevSpec << FixItHint::CreateRemoval(Tok.getLocation()); 1471 else 1472 Diag(Tok, DiagID) << PrevSpec; 1473 } 1474 1475 DS.SetRangeEnd(Tok.getLocation()); 1476 ConsumeToken(); 1477 } 1478} 1479 1480/// ParseOptionalTypeSpecifier - Try to parse a single type-specifier. We 1481/// primarily follow the C++ grammar with additions for C99 and GNU, 1482/// which together subsume the C grammar. Note that the C++ 1483/// type-specifier also includes the C type-qualifier (for const, 1484/// volatile, and C99 restrict). Returns true if a type-specifier was 1485/// found (and parsed), false otherwise. 1486/// 1487/// type-specifier: [C++ 7.1.5] 1488/// simple-type-specifier 1489/// class-specifier 1490/// enum-specifier 1491/// elaborated-type-specifier [TODO] 1492/// cv-qualifier 1493/// 1494/// cv-qualifier: [C++ 7.1.5.1] 1495/// 'const' 1496/// 'volatile' 1497/// [C99] 'restrict' 1498/// 1499/// simple-type-specifier: [ C++ 7.1.5.2] 1500/// '::'[opt] nested-name-specifier[opt] type-name [TODO] 1501/// '::'[opt] nested-name-specifier 'template' template-id [TODO] 1502/// 'char' 1503/// 'wchar_t' 1504/// 'bool' 1505/// 'short' 1506/// 'int' 1507/// 'long' 1508/// 'signed' 1509/// 'unsigned' 1510/// 'float' 1511/// 'double' 1512/// 'void' 1513/// [C99] '_Bool' 1514/// [C99] '_Complex' 1515/// [C99] '_Imaginary' // Removed in TC2? 1516/// [GNU] '_Decimal32' 1517/// [GNU] '_Decimal64' 1518/// [GNU] '_Decimal128' 1519/// [GNU] typeof-specifier 1520/// [OBJC] class-name objc-protocol-refs[opt] [TODO] 1521/// [OBJC] typedef-name objc-protocol-refs[opt] [TODO] 1522/// [C++0x] 'decltype' ( expression ) 1523/// [AltiVec] '__vector' 1524bool Parser::ParseOptionalTypeSpecifier(DeclSpec &DS, bool& isInvalid, 1525 const char *&PrevSpec, 1526 unsigned &DiagID, 1527 const ParsedTemplateInfo &TemplateInfo, 1528 bool SuppressDeclarations) { 1529 SourceLocation Loc = Tok.getLocation(); 1530 1531 switch (Tok.getKind()) { 1532 case tok::identifier: // foo::bar 1533 // If we already have a type specifier, this identifier is not a type. 1534 if (DS.getTypeSpecType() != DeclSpec::TST_unspecified || 1535 DS.getTypeSpecWidth() != DeclSpec::TSW_unspecified || 1536 DS.getTypeSpecSign() != DeclSpec::TSS_unspecified) 1537 return false; 1538 // Check for need to substitute AltiVec keyword tokens. 1539 if (TryAltiVecToken(DS, Loc, PrevSpec, DiagID, isInvalid)) 1540 break; 1541 // Fall through. 1542 case tok::kw_typename: // typename foo::bar 1543 // Annotate typenames and C++ scope specifiers. If we get one, just 1544 // recurse to handle whatever we get. 1545 if (TryAnnotateTypeOrScopeToken()) 1546 return true; 1547 if (Tok.is(tok::identifier)) 1548 return false; 1549 return ParseOptionalTypeSpecifier(DS, isInvalid, PrevSpec, DiagID, 1550 TemplateInfo, SuppressDeclarations); 1551 case tok::coloncolon: // ::foo::bar 1552 if (NextToken().is(tok::kw_new) || // ::new 1553 NextToken().is(tok::kw_delete)) // ::delete 1554 return false; 1555 1556 // Annotate typenames and C++ scope specifiers. If we get one, just 1557 // recurse to handle whatever we get. 1558 if (TryAnnotateTypeOrScopeToken()) 1559 return true; 1560 return ParseOptionalTypeSpecifier(DS, isInvalid, PrevSpec, DiagID, 1561 TemplateInfo, SuppressDeclarations); 1562 1563 // simple-type-specifier: 1564 case tok::annot_typename: { 1565 if (ParsedType T = getTypeAnnotation(Tok)) { 1566 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, 1567 Tok.getAnnotationEndLoc(), PrevSpec, 1568 DiagID, T); 1569 } else 1570 DS.SetTypeSpecError(); 1571 DS.SetRangeEnd(Tok.getAnnotationEndLoc()); 1572 ConsumeToken(); // The typename 1573 1574 // Objective-C supports syntax of the form 'id<proto1,proto2>' where 'id' 1575 // is a specific typedef and 'itf<proto1,proto2>' where 'itf' is an 1576 // Objective-C interface. If we don't have Objective-C or a '<', this is 1577 // just a normal reference to a typedef name. 1578 if (Tok.is(tok::less) && getLang().ObjC1) 1579 ParseObjCProtocolQualifiers(DS); 1580 1581 return true; 1582 } 1583 1584 case tok::kw_short: 1585 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_short, Loc, PrevSpec, DiagID); 1586 break; 1587 case tok::kw_long: 1588 if (DS.getTypeSpecWidth() != DeclSpec::TSW_long) 1589 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_long, Loc, PrevSpec, 1590 DiagID); 1591 else 1592 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec, 1593 DiagID); 1594 break; 1595 case tok::kw_signed: 1596 isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_signed, Loc, PrevSpec, DiagID); 1597 break; 1598 case tok::kw_unsigned: 1599 isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_unsigned, Loc, PrevSpec, 1600 DiagID); 1601 break; 1602 case tok::kw__Complex: 1603 isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_complex, Loc, PrevSpec, 1604 DiagID); 1605 break; 1606 case tok::kw__Imaginary: 1607 isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_imaginary, Loc, PrevSpec, 1608 DiagID); 1609 break; 1610 case tok::kw_void: 1611 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec, DiagID); 1612 break; 1613 case tok::kw_char: 1614 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec, DiagID); 1615 break; 1616 case tok::kw_int: 1617 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec, DiagID); 1618 break; 1619 case tok::kw_float: 1620 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec, DiagID); 1621 break; 1622 case tok::kw_double: 1623 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec, DiagID); 1624 break; 1625 case tok::kw_wchar_t: 1626 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec, DiagID); 1627 break; 1628 case tok::kw_char16_t: 1629 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char16, Loc, PrevSpec, DiagID); 1630 break; 1631 case tok::kw_char32_t: 1632 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char32, Loc, PrevSpec, DiagID); 1633 break; 1634 case tok::kw_bool: 1635 case tok::kw__Bool: 1636 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec, DiagID); 1637 break; 1638 case tok::kw__Decimal32: 1639 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal32, Loc, PrevSpec, 1640 DiagID); 1641 break; 1642 case tok::kw__Decimal64: 1643 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal64, Loc, PrevSpec, 1644 DiagID); 1645 break; 1646 case tok::kw__Decimal128: 1647 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal128, Loc, PrevSpec, 1648 DiagID); 1649 break; 1650 case tok::kw___vector: 1651 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID); 1652 break; 1653 case tok::kw___pixel: 1654 isInvalid = DS.SetTypeAltiVecPixel(true, Loc, PrevSpec, DiagID); 1655 break; 1656 1657 // class-specifier: 1658 case tok::kw_class: 1659 case tok::kw_struct: 1660 case tok::kw_union: { 1661 tok::TokenKind Kind = Tok.getKind(); 1662 ConsumeToken(); 1663 ParseClassSpecifier(Kind, Loc, DS, TemplateInfo, AS_none, 1664 SuppressDeclarations); 1665 return true; 1666 } 1667 1668 // enum-specifier: 1669 case tok::kw_enum: 1670 ConsumeToken(); 1671 ParseEnumSpecifier(Loc, DS, TemplateInfo, AS_none); 1672 return true; 1673 1674 // cv-qualifier: 1675 case tok::kw_const: 1676 isInvalid = DS.SetTypeQual(DeclSpec::TQ_const , Loc, PrevSpec, 1677 DiagID, getLang()); 1678 break; 1679 case tok::kw_volatile: 1680 isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, 1681 DiagID, getLang()); 1682 break; 1683 case tok::kw_restrict: 1684 isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, 1685 DiagID, getLang()); 1686 break; 1687 1688 // GNU typeof support. 1689 case tok::kw_typeof: 1690 ParseTypeofSpecifier(DS); 1691 return true; 1692 1693 // C++0x decltype support. 1694 case tok::kw_decltype: 1695 ParseDecltypeSpecifier(DS); 1696 return true; 1697 1698 // C++0x auto support. 1699 case tok::kw_auto: 1700 if (!getLang().CPlusPlus0x) 1701 return false; 1702 1703 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_auto, Loc, PrevSpec, DiagID); 1704 break; 1705 1706 case tok::kw___ptr64: 1707 case tok::kw___w64: 1708 case tok::kw___cdecl: 1709 case tok::kw___stdcall: 1710 case tok::kw___fastcall: 1711 case tok::kw___thiscall: 1712 ParseMicrosoftTypeAttributes(DS.getAttributes()); 1713 return true; 1714 1715 case tok::kw___pascal: 1716 ParseBorlandTypeAttributes(DS.getAttributes()); 1717 return true; 1718 1719 default: 1720 // Not a type-specifier; do nothing. 1721 return false; 1722 } 1723 1724 // If the specifier combination wasn't legal, issue a diagnostic. 1725 if (isInvalid) { 1726 assert(PrevSpec && "Method did not return previous specifier!"); 1727 // Pick between error or extwarn. 1728 Diag(Tok, DiagID) << PrevSpec; 1729 } 1730 DS.SetRangeEnd(Tok.getLocation()); 1731 ConsumeToken(); // whatever we parsed above. 1732 return true; 1733} 1734 1735/// ParseStructDeclaration - Parse a struct declaration without the terminating 1736/// semicolon. 1737/// 1738/// struct-declaration: 1739/// specifier-qualifier-list struct-declarator-list 1740/// [GNU] __extension__ struct-declaration 1741/// [GNU] specifier-qualifier-list 1742/// struct-declarator-list: 1743/// struct-declarator 1744/// struct-declarator-list ',' struct-declarator 1745/// [GNU] struct-declarator-list ',' attributes[opt] struct-declarator 1746/// struct-declarator: 1747/// declarator 1748/// [GNU] declarator attributes[opt] 1749/// declarator[opt] ':' constant-expression 1750/// [GNU] declarator[opt] ':' constant-expression attributes[opt] 1751/// 1752void Parser:: 1753ParseStructDeclaration(DeclSpec &DS, FieldCallback &Fields) { 1754 if (Tok.is(tok::kw___extension__)) { 1755 // __extension__ silences extension warnings in the subexpression. 1756 ExtensionRAIIObject O(Diags); // Use RAII to do this. 1757 ConsumeToken(); 1758 return ParseStructDeclaration(DS, Fields); 1759 } 1760 1761 // Parse the common specifier-qualifiers-list piece. 1762 ParseSpecifierQualifierList(DS); 1763 1764 // If there are no declarators, this is a free-standing declaration 1765 // specifier. Let the actions module cope with it. 1766 if (Tok.is(tok::semi)) { 1767 Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS_none, DS); 1768 return; 1769 } 1770 1771 // Read struct-declarators until we find the semicolon. 1772 bool FirstDeclarator = true; 1773 while (1) { 1774 ParsingDeclRAIIObject PD(*this); 1775 FieldDeclarator DeclaratorInfo(DS); 1776 1777 // Attributes are only allowed here on successive declarators. 1778 if (!FirstDeclarator) 1779 MaybeParseGNUAttributes(DeclaratorInfo.D); 1780 1781 /// struct-declarator: declarator 1782 /// struct-declarator: declarator[opt] ':' constant-expression 1783 if (Tok.isNot(tok::colon)) { 1784 // Don't parse FOO:BAR as if it were a typo for FOO::BAR. 1785 ColonProtectionRAIIObject X(*this); 1786 ParseDeclarator(DeclaratorInfo.D); 1787 } 1788 1789 if (Tok.is(tok::colon)) { 1790 ConsumeToken(); 1791 ExprResult Res(ParseConstantExpression()); 1792 if (Res.isInvalid()) 1793 SkipUntil(tok::semi, true, true); 1794 else 1795 DeclaratorInfo.BitfieldSize = Res.release(); 1796 } 1797 1798 // If attributes exist after the declarator, parse them. 1799 MaybeParseGNUAttributes(DeclaratorInfo.D); 1800 1801 // We're done with this declarator; invoke the callback. 1802 Decl *D = Fields.invoke(DeclaratorInfo); 1803 PD.complete(D); 1804 1805 // If we don't have a comma, it is either the end of the list (a ';') 1806 // or an error, bail out. 1807 if (Tok.isNot(tok::comma)) 1808 return; 1809 1810 // Consume the comma. 1811 ConsumeToken(); 1812 1813 FirstDeclarator = false; 1814 } 1815} 1816 1817/// ParseStructUnionBody 1818/// struct-contents: 1819/// struct-declaration-list 1820/// [EXT] empty 1821/// [GNU] "struct-declaration-list" without terminatoring ';' 1822/// struct-declaration-list: 1823/// struct-declaration 1824/// struct-declaration-list struct-declaration 1825/// [OBC] '@' 'defs' '(' class-name ')' 1826/// 1827void Parser::ParseStructUnionBody(SourceLocation RecordLoc, 1828 unsigned TagType, Decl *TagDecl) { 1829 PrettyDeclStackTraceEntry CrashInfo(Actions, TagDecl, RecordLoc, 1830 "parsing struct/union body"); 1831 1832 SourceLocation LBraceLoc = ConsumeBrace(); 1833 1834 ParseScope StructScope(this, Scope::ClassScope|Scope::DeclScope); 1835 Actions.ActOnTagStartDefinition(getCurScope(), TagDecl); 1836 1837 // Empty structs are an extension in C (C99 6.7.2.1p7), but are allowed in 1838 // C++. 1839 if (Tok.is(tok::r_brace) && !getLang().CPlusPlus) 1840 Diag(Tok, diag::ext_empty_struct_union) 1841 << (TagType == TST_union); 1842 1843 llvm::SmallVector<Decl *, 32> FieldDecls; 1844 1845 // While we still have something to read, read the declarations in the struct. 1846 while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) { 1847 // Each iteration of this loop reads one struct-declaration. 1848 1849 // Check for extraneous top-level semicolon. 1850 if (Tok.is(tok::semi)) { 1851 Diag(Tok, diag::ext_extra_struct_semi) 1852 << DeclSpec::getSpecifierName((DeclSpec::TST)TagType) 1853 << FixItHint::CreateRemoval(Tok.getLocation()); 1854 ConsumeToken(); 1855 continue; 1856 } 1857 1858 // Parse all the comma separated declarators. 1859 DeclSpec DS; 1860 1861 if (!Tok.is(tok::at)) { 1862 struct CFieldCallback : FieldCallback { 1863 Parser &P; 1864 Decl *TagDecl; 1865 llvm::SmallVectorImpl<Decl *> &FieldDecls; 1866 1867 CFieldCallback(Parser &P, Decl *TagDecl, 1868 llvm::SmallVectorImpl<Decl *> &FieldDecls) : 1869 P(P), TagDecl(TagDecl), FieldDecls(FieldDecls) {} 1870 1871 virtual Decl *invoke(FieldDeclarator &FD) { 1872 // Install the declarator into the current TagDecl. 1873 Decl *Field = P.Actions.ActOnField(P.getCurScope(), TagDecl, 1874 FD.D.getDeclSpec().getSourceRange().getBegin(), 1875 FD.D, FD.BitfieldSize); 1876 FieldDecls.push_back(Field); 1877 return Field; 1878 } 1879 } Callback(*this, TagDecl, FieldDecls); 1880 1881 ParseStructDeclaration(DS, Callback); 1882 } else { // Handle @defs 1883 ConsumeToken(); 1884 if (!Tok.isObjCAtKeyword(tok::objc_defs)) { 1885 Diag(Tok, diag::err_unexpected_at); 1886 SkipUntil(tok::semi, true); 1887 continue; 1888 } 1889 ConsumeToken(); 1890 ExpectAndConsume(tok::l_paren, diag::err_expected_lparen); 1891 if (!Tok.is(tok::identifier)) { 1892 Diag(Tok, diag::err_expected_ident); 1893 SkipUntil(tok::semi, true); 1894 continue; 1895 } 1896 llvm::SmallVector<Decl *, 16> Fields; 1897 Actions.ActOnDefs(getCurScope(), TagDecl, Tok.getLocation(), 1898 Tok.getIdentifierInfo(), Fields); 1899 FieldDecls.insert(FieldDecls.end(), Fields.begin(), Fields.end()); 1900 ConsumeToken(); 1901 ExpectAndConsume(tok::r_paren, diag::err_expected_rparen); 1902 } 1903 1904 if (Tok.is(tok::semi)) { 1905 ConsumeToken(); 1906 } else if (Tok.is(tok::r_brace)) { 1907 ExpectAndConsume(tok::semi, diag::ext_expected_semi_decl_list); 1908 break; 1909 } else { 1910 ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list); 1911 // Skip to end of block or statement to avoid ext-warning on extra ';'. 1912 SkipUntil(tok::r_brace, true, true); 1913 // If we stopped at a ';', eat it. 1914 if (Tok.is(tok::semi)) ConsumeToken(); 1915 } 1916 } 1917 1918 SourceLocation RBraceLoc = MatchRHSPunctuation(tok::r_brace, LBraceLoc); 1919 1920 ParsedAttributes attrs; 1921 // If attributes exist after struct contents, parse them. 1922 MaybeParseGNUAttributes(attrs); 1923 1924 Actions.ActOnFields(getCurScope(), 1925 RecordLoc, TagDecl, FieldDecls.data(), FieldDecls.size(), 1926 LBraceLoc, RBraceLoc, 1927 attrs.getList()); 1928 StructScope.Exit(); 1929 Actions.ActOnTagFinishDefinition(getCurScope(), TagDecl, RBraceLoc); 1930} 1931 1932/// ParseEnumSpecifier 1933/// enum-specifier: [C99 6.7.2.2] 1934/// 'enum' identifier[opt] '{' enumerator-list '}' 1935///[C99/C++]'enum' identifier[opt] '{' enumerator-list ',' '}' 1936/// [GNU] 'enum' attributes[opt] identifier[opt] '{' enumerator-list ',' [opt] 1937/// '}' attributes[opt] 1938/// 'enum' identifier 1939/// [GNU] 'enum' attributes[opt] identifier 1940/// 1941/// [C++0x] enum-head '{' enumerator-list[opt] '}' 1942/// [C++0x] enum-head '{' enumerator-list ',' '}' 1943/// 1944/// enum-head: [C++0x] 1945/// enum-key attributes[opt] identifier[opt] enum-base[opt] 1946/// enum-key attributes[opt] nested-name-specifier identifier enum-base[opt] 1947/// 1948/// enum-key: [C++0x] 1949/// 'enum' 1950/// 'enum' 'class' 1951/// 'enum' 'struct' 1952/// 1953/// enum-base: [C++0x] 1954/// ':' type-specifier-seq 1955/// 1956/// [C++] elaborated-type-specifier: 1957/// [C++] 'enum' '::'[opt] nested-name-specifier[opt] identifier 1958/// 1959void Parser::ParseEnumSpecifier(SourceLocation StartLoc, DeclSpec &DS, 1960 const ParsedTemplateInfo &TemplateInfo, 1961 AccessSpecifier AS) { 1962 // Parse the tag portion of this. 1963 if (Tok.is(tok::code_completion)) { 1964 // Code completion for an enum name. 1965 Actions.CodeCompleteTag(getCurScope(), DeclSpec::TST_enum); 1966 ConsumeCodeCompletionToken(); 1967 } 1968 1969 // If attributes exist after tag, parse them. 1970 ParsedAttributes attrs; 1971 MaybeParseGNUAttributes(attrs); 1972 1973 CXXScopeSpec &SS = DS.getTypeSpecScope(); 1974 if (getLang().CPlusPlus) { 1975 if (ParseOptionalCXXScopeSpecifier(SS, ParsedType(), false)) 1976 return; 1977 1978 if (SS.isSet() && Tok.isNot(tok::identifier)) { 1979 Diag(Tok, diag::err_expected_ident); 1980 if (Tok.isNot(tok::l_brace)) { 1981 // Has no name and is not a definition. 1982 // Skip the rest of this declarator, up until the comma or semicolon. 1983 SkipUntil(tok::comma, true); 1984 return; 1985 } 1986 } 1987 } 1988 1989 bool AllowFixedUnderlyingType = getLang().CPlusPlus0x || getLang().Microsoft; 1990 bool IsScopedEnum = false; 1991 bool IsScopedUsingClassTag = false; 1992 1993 if (getLang().CPlusPlus0x && 1994 (Tok.is(tok::kw_class) || Tok.is(tok::kw_struct))) { 1995 IsScopedEnum = true; 1996 IsScopedUsingClassTag = Tok.is(tok::kw_class); 1997 ConsumeToken(); 1998 } 1999 2000 // Must have either 'enum name' or 'enum {...}'. 2001 if (Tok.isNot(tok::identifier) && Tok.isNot(tok::l_brace) && 2002 (AllowFixedUnderlyingType && Tok.isNot(tok::colon))) { 2003 Diag(Tok, diag::err_expected_ident_lbrace); 2004 2005 // Skip the rest of this declarator, up until the comma or semicolon. 2006 SkipUntil(tok::comma, true); 2007 return; 2008 } 2009 2010 // If an identifier is present, consume and remember it. 2011 IdentifierInfo *Name = 0; 2012 SourceLocation NameLoc; 2013 if (Tok.is(tok::identifier)) { 2014 Name = Tok.getIdentifierInfo(); 2015 NameLoc = ConsumeToken(); 2016 } 2017 2018 if (!Name && IsScopedEnum) { 2019 // C++0x 7.2p2: The optional identifier shall not be omitted in the 2020 // declaration of a scoped enumeration. 2021 Diag(Tok, diag::err_scoped_enum_missing_identifier); 2022 IsScopedEnum = false; 2023 IsScopedUsingClassTag = false; 2024 } 2025 2026 TypeResult BaseType; 2027 2028 // Parse the fixed underlying type. 2029 if (AllowFixedUnderlyingType && Tok.is(tok::colon)) { 2030 bool PossibleBitfield = false; 2031 if (getCurScope()->getFlags() & Scope::ClassScope) { 2032 // If we're in class scope, this can either be an enum declaration with 2033 // an underlying type, or a declaration of a bitfield member. We try to 2034 // use a simple disambiguation scheme first to catch the common cases 2035 // (integer literal, sizeof); if it's still ambiguous, we then consider 2036 // anything that's a simple-type-specifier followed by '(' as an 2037 // expression. This suffices because function types are not valid 2038 // underlying types anyway. 2039 TPResult TPR = isExpressionOrTypeSpecifierSimple(NextToken().getKind()); 2040 // If the next token starts an expression, we know we're parsing a 2041 // bit-field. This is the common case. 2042 if (TPR == TPResult::True()) 2043 PossibleBitfield = true; 2044 // If the next token starts a type-specifier-seq, it may be either a 2045 // a fixed underlying type or the start of a function-style cast in C++; 2046 // lookahead one more token to see if it's obvious that we have a 2047 // fixed underlying type. 2048 else if (TPR == TPResult::False() && 2049 GetLookAheadToken(2).getKind() == tok::semi) { 2050 // Consume the ':'. 2051 ConsumeToken(); 2052 } else { 2053 // We have the start of a type-specifier-seq, so we have to perform 2054 // tentative parsing to determine whether we have an expression or a 2055 // type. 2056 TentativeParsingAction TPA(*this); 2057 2058 // Consume the ':'. 2059 ConsumeToken(); 2060 2061 if ((getLang().CPlusPlus && 2062 isCXXDeclarationSpecifier() != TPResult::True()) || 2063 (!getLang().CPlusPlus && !isDeclarationSpecifier(true))) { 2064 // We'll parse this as a bitfield later. 2065 PossibleBitfield = true; 2066 TPA.Revert(); 2067 } else { 2068 // We have a type-specifier-seq. 2069 TPA.Commit(); 2070 } 2071 } 2072 } else { 2073 // Consume the ':'. 2074 ConsumeToken(); 2075 } 2076 2077 if (!PossibleBitfield) { 2078 SourceRange Range; 2079 BaseType = ParseTypeName(&Range); 2080 2081 if (!getLang().CPlusPlus0x) 2082 Diag(StartLoc, diag::ext_ms_enum_fixed_underlying_type) 2083 << Range; 2084 } 2085 } 2086 2087 // There are three options here. If we have 'enum foo;', then this is a 2088 // forward declaration. If we have 'enum foo {...' then this is a 2089 // definition. Otherwise we have something like 'enum foo xyz', a reference. 2090 // 2091 // This is needed to handle stuff like this right (C99 6.7.2.3p11): 2092 // enum foo {..}; void bar() { enum foo; } <- new foo in bar. 2093 // enum foo {..}; void bar() { enum foo x; } <- use of old foo. 2094 // 2095 Sema::TagUseKind TUK; 2096 if (Tok.is(tok::l_brace)) 2097 TUK = Sema::TUK_Definition; 2098 else if (Tok.is(tok::semi)) 2099 TUK = Sema::TUK_Declaration; 2100 else 2101 TUK = Sema::TUK_Reference; 2102 2103 // enums cannot be templates, although they can be referenced from a 2104 // template. 2105 if (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate && 2106 TUK != Sema::TUK_Reference) { 2107 Diag(Tok, diag::err_enum_template); 2108 2109 // Skip the rest of this declarator, up until the comma or semicolon. 2110 SkipUntil(tok::comma, true); 2111 return; 2112 } 2113 2114 if (!Name && TUK != Sema::TUK_Definition) { 2115 Diag(Tok, diag::err_enumerator_unnamed_no_def); 2116 2117 // Skip the rest of this declarator, up until the comma or semicolon. 2118 SkipUntil(tok::comma, true); 2119 return; 2120 } 2121 2122 bool Owned = false; 2123 bool IsDependent = false; 2124 SourceLocation TSTLoc = NameLoc.isValid()? NameLoc : StartLoc; 2125 const char *PrevSpec = 0; 2126 unsigned DiagID; 2127 Decl *TagDecl = Actions.ActOnTag(getCurScope(), DeclSpec::TST_enum, TUK, 2128 StartLoc, SS, Name, NameLoc, attrs.getList(), 2129 AS, 2130 MultiTemplateParamsArg(Actions), 2131 Owned, IsDependent, IsScopedEnum, 2132 IsScopedUsingClassTag, BaseType); 2133 2134 if (IsDependent) { 2135 // This enum has a dependent nested-name-specifier. Handle it as a 2136 // dependent tag. 2137 if (!Name) { 2138 DS.SetTypeSpecError(); 2139 Diag(Tok, diag::err_expected_type_name_after_typename); 2140 return; 2141 } 2142 2143 TypeResult Type = Actions.ActOnDependentTag(getCurScope(), DeclSpec::TST_enum, 2144 TUK, SS, Name, StartLoc, 2145 NameLoc); 2146 if (Type.isInvalid()) { 2147 DS.SetTypeSpecError(); 2148 return; 2149 } 2150 2151 if (DS.SetTypeSpecType(DeclSpec::TST_typename, TSTLoc, PrevSpec, DiagID, 2152 Type.get())) 2153 Diag(StartLoc, DiagID) << PrevSpec; 2154 2155 return; 2156 } 2157 2158 if (!TagDecl) { 2159 // The action failed to produce an enumeration tag. If this is a 2160 // definition, consume the entire definition. 2161 if (Tok.is(tok::l_brace)) { 2162 ConsumeBrace(); 2163 SkipUntil(tok::r_brace); 2164 } 2165 2166 DS.SetTypeSpecError(); 2167 return; 2168 } 2169 2170 if (Tok.is(tok::l_brace)) 2171 ParseEnumBody(StartLoc, TagDecl); 2172 2173 // FIXME: The DeclSpec should keep the locations of both the keyword 2174 // and the name (if there is one). 2175 if (DS.SetTypeSpecType(DeclSpec::TST_enum, TSTLoc, PrevSpec, DiagID, 2176 TagDecl, Owned)) 2177 Diag(StartLoc, DiagID) << PrevSpec; 2178} 2179 2180/// ParseEnumBody - Parse a {} enclosed enumerator-list. 2181/// enumerator-list: 2182/// enumerator 2183/// enumerator-list ',' enumerator 2184/// enumerator: 2185/// enumeration-constant 2186/// enumeration-constant '=' constant-expression 2187/// enumeration-constant: 2188/// identifier 2189/// 2190void Parser::ParseEnumBody(SourceLocation StartLoc, Decl *EnumDecl) { 2191 // Enter the scope of the enum body and start the definition. 2192 ParseScope EnumScope(this, Scope::DeclScope); 2193 Actions.ActOnTagStartDefinition(getCurScope(), EnumDecl); 2194 2195 SourceLocation LBraceLoc = ConsumeBrace(); 2196 2197 // C does not allow an empty enumerator-list, C++ does [dcl.enum]. 2198 if (Tok.is(tok::r_brace) && !getLang().CPlusPlus) 2199 Diag(Tok, diag::error_empty_enum); 2200 2201 llvm::SmallVector<Decl *, 32> EnumConstantDecls; 2202 2203 Decl *LastEnumConstDecl = 0; 2204 2205 // Parse the enumerator-list. 2206 while (Tok.is(tok::identifier)) { 2207 IdentifierInfo *Ident = Tok.getIdentifierInfo(); 2208 SourceLocation IdentLoc = ConsumeToken(); 2209 2210 // If attributes exist after the enumerator, parse them. 2211 ParsedAttributes attrs; 2212 MaybeParseGNUAttributes(attrs); 2213 2214 SourceLocation EqualLoc; 2215 ExprResult AssignedVal; 2216 if (Tok.is(tok::equal)) { 2217 EqualLoc = ConsumeToken(); 2218 AssignedVal = ParseConstantExpression(); 2219 if (AssignedVal.isInvalid()) 2220 SkipUntil(tok::comma, tok::r_brace, true, true); 2221 } 2222 2223 // Install the enumerator constant into EnumDecl. 2224 Decl *EnumConstDecl = Actions.ActOnEnumConstant(getCurScope(), EnumDecl, 2225 LastEnumConstDecl, 2226 IdentLoc, Ident, 2227 attrs.getList(), EqualLoc, 2228 AssignedVal.release()); 2229 EnumConstantDecls.push_back(EnumConstDecl); 2230 LastEnumConstDecl = EnumConstDecl; 2231 2232 if (Tok.is(tok::identifier)) { 2233 // We're missing a comma between enumerators. 2234 SourceLocation Loc = PP.getLocForEndOfToken(PrevTokLocation); 2235 Diag(Loc, diag::err_enumerator_list_missing_comma) 2236 << FixItHint::CreateInsertion(Loc, ", "); 2237 continue; 2238 } 2239 2240 if (Tok.isNot(tok::comma)) 2241 break; 2242 SourceLocation CommaLoc = ConsumeToken(); 2243 2244 if (Tok.isNot(tok::identifier) && 2245 !(getLang().C99 || getLang().CPlusPlus0x)) 2246 Diag(CommaLoc, diag::ext_enumerator_list_comma) 2247 << getLang().CPlusPlus 2248 << FixItHint::CreateRemoval(CommaLoc); 2249 } 2250 2251 // Eat the }. 2252 SourceLocation RBraceLoc = MatchRHSPunctuation(tok::r_brace, LBraceLoc); 2253 2254 // If attributes exist after the identifier list, parse them. 2255 ParsedAttributes attrs; 2256 MaybeParseGNUAttributes(attrs); 2257 2258 Actions.ActOnEnumBody(StartLoc, LBraceLoc, RBraceLoc, EnumDecl, 2259 EnumConstantDecls.data(), EnumConstantDecls.size(), 2260 getCurScope(), attrs.getList()); 2261 2262 EnumScope.Exit(); 2263 Actions.ActOnTagFinishDefinition(getCurScope(), EnumDecl, RBraceLoc); 2264} 2265 2266/// isTypeSpecifierQualifier - Return true if the current token could be the 2267/// start of a type-qualifier-list. 2268bool Parser::isTypeQualifier() const { 2269 switch (Tok.getKind()) { 2270 default: return false; 2271 // type-qualifier 2272 case tok::kw_const: 2273 case tok::kw_volatile: 2274 case tok::kw_restrict: 2275 return true; 2276 } 2277} 2278 2279/// isKnownToBeTypeSpecifier - Return true if we know that the specified token 2280/// is definitely a type-specifier. Return false if it isn't part of a type 2281/// specifier or if we're not sure. 2282bool Parser::isKnownToBeTypeSpecifier(const Token &Tok) const { 2283 switch (Tok.getKind()) { 2284 default: return false; 2285 // type-specifiers 2286 case tok::kw_short: 2287 case tok::kw_long: 2288 case tok::kw_signed: 2289 case tok::kw_unsigned: 2290 case tok::kw__Complex: 2291 case tok::kw__Imaginary: 2292 case tok::kw_void: 2293 case tok::kw_char: 2294 case tok::kw_wchar_t: 2295 case tok::kw_char16_t: 2296 case tok::kw_char32_t: 2297 case tok::kw_int: 2298 case tok::kw_float: 2299 case tok::kw_double: 2300 case tok::kw_bool: 2301 case tok::kw__Bool: 2302 case tok::kw__Decimal32: 2303 case tok::kw__Decimal64: 2304 case tok::kw__Decimal128: 2305 case tok::kw___vector: 2306 2307 // struct-or-union-specifier (C99) or class-specifier (C++) 2308 case tok::kw_class: 2309 case tok::kw_struct: 2310 case tok::kw_union: 2311 // enum-specifier 2312 case tok::kw_enum: 2313 2314 // typedef-name 2315 case tok::annot_typename: 2316 return true; 2317 } 2318} 2319 2320/// isTypeSpecifierQualifier - Return true if the current token could be the 2321/// start of a specifier-qualifier-list. 2322bool Parser::isTypeSpecifierQualifier() { 2323 switch (Tok.getKind()) { 2324 default: return false; 2325 2326 case tok::identifier: // foo::bar 2327 if (TryAltiVecVectorToken()) 2328 return true; 2329 // Fall through. 2330 case tok::kw_typename: // typename T::type 2331 // Annotate typenames and C++ scope specifiers. If we get one, just 2332 // recurse to handle whatever we get. 2333 if (TryAnnotateTypeOrScopeToken()) 2334 return true; 2335 if (Tok.is(tok::identifier)) 2336 return false; 2337 return isTypeSpecifierQualifier(); 2338 2339 case tok::coloncolon: // ::foo::bar 2340 if (NextToken().is(tok::kw_new) || // ::new 2341 NextToken().is(tok::kw_delete)) // ::delete 2342 return false; 2343 2344 if (TryAnnotateTypeOrScopeToken()) 2345 return true; 2346 return isTypeSpecifierQualifier(); 2347 2348 // GNU attributes support. 2349 case tok::kw___attribute: 2350 // GNU typeof support. 2351 case tok::kw_typeof: 2352 2353 // type-specifiers 2354 case tok::kw_short: 2355 case tok::kw_long: 2356 case tok::kw_signed: 2357 case tok::kw_unsigned: 2358 case tok::kw__Complex: 2359 case tok::kw__Imaginary: 2360 case tok::kw_void: 2361 case tok::kw_char: 2362 case tok::kw_wchar_t: 2363 case tok::kw_char16_t: 2364 case tok::kw_char32_t: 2365 case tok::kw_int: 2366 case tok::kw_float: 2367 case tok::kw_double: 2368 case tok::kw_bool: 2369 case tok::kw__Bool: 2370 case tok::kw__Decimal32: 2371 case tok::kw__Decimal64: 2372 case tok::kw__Decimal128: 2373 case tok::kw___vector: 2374 2375 // struct-or-union-specifier (C99) or class-specifier (C++) 2376 case tok::kw_class: 2377 case tok::kw_struct: 2378 case tok::kw_union: 2379 // enum-specifier 2380 case tok::kw_enum: 2381 2382 // type-qualifier 2383 case tok::kw_const: 2384 case tok::kw_volatile: 2385 case tok::kw_restrict: 2386 2387 // typedef-name 2388 case tok::annot_typename: 2389 return true; 2390 2391 // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'. 2392 case tok::less: 2393 return getLang().ObjC1; 2394 2395 case tok::kw___cdecl: 2396 case tok::kw___stdcall: 2397 case tok::kw___fastcall: 2398 case tok::kw___thiscall: 2399 case tok::kw___w64: 2400 case tok::kw___ptr64: 2401 case tok::kw___pascal: 2402 return true; 2403 } 2404} 2405 2406/// isDeclarationSpecifier() - Return true if the current token is part of a 2407/// declaration specifier. 2408/// 2409/// \param DisambiguatingWithExpression True to indicate that the purpose of 2410/// this check is to disambiguate between an expression and a declaration. 2411bool Parser::isDeclarationSpecifier(bool DisambiguatingWithExpression) { 2412 switch (Tok.getKind()) { 2413 default: return false; 2414 2415 case tok::identifier: // foo::bar 2416 // Unfortunate hack to support "Class.factoryMethod" notation. 2417 if (getLang().ObjC1 && NextToken().is(tok::period)) 2418 return false; 2419 if (TryAltiVecVectorToken()) 2420 return true; 2421 // Fall through. 2422 case tok::kw_typename: // typename T::type 2423 // Annotate typenames and C++ scope specifiers. If we get one, just 2424 // recurse to handle whatever we get. 2425 if (TryAnnotateTypeOrScopeToken()) 2426 return true; 2427 if (Tok.is(tok::identifier)) 2428 return false; 2429 2430 // If we're in Objective-C and we have an Objective-C class type followed 2431 // by an identifier and then either ':' or ']', in a place where an 2432 // expression is permitted, then this is probably a class message send 2433 // missing the initial '['. In this case, we won't consider this to be 2434 // the start of a declaration. 2435 if (DisambiguatingWithExpression && 2436 isStartOfObjCClassMessageMissingOpenBracket()) 2437 return false; 2438 2439 return isDeclarationSpecifier(); 2440 2441 case tok::coloncolon: // ::foo::bar 2442 if (NextToken().is(tok::kw_new) || // ::new 2443 NextToken().is(tok::kw_delete)) // ::delete 2444 return false; 2445 2446 // Annotate typenames and C++ scope specifiers. If we get one, just 2447 // recurse to handle whatever we get. 2448 if (TryAnnotateTypeOrScopeToken()) 2449 return true; 2450 return isDeclarationSpecifier(); 2451 2452 // storage-class-specifier 2453 case tok::kw_typedef: 2454 case tok::kw_extern: 2455 case tok::kw___private_extern__: 2456 case tok::kw_static: 2457 case tok::kw_auto: 2458 case tok::kw_register: 2459 case tok::kw___thread: 2460 2461 // type-specifiers 2462 case tok::kw_short: 2463 case tok::kw_long: 2464 case tok::kw_signed: 2465 case tok::kw_unsigned: 2466 case tok::kw__Complex: 2467 case tok::kw__Imaginary: 2468 case tok::kw_void: 2469 case tok::kw_char: 2470 case tok::kw_wchar_t: 2471 case tok::kw_char16_t: 2472 case tok::kw_char32_t: 2473 2474 case tok::kw_int: 2475 case tok::kw_float: 2476 case tok::kw_double: 2477 case tok::kw_bool: 2478 case tok::kw__Bool: 2479 case tok::kw__Decimal32: 2480 case tok::kw__Decimal64: 2481 case tok::kw__Decimal128: 2482 case tok::kw___vector: 2483 2484 // struct-or-union-specifier (C99) or class-specifier (C++) 2485 case tok::kw_class: 2486 case tok::kw_struct: 2487 case tok::kw_union: 2488 // enum-specifier 2489 case tok::kw_enum: 2490 2491 // type-qualifier 2492 case tok::kw_const: 2493 case tok::kw_volatile: 2494 case tok::kw_restrict: 2495 2496 // function-specifier 2497 case tok::kw_inline: 2498 case tok::kw_virtual: 2499 case tok::kw_explicit: 2500 2501 // typedef-name 2502 case tok::annot_typename: 2503 2504 // GNU typeof support. 2505 case tok::kw_typeof: 2506 2507 // GNU attributes. 2508 case tok::kw___attribute: 2509 return true; 2510 2511 // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'. 2512 case tok::less: 2513 return getLang().ObjC1; 2514 2515 case tok::kw___declspec: 2516 case tok::kw___cdecl: 2517 case tok::kw___stdcall: 2518 case tok::kw___fastcall: 2519 case tok::kw___thiscall: 2520 case tok::kw___w64: 2521 case tok::kw___ptr64: 2522 case tok::kw___forceinline: 2523 case tok::kw___pascal: 2524 return true; 2525 } 2526} 2527 2528bool Parser::isConstructorDeclarator() { 2529 TentativeParsingAction TPA(*this); 2530 2531 // Parse the C++ scope specifier. 2532 CXXScopeSpec SS; 2533 if (ParseOptionalCXXScopeSpecifier(SS, ParsedType(), true)) { 2534 TPA.Revert(); 2535 return false; 2536 } 2537 2538 // Parse the constructor name. 2539 if (Tok.is(tok::identifier) || Tok.is(tok::annot_template_id)) { 2540 // We already know that we have a constructor name; just consume 2541 // the token. 2542 ConsumeToken(); 2543 } else { 2544 TPA.Revert(); 2545 return false; 2546 } 2547 2548 // Current class name must be followed by a left parentheses. 2549 if (Tok.isNot(tok::l_paren)) { 2550 TPA.Revert(); 2551 return false; 2552 } 2553 ConsumeParen(); 2554 2555 // A right parentheses or ellipsis signals that we have a constructor. 2556 if (Tok.is(tok::r_paren) || Tok.is(tok::ellipsis)) { 2557 TPA.Revert(); 2558 return true; 2559 } 2560 2561 // If we need to, enter the specified scope. 2562 DeclaratorScopeObj DeclScopeObj(*this, SS); 2563 if (SS.isSet() && Actions.ShouldEnterDeclaratorScope(getCurScope(), SS)) 2564 DeclScopeObj.EnterDeclaratorScope(); 2565 2566 // Optionally skip Microsoft attributes. 2567 ParsedAttributes Attrs; 2568 MaybeParseMicrosoftAttributes(Attrs); 2569 2570 // Check whether the next token(s) are part of a declaration 2571 // specifier, in which case we have the start of a parameter and, 2572 // therefore, we know that this is a constructor. 2573 bool IsConstructor = isDeclarationSpecifier(); 2574 TPA.Revert(); 2575 return IsConstructor; 2576} 2577 2578/// ParseTypeQualifierListOpt 2579/// type-qualifier-list: [C99 6.7.5] 2580/// type-qualifier 2581/// [vendor] attributes 2582/// [ only if VendorAttributesAllowed=true ] 2583/// type-qualifier-list type-qualifier 2584/// [vendor] type-qualifier-list attributes 2585/// [ only if VendorAttributesAllowed=true ] 2586/// [C++0x] attribute-specifier[opt] is allowed before cv-qualifier-seq 2587/// [ only if CXX0XAttributesAllowed=true ] 2588/// Note: vendor can be GNU, MS, etc. 2589/// 2590void Parser::ParseTypeQualifierListOpt(DeclSpec &DS, 2591 bool VendorAttributesAllowed, 2592 bool CXX0XAttributesAllowed) { 2593 if (getLang().CPlusPlus0x && isCXX0XAttributeSpecifier()) { 2594 SourceLocation Loc = Tok.getLocation(); 2595 ParsedAttributesWithRange attrs; 2596 ParseCXX0XAttributes(attrs); 2597 if (CXX0XAttributesAllowed) 2598 DS.takeAttributesFrom(attrs); 2599 else 2600 Diag(Loc, diag::err_attributes_not_allowed); 2601 } 2602 2603 while (1) { 2604 bool isInvalid = false; 2605 const char *PrevSpec = 0; 2606 unsigned DiagID = 0; 2607 SourceLocation Loc = Tok.getLocation(); 2608 2609 switch (Tok.getKind()) { 2610 case tok::code_completion: 2611 Actions.CodeCompleteTypeQualifiers(DS); 2612 ConsumeCodeCompletionToken(); 2613 break; 2614 2615 case tok::kw_const: 2616 isInvalid = DS.SetTypeQual(DeclSpec::TQ_const , Loc, PrevSpec, DiagID, 2617 getLang()); 2618 break; 2619 case tok::kw_volatile: 2620 isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, DiagID, 2621 getLang()); 2622 break; 2623 case tok::kw_restrict: 2624 isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, DiagID, 2625 getLang()); 2626 break; 2627 case tok::kw___w64: 2628 case tok::kw___ptr64: 2629 case tok::kw___cdecl: 2630 case tok::kw___stdcall: 2631 case tok::kw___fastcall: 2632 case tok::kw___thiscall: 2633 if (VendorAttributesAllowed) { 2634 ParseMicrosoftTypeAttributes(DS.getAttributes()); 2635 continue; 2636 } 2637 goto DoneWithTypeQuals; 2638 case tok::kw___pascal: 2639 if (VendorAttributesAllowed) { 2640 ParseBorlandTypeAttributes(DS.getAttributes()); 2641 continue; 2642 } 2643 goto DoneWithTypeQuals; 2644 case tok::kw___attribute: 2645 if (VendorAttributesAllowed) { 2646 ParseGNUAttributes(DS.getAttributes()); 2647 continue; // do *not* consume the next token! 2648 } 2649 // otherwise, FALL THROUGH! 2650 default: 2651 DoneWithTypeQuals: 2652 // If this is not a type-qualifier token, we're done reading type 2653 // qualifiers. First verify that DeclSpec's are consistent. 2654 DS.Finish(Diags, PP); 2655 return; 2656 } 2657 2658 // If the specifier combination wasn't legal, issue a diagnostic. 2659 if (isInvalid) { 2660 assert(PrevSpec && "Method did not return previous specifier!"); 2661 Diag(Tok, DiagID) << PrevSpec; 2662 } 2663 ConsumeToken(); 2664 } 2665} 2666 2667 2668/// ParseDeclarator - Parse and verify a newly-initialized declarator. 2669/// 2670void Parser::ParseDeclarator(Declarator &D) { 2671 /// This implements the 'declarator' production in the C grammar, then checks 2672 /// for well-formedness and issues diagnostics. 2673 ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator); 2674} 2675 2676/// ParseDeclaratorInternal - Parse a C or C++ declarator. The direct-declarator 2677/// is parsed by the function passed to it. Pass null, and the direct-declarator 2678/// isn't parsed at all, making this function effectively parse the C++ 2679/// ptr-operator production. 2680/// 2681/// declarator: [C99 6.7.5] [C++ 8p4, dcl.decl] 2682/// [C] pointer[opt] direct-declarator 2683/// [C++] direct-declarator 2684/// [C++] ptr-operator declarator 2685/// 2686/// pointer: [C99 6.7.5] 2687/// '*' type-qualifier-list[opt] 2688/// '*' type-qualifier-list[opt] pointer 2689/// 2690/// ptr-operator: 2691/// '*' cv-qualifier-seq[opt] 2692/// '&' 2693/// [C++0x] '&&' 2694/// [GNU] '&' restrict[opt] attributes[opt] 2695/// [GNU?] '&&' restrict[opt] attributes[opt] 2696/// '::'[opt] nested-name-specifier '*' cv-qualifier-seq[opt] 2697void Parser::ParseDeclaratorInternal(Declarator &D, 2698 DirectDeclParseFunction DirectDeclParser) { 2699 if (Diags.hasAllExtensionsSilenced()) 2700 D.setExtension(); 2701 2702 // C++ member pointers start with a '::' or a nested-name. 2703 // Member pointers get special handling, since there's no place for the 2704 // scope spec in the generic path below. 2705 if (getLang().CPlusPlus && 2706 (Tok.is(tok::coloncolon) || Tok.is(tok::identifier) || 2707 Tok.is(tok::annot_cxxscope))) { 2708 CXXScopeSpec SS; 2709 ParseOptionalCXXScopeSpecifier(SS, ParsedType(), true); // ignore fail 2710 2711 if (SS.isNotEmpty()) { 2712 if (Tok.isNot(tok::star)) { 2713 // The scope spec really belongs to the direct-declarator. 2714 D.getCXXScopeSpec() = SS; 2715 if (DirectDeclParser) 2716 (this->*DirectDeclParser)(D); 2717 return; 2718 } 2719 2720 SourceLocation Loc = ConsumeToken(); 2721 D.SetRangeEnd(Loc); 2722 DeclSpec DS; 2723 ParseTypeQualifierListOpt(DS); 2724 D.ExtendWithDeclSpec(DS); 2725 2726 // Recurse to parse whatever is left. 2727 ParseDeclaratorInternal(D, DirectDeclParser); 2728 2729 // Sema will have to catch (syntactically invalid) pointers into global 2730 // scope. It has to catch pointers into namespace scope anyway. 2731 D.AddTypeInfo(DeclaratorChunk::getMemberPointer(SS,DS.getTypeQualifiers(), 2732 Loc, DS.takeAttributes()), 2733 /* Don't replace range end. */SourceLocation()); 2734 return; 2735 } 2736 } 2737 2738 tok::TokenKind Kind = Tok.getKind(); 2739 // Not a pointer, C++ reference, or block. 2740 if (Kind != tok::star && Kind != tok::caret && 2741 (Kind != tok::amp || !getLang().CPlusPlus) && 2742 // We parse rvalue refs in C++03, because otherwise the errors are scary. 2743 (Kind != tok::ampamp || !getLang().CPlusPlus)) { 2744 if (DirectDeclParser) 2745 (this->*DirectDeclParser)(D); 2746 return; 2747 } 2748 2749 // Otherwise, '*' -> pointer, '^' -> block, '&' -> lvalue reference, 2750 // '&&' -> rvalue reference 2751 SourceLocation Loc = ConsumeToken(); // Eat the *, ^, & or &&. 2752 D.SetRangeEnd(Loc); 2753 2754 if (Kind == tok::star || Kind == tok::caret) { 2755 // Is a pointer. 2756 DeclSpec DS; 2757 2758 ParseTypeQualifierListOpt(DS); 2759 D.ExtendWithDeclSpec(DS); 2760 2761 // Recursively parse the declarator. 2762 ParseDeclaratorInternal(D, DirectDeclParser); 2763 if (Kind == tok::star) 2764 // Remember that we parsed a pointer type, and remember the type-quals. 2765 D.AddTypeInfo(DeclaratorChunk::getPointer(DS.getTypeQualifiers(), Loc, 2766 DS.getConstSpecLoc(), 2767 DS.getVolatileSpecLoc(), 2768 DS.getRestrictSpecLoc(), 2769 DS.takeAttributes()), 2770 SourceLocation()); 2771 else 2772 // Remember that we parsed a Block type, and remember the type-quals. 2773 D.AddTypeInfo(DeclaratorChunk::getBlockPointer(DS.getTypeQualifiers(), 2774 Loc, DS.takeAttributes()), 2775 SourceLocation()); 2776 } else { 2777 // Is a reference 2778 DeclSpec DS; 2779 2780 // Complain about rvalue references in C++03, but then go on and build 2781 // the declarator. 2782 if (Kind == tok::ampamp && !getLang().CPlusPlus0x) 2783 Diag(Loc, diag::ext_rvalue_reference); 2784 2785 // C++ 8.3.2p1: cv-qualified references are ill-formed except when the 2786 // cv-qualifiers are introduced through the use of a typedef or of a 2787 // template type argument, in which case the cv-qualifiers are ignored. 2788 // 2789 // [GNU] Retricted references are allowed. 2790 // [GNU] Attributes on references are allowed. 2791 // [C++0x] Attributes on references are not allowed. 2792 ParseTypeQualifierListOpt(DS, true, false); 2793 D.ExtendWithDeclSpec(DS); 2794 2795 if (DS.getTypeQualifiers() != DeclSpec::TQ_unspecified) { 2796 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 2797 Diag(DS.getConstSpecLoc(), 2798 diag::err_invalid_reference_qualifier_application) << "const"; 2799 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 2800 Diag(DS.getVolatileSpecLoc(), 2801 diag::err_invalid_reference_qualifier_application) << "volatile"; 2802 } 2803 2804 // Recursively parse the declarator. 2805 ParseDeclaratorInternal(D, DirectDeclParser); 2806 2807 if (D.getNumTypeObjects() > 0) { 2808 // C++ [dcl.ref]p4: There shall be no references to references. 2809 DeclaratorChunk& InnerChunk = D.getTypeObject(D.getNumTypeObjects() - 1); 2810 if (InnerChunk.Kind == DeclaratorChunk::Reference) { 2811 if (const IdentifierInfo *II = D.getIdentifier()) 2812 Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference) 2813 << II; 2814 else 2815 Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference) 2816 << "type name"; 2817 2818 // Once we've complained about the reference-to-reference, we 2819 // can go ahead and build the (technically ill-formed) 2820 // declarator: reference collapsing will take care of it. 2821 } 2822 } 2823 2824 // Remember that we parsed a reference type. It doesn't have type-quals. 2825 D.AddTypeInfo(DeclaratorChunk::getReference(DS.getTypeQualifiers(), Loc, 2826 DS.takeAttributes(), 2827 Kind == tok::amp), 2828 SourceLocation()); 2829 } 2830} 2831 2832/// ParseDirectDeclarator 2833/// direct-declarator: [C99 6.7.5] 2834/// [C99] identifier 2835/// '(' declarator ')' 2836/// [GNU] '(' attributes declarator ')' 2837/// [C90] direct-declarator '[' constant-expression[opt] ']' 2838/// [C99] direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']' 2839/// [C99] direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']' 2840/// [C99] direct-declarator '[' type-qual-list 'static' assignment-expr ']' 2841/// [C99] direct-declarator '[' type-qual-list[opt] '*' ']' 2842/// direct-declarator '(' parameter-type-list ')' 2843/// direct-declarator '(' identifier-list[opt] ')' 2844/// [GNU] direct-declarator '(' parameter-forward-declarations 2845/// parameter-type-list[opt] ')' 2846/// [C++] direct-declarator '(' parameter-declaration-clause ')' 2847/// cv-qualifier-seq[opt] exception-specification[opt] 2848/// [C++] declarator-id 2849/// 2850/// declarator-id: [C++ 8] 2851/// '...'[opt] id-expression 2852/// '::'[opt] nested-name-specifier[opt] type-name 2853/// 2854/// id-expression: [C++ 5.1] 2855/// unqualified-id 2856/// qualified-id 2857/// 2858/// unqualified-id: [C++ 5.1] 2859/// identifier 2860/// operator-function-id 2861/// conversion-function-id 2862/// '~' class-name 2863/// template-id 2864/// 2865void Parser::ParseDirectDeclarator(Declarator &D) { 2866 DeclaratorScopeObj DeclScopeObj(*this, D.getCXXScopeSpec()); 2867 2868 if (getLang().CPlusPlus && D.mayHaveIdentifier()) { 2869 // ParseDeclaratorInternal might already have parsed the scope. 2870 if (D.getCXXScopeSpec().isEmpty()) { 2871 ParseOptionalCXXScopeSpecifier(D.getCXXScopeSpec(), ParsedType(), true); 2872 } 2873 2874 if (D.getCXXScopeSpec().isValid()) { 2875 if (Actions.ShouldEnterDeclaratorScope(getCurScope(), D.getCXXScopeSpec())) 2876 // Change the declaration context for name lookup, until this function 2877 // is exited (and the declarator has been parsed). 2878 DeclScopeObj.EnterDeclaratorScope(); 2879 } 2880 2881 // C++0x [dcl.fct]p14: 2882 // There is a syntactic ambiguity when an ellipsis occurs at the end 2883 // of a parameter-declaration-clause without a preceding comma. In 2884 // this case, the ellipsis is parsed as part of the 2885 // abstract-declarator if the type of the parameter names a template 2886 // parameter pack that has not been expanded; otherwise, it is parsed 2887 // as part of the parameter-declaration-clause. 2888 if (Tok.is(tok::ellipsis) && 2889 !((D.getContext() == Declarator::PrototypeContext || 2890 D.getContext() == Declarator::BlockLiteralContext) && 2891 NextToken().is(tok::r_paren) && 2892 !Actions.containsUnexpandedParameterPacks(D))) 2893 D.setEllipsisLoc(ConsumeToken()); 2894 2895 if (Tok.is(tok::identifier) || Tok.is(tok::kw_operator) || 2896 Tok.is(tok::annot_template_id) || Tok.is(tok::tilde)) { 2897 // We found something that indicates the start of an unqualified-id. 2898 // Parse that unqualified-id. 2899 bool AllowConstructorName; 2900 if (D.getDeclSpec().hasTypeSpecifier()) 2901 AllowConstructorName = false; 2902 else if (D.getCXXScopeSpec().isSet()) 2903 AllowConstructorName = 2904 (D.getContext() == Declarator::FileContext || 2905 (D.getContext() == Declarator::MemberContext && 2906 D.getDeclSpec().isFriendSpecified())); 2907 else 2908 AllowConstructorName = (D.getContext() == Declarator::MemberContext); 2909 2910 if (ParseUnqualifiedId(D.getCXXScopeSpec(), 2911 /*EnteringContext=*/true, 2912 /*AllowDestructorName=*/true, 2913 AllowConstructorName, 2914 ParsedType(), 2915 D.getName()) || 2916 // Once we're past the identifier, if the scope was bad, mark the 2917 // whole declarator bad. 2918 D.getCXXScopeSpec().isInvalid()) { 2919 D.SetIdentifier(0, Tok.getLocation()); 2920 D.setInvalidType(true); 2921 } else { 2922 // Parsed the unqualified-id; update range information and move along. 2923 if (D.getSourceRange().getBegin().isInvalid()) 2924 D.SetRangeBegin(D.getName().getSourceRange().getBegin()); 2925 D.SetRangeEnd(D.getName().getSourceRange().getEnd()); 2926 } 2927 goto PastIdentifier; 2928 } 2929 } else if (Tok.is(tok::identifier) && D.mayHaveIdentifier()) { 2930 assert(!getLang().CPlusPlus && 2931 "There's a C++-specific check for tok::identifier above"); 2932 assert(Tok.getIdentifierInfo() && "Not an identifier?"); 2933 D.SetIdentifier(Tok.getIdentifierInfo(), Tok.getLocation()); 2934 ConsumeToken(); 2935 goto PastIdentifier; 2936 } 2937 2938 if (Tok.is(tok::l_paren)) { 2939 // direct-declarator: '(' declarator ')' 2940 // direct-declarator: '(' attributes declarator ')' 2941 // Example: 'char (*X)' or 'int (*XX)(void)' 2942 ParseParenDeclarator(D); 2943 2944 // If the declarator was parenthesized, we entered the declarator 2945 // scope when parsing the parenthesized declarator, then exited 2946 // the scope already. Re-enter the scope, if we need to. 2947 if (D.getCXXScopeSpec().isSet()) { 2948 // If there was an error parsing parenthesized declarator, declarator 2949 // scope may have been enterred before. Don't do it again. 2950 if (!D.isInvalidType() && 2951 Actions.ShouldEnterDeclaratorScope(getCurScope(), D.getCXXScopeSpec())) 2952 // Change the declaration context for name lookup, until this function 2953 // is exited (and the declarator has been parsed). 2954 DeclScopeObj.EnterDeclaratorScope(); 2955 } 2956 } else if (D.mayOmitIdentifier()) { 2957 // This could be something simple like "int" (in which case the declarator 2958 // portion is empty), if an abstract-declarator is allowed. 2959 D.SetIdentifier(0, Tok.getLocation()); 2960 } else { 2961 if (D.getContext() == Declarator::MemberContext) 2962 Diag(Tok, diag::err_expected_member_name_or_semi) 2963 << D.getDeclSpec().getSourceRange(); 2964 else if (getLang().CPlusPlus) 2965 Diag(Tok, diag::err_expected_unqualified_id) << getLang().CPlusPlus; 2966 else 2967 Diag(Tok, diag::err_expected_ident_lparen); 2968 D.SetIdentifier(0, Tok.getLocation()); 2969 D.setInvalidType(true); 2970 } 2971 2972 PastIdentifier: 2973 assert(D.isPastIdentifier() && 2974 "Haven't past the location of the identifier yet?"); 2975 2976 // Don't parse attributes unless we have an identifier. 2977 if (D.getIdentifier()) 2978 MaybeParseCXX0XAttributes(D); 2979 2980 while (1) { 2981 if (Tok.is(tok::l_paren)) { 2982 // The paren may be part of a C++ direct initializer, eg. "int x(1);". 2983 // In such a case, check if we actually have a function declarator; if it 2984 // is not, the declarator has been fully parsed. 2985 if (getLang().CPlusPlus && D.mayBeFollowedByCXXDirectInit()) { 2986 // When not in file scope, warn for ambiguous function declarators, just 2987 // in case the author intended it as a variable definition. 2988 bool warnIfAmbiguous = D.getContext() != Declarator::FileContext; 2989 if (!isCXXFunctionDeclarator(warnIfAmbiguous)) 2990 break; 2991 } 2992 ParsedAttributes attrs; 2993 ParseFunctionDeclarator(ConsumeParen(), D, attrs); 2994 } else if (Tok.is(tok::l_square)) { 2995 ParseBracketDeclarator(D); 2996 } else { 2997 break; 2998 } 2999 } 3000} 3001 3002/// ParseParenDeclarator - We parsed the declarator D up to a paren. This is 3003/// only called before the identifier, so these are most likely just grouping 3004/// parens for precedence. If we find that these are actually function 3005/// parameter parens in an abstract-declarator, we call ParseFunctionDeclarator. 3006/// 3007/// direct-declarator: 3008/// '(' declarator ')' 3009/// [GNU] '(' attributes declarator ')' 3010/// direct-declarator '(' parameter-type-list ')' 3011/// direct-declarator '(' identifier-list[opt] ')' 3012/// [GNU] direct-declarator '(' parameter-forward-declarations 3013/// parameter-type-list[opt] ')' 3014/// 3015void Parser::ParseParenDeclarator(Declarator &D) { 3016 SourceLocation StartLoc = ConsumeParen(); 3017 assert(!D.isPastIdentifier() && "Should be called before passing identifier"); 3018 3019 // Eat any attributes before we look at whether this is a grouping or function 3020 // declarator paren. If this is a grouping paren, the attribute applies to 3021 // the type being built up, for example: 3022 // int (__attribute__(()) *x)(long y) 3023 // If this ends up not being a grouping paren, the attribute applies to the 3024 // first argument, for example: 3025 // int (__attribute__(()) int x) 3026 // In either case, we need to eat any attributes to be able to determine what 3027 // sort of paren this is. 3028 // 3029 ParsedAttributes attrs; 3030 bool RequiresArg = false; 3031 if (Tok.is(tok::kw___attribute)) { 3032 ParseGNUAttributes(attrs); 3033 3034 // We require that the argument list (if this is a non-grouping paren) be 3035 // present even if the attribute list was empty. 3036 RequiresArg = true; 3037 } 3038 // Eat any Microsoft extensions. 3039 if (Tok.is(tok::kw___cdecl) || Tok.is(tok::kw___stdcall) || 3040 Tok.is(tok::kw___thiscall) || Tok.is(tok::kw___fastcall) || 3041 Tok.is(tok::kw___w64) || Tok.is(tok::kw___ptr64)) { 3042 ParseMicrosoftTypeAttributes(attrs); 3043 } 3044 // Eat any Borland extensions. 3045 if (Tok.is(tok::kw___pascal)) 3046 ParseBorlandTypeAttributes(attrs); 3047 3048 // If we haven't past the identifier yet (or where the identifier would be 3049 // stored, if this is an abstract declarator), then this is probably just 3050 // grouping parens. However, if this could be an abstract-declarator, then 3051 // this could also be the start of function arguments (consider 'void()'). 3052 bool isGrouping; 3053 3054 if (!D.mayOmitIdentifier()) { 3055 // If this can't be an abstract-declarator, this *must* be a grouping 3056 // paren, because we haven't seen the identifier yet. 3057 isGrouping = true; 3058 } else if (Tok.is(tok::r_paren) || // 'int()' is a function. 3059 (getLang().CPlusPlus && Tok.is(tok::ellipsis)) || // C++ int(...) 3060 isDeclarationSpecifier()) { // 'int(int)' is a function. 3061 // This handles C99 6.7.5.3p11: in "typedef int X; void foo(X)", X is 3062 // considered to be a type, not a K&R identifier-list. 3063 isGrouping = false; 3064 } else { 3065 // Otherwise, this is a grouping paren, e.g. 'int (*X)' or 'int(X)'. 3066 isGrouping = true; 3067 } 3068 3069 // If this is a grouping paren, handle: 3070 // direct-declarator: '(' declarator ')' 3071 // direct-declarator: '(' attributes declarator ')' 3072 if (isGrouping) { 3073 bool hadGroupingParens = D.hasGroupingParens(); 3074 D.setGroupingParens(true); 3075 if (!attrs.empty()) 3076 D.addAttributes(attrs.getList(), SourceLocation()); 3077 3078 ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator); 3079 // Match the ')'. 3080 SourceLocation EndLoc = MatchRHSPunctuation(tok::r_paren, StartLoc); 3081 D.AddTypeInfo(DeclaratorChunk::getParen(StartLoc, EndLoc), EndLoc); 3082 3083 D.setGroupingParens(hadGroupingParens); 3084 return; 3085 } 3086 3087 // Okay, if this wasn't a grouping paren, it must be the start of a function 3088 // argument list. Recognize that this declarator will never have an 3089 // identifier (and remember where it would have been), then call into 3090 // ParseFunctionDeclarator to handle of argument list. 3091 D.SetIdentifier(0, Tok.getLocation()); 3092 3093 ParseFunctionDeclarator(StartLoc, D, attrs, RequiresArg); 3094} 3095 3096/// ParseFunctionDeclarator - We are after the identifier and have parsed the 3097/// declarator D up to a paren, which indicates that we are parsing function 3098/// arguments. 3099/// 3100/// If AttrList is non-null, then the caller parsed those arguments immediately 3101/// after the open paren - they should be considered to be the first argument of 3102/// a parameter. If RequiresArg is true, then the first argument of the 3103/// function is required to be present and required to not be an identifier 3104/// list. 3105/// 3106/// This method also handles this portion of the grammar: 3107/// parameter-type-list: [C99 6.7.5] 3108/// parameter-list 3109/// parameter-list ',' '...' 3110/// [C++] parameter-list '...' 3111/// 3112/// parameter-list: [C99 6.7.5] 3113/// parameter-declaration 3114/// parameter-list ',' parameter-declaration 3115/// 3116/// parameter-declaration: [C99 6.7.5] 3117/// declaration-specifiers declarator 3118/// [C++] declaration-specifiers declarator '=' assignment-expression 3119/// [GNU] declaration-specifiers declarator attributes 3120/// declaration-specifiers abstract-declarator[opt] 3121/// [C++] declaration-specifiers abstract-declarator[opt] 3122/// '=' assignment-expression 3123/// [GNU] declaration-specifiers abstract-declarator[opt] attributes 3124/// 3125/// For C++, after the parameter-list, it also parses "cv-qualifier-seq[opt]", 3126/// C++0x "ref-qualifier[opt]" and "exception-specification[opt]". 3127/// 3128void Parser::ParseFunctionDeclarator(SourceLocation LParenLoc, Declarator &D, 3129 ParsedAttributes &attrs, 3130 bool RequiresArg) { 3131 // lparen is already consumed! 3132 assert(D.isPastIdentifier() && "Should not call before identifier!"); 3133 3134 ParsedType TrailingReturnType; 3135 3136 // This parameter list may be empty. 3137 if (Tok.is(tok::r_paren)) { 3138 if (RequiresArg) 3139 Diag(Tok, diag::err_argument_required_after_attribute); 3140 3141 SourceLocation RParenLoc = ConsumeParen(); // Eat the closing ')'. 3142 SourceLocation EndLoc = RParenLoc; 3143 3144 // cv-qualifier-seq[opt]. 3145 DeclSpec DS; 3146 SourceLocation RefQualifierLoc; 3147 bool RefQualifierIsLValueRef = true; 3148 bool hasExceptionSpec = false; 3149 SourceLocation ThrowLoc; 3150 bool hasAnyExceptionSpec = false; 3151 llvm::SmallVector<ParsedType, 2> Exceptions; 3152 llvm::SmallVector<SourceRange, 2> ExceptionRanges; 3153 if (getLang().CPlusPlus) { 3154 MaybeParseCXX0XAttributes(attrs); 3155 3156 ParseTypeQualifierListOpt(DS, false /*no attributes*/); 3157 if (!DS.getSourceRange().getEnd().isInvalid()) 3158 EndLoc = DS.getSourceRange().getEnd(); 3159 3160 // Parse ref-qualifier[opt] 3161 if (Tok.is(tok::amp) || Tok.is(tok::ampamp)) { 3162 if (!getLang().CPlusPlus0x) 3163 Diag(Tok, diag::ext_ref_qualifier); 3164 3165 RefQualifierIsLValueRef = Tok.is(tok::amp); 3166 RefQualifierLoc = ConsumeToken(); 3167 EndLoc = RefQualifierLoc; 3168 } 3169 3170 // Parse exception-specification[opt]. 3171 if (Tok.is(tok::kw_throw)) { 3172 hasExceptionSpec = true; 3173 ThrowLoc = Tok.getLocation(); 3174 ParseExceptionSpecification(EndLoc, Exceptions, ExceptionRanges, 3175 hasAnyExceptionSpec); 3176 assert(Exceptions.size() == ExceptionRanges.size() && 3177 "Produced different number of exception types and ranges."); 3178 } 3179 3180 // Parse trailing-return-type. 3181 if (getLang().CPlusPlus0x && Tok.is(tok::arrow)) { 3182 TrailingReturnType = ParseTrailingReturnType().get(); 3183 } 3184 } 3185 3186 // Remember that we parsed a function type, and remember the attributes. 3187 // int() -> no prototype, no '...'. 3188 D.AddTypeInfo(DeclaratorChunk::getFunction(attrs, 3189 /*prototype*/getLang().CPlusPlus, 3190 /*variadic*/ false, 3191 SourceLocation(), 3192 /*arglist*/ 0, 0, 3193 DS.getTypeQualifiers(), 3194 RefQualifierIsLValueRef, 3195 RefQualifierLoc, 3196 hasExceptionSpec, ThrowLoc, 3197 hasAnyExceptionSpec, 3198 Exceptions.data(), 3199 ExceptionRanges.data(), 3200 Exceptions.size(), 3201 LParenLoc, RParenLoc, D, 3202 TrailingReturnType), 3203 EndLoc); 3204 return; 3205 } 3206 3207 // Alternatively, this parameter list may be an identifier list form for a 3208 // K&R-style function: void foo(a,b,c) 3209 if (!getLang().CPlusPlus && Tok.is(tok::identifier) 3210 && !TryAltiVecVectorToken()) { 3211 if (TryAnnotateTypeOrScopeToken() || !Tok.is(tok::annot_typename)) { 3212 // K&R identifier lists can't have typedefs as identifiers, per 3213 // C99 6.7.5.3p11. 3214 if (RequiresArg) 3215 Diag(Tok, diag::err_argument_required_after_attribute); 3216 3217 // Identifier list. Note that '(' identifier-list ')' is only allowed for 3218 // normal declarators, not for abstract-declarators. Get the first 3219 // identifier. 3220 Token FirstTok = Tok; 3221 ConsumeToken(); // eat the first identifier. 3222 3223 // Identifier lists follow a really simple grammar: the identifiers can 3224 // be followed *only* by a ", moreidentifiers" or ")". However, K&R 3225 // identifier lists are really rare in the brave new modern world, and it 3226 // is very common for someone to typo a type in a non-k&r style list. If 3227 // we are presented with something like: "void foo(intptr x, float y)", 3228 // we don't want to start parsing the function declarator as though it is 3229 // a K&R style declarator just because intptr is an invalid type. 3230 // 3231 // To handle this, we check to see if the token after the first identifier 3232 // is a "," or ")". Only if so, do we parse it as an identifier list. 3233 if (Tok.is(tok::comma) || Tok.is(tok::r_paren)) 3234 return ParseFunctionDeclaratorIdentifierList(LParenLoc, 3235 FirstTok.getIdentifierInfo(), 3236 FirstTok.getLocation(), D); 3237 3238 // If we get here, the code is invalid. Push the first identifier back 3239 // into the token stream and parse the first argument as an (invalid) 3240 // normal argument declarator. 3241 PP.EnterToken(Tok); 3242 Tok = FirstTok; 3243 } 3244 } 3245 3246 // Finally, a normal, non-empty parameter type list. 3247 3248 // Build up an array of information about the parsed arguments. 3249 llvm::SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo; 3250 3251 // Enter function-declaration scope, limiting any declarators to the 3252 // function prototype scope, including parameter declarators. 3253 ParseScope PrototypeScope(this, 3254 Scope::FunctionPrototypeScope|Scope::DeclScope); 3255 3256 bool IsVariadic = false; 3257 SourceLocation EllipsisLoc; 3258 while (1) { 3259 if (Tok.is(tok::ellipsis)) { 3260 IsVariadic = true; 3261 EllipsisLoc = ConsumeToken(); // Consume the ellipsis. 3262 break; 3263 } 3264 3265 // Parse the declaration-specifiers. 3266 // Just use the ParsingDeclaration "scope" of the declarator. 3267 DeclSpec DS; 3268 3269 // Skip any Microsoft attributes before a param. 3270 if (getLang().Microsoft && Tok.is(tok::l_square)) 3271 ParseMicrosoftAttributes(DS.getAttributes()); 3272 3273 SourceLocation DSStart = Tok.getLocation(); 3274 3275 // If the caller parsed attributes for the first argument, add them now. 3276 // Take them so that we only apply the attributes to the first parameter. 3277 DS.takeAttributesFrom(attrs); 3278 3279 ParseDeclarationSpecifiers(DS); 3280 3281 // Parse the declarator. This is "PrototypeContext", because we must 3282 // accept either 'declarator' or 'abstract-declarator' here. 3283 Declarator ParmDecl(DS, Declarator::PrototypeContext); 3284 ParseDeclarator(ParmDecl); 3285 3286 // Parse GNU attributes, if present. 3287 MaybeParseGNUAttributes(ParmDecl); 3288 3289 // Remember this parsed parameter in ParamInfo. 3290 IdentifierInfo *ParmII = ParmDecl.getIdentifier(); 3291 3292 // DefArgToks is used when the parsing of default arguments needs 3293 // to be delayed. 3294 CachedTokens *DefArgToks = 0; 3295 3296 // If no parameter was specified, verify that *something* was specified, 3297 // otherwise we have a missing type and identifier. 3298 if (DS.isEmpty() && ParmDecl.getIdentifier() == 0 && 3299 ParmDecl.getNumTypeObjects() == 0) { 3300 // Completely missing, emit error. 3301 Diag(DSStart, diag::err_missing_param); 3302 } else { 3303 // Otherwise, we have something. Add it and let semantic analysis try 3304 // to grok it and add the result to the ParamInfo we are building. 3305 3306 // Inform the actions module about the parameter declarator, so it gets 3307 // added to the current scope. 3308 Decl *Param = Actions.ActOnParamDeclarator(getCurScope(), ParmDecl); 3309 3310 // Parse the default argument, if any. We parse the default 3311 // arguments in all dialects; the semantic analysis in 3312 // ActOnParamDefaultArgument will reject the default argument in 3313 // C. 3314 if (Tok.is(tok::equal)) { 3315 SourceLocation EqualLoc = Tok.getLocation(); 3316 3317 // Parse the default argument 3318 if (D.getContext() == Declarator::MemberContext) { 3319 // If we're inside a class definition, cache the tokens 3320 // corresponding to the default argument. We'll actually parse 3321 // them when we see the end of the class definition. 3322 // FIXME: Templates will require something similar. 3323 // FIXME: Can we use a smart pointer for Toks? 3324 DefArgToks = new CachedTokens; 3325 3326 if (!ConsumeAndStoreUntil(tok::comma, tok::r_paren, *DefArgToks, 3327 /*StopAtSemi=*/true, 3328 /*ConsumeFinalToken=*/false)) { 3329 delete DefArgToks; 3330 DefArgToks = 0; 3331 Actions.ActOnParamDefaultArgumentError(Param); 3332 } else { 3333 // Mark the end of the default argument so that we know when to 3334 // stop when we parse it later on. 3335 Token DefArgEnd; 3336 DefArgEnd.startToken(); 3337 DefArgEnd.setKind(tok::cxx_defaultarg_end); 3338 DefArgEnd.setLocation(Tok.getLocation()); 3339 DefArgToks->push_back(DefArgEnd); 3340 Actions.ActOnParamUnparsedDefaultArgument(Param, EqualLoc, 3341 (*DefArgToks)[1].getLocation()); 3342 } 3343 } else { 3344 // Consume the '='. 3345 ConsumeToken(); 3346 3347 // The argument isn't actually potentially evaluated unless it is 3348 // used. 3349 EnterExpressionEvaluationContext Eval(Actions, 3350 Sema::PotentiallyEvaluatedIfUsed); 3351 3352 ExprResult DefArgResult(ParseAssignmentExpression()); 3353 if (DefArgResult.isInvalid()) { 3354 Actions.ActOnParamDefaultArgumentError(Param); 3355 SkipUntil(tok::comma, tok::r_paren, true, true); 3356 } else { 3357 // Inform the actions module about the default argument 3358 Actions.ActOnParamDefaultArgument(Param, EqualLoc, 3359 DefArgResult.take()); 3360 } 3361 } 3362 } 3363 3364 ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII, 3365 ParmDecl.getIdentifierLoc(), Param, 3366 DefArgToks)); 3367 } 3368 3369 // If the next token is a comma, consume it and keep reading arguments. 3370 if (Tok.isNot(tok::comma)) { 3371 if (Tok.is(tok::ellipsis)) { 3372 IsVariadic = true; 3373 EllipsisLoc = ConsumeToken(); // Consume the ellipsis. 3374 3375 if (!getLang().CPlusPlus) { 3376 // We have ellipsis without a preceding ',', which is ill-formed 3377 // in C. Complain and provide the fix. 3378 Diag(EllipsisLoc, diag::err_missing_comma_before_ellipsis) 3379 << FixItHint::CreateInsertion(EllipsisLoc, ", "); 3380 } 3381 } 3382 3383 break; 3384 } 3385 3386 // Consume the comma. 3387 ConsumeToken(); 3388 } 3389 3390 // If we have the closing ')', eat it. 3391 SourceLocation RParenLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc); 3392 SourceLocation EndLoc = RParenLoc; 3393 3394 DeclSpec DS; 3395 SourceLocation RefQualifierLoc; 3396 bool RefQualifierIsLValueRef = true; 3397 bool hasExceptionSpec = false; 3398 SourceLocation ThrowLoc; 3399 bool hasAnyExceptionSpec = false; 3400 llvm::SmallVector<ParsedType, 2> Exceptions; 3401 llvm::SmallVector<SourceRange, 2> ExceptionRanges; 3402 3403 if (getLang().CPlusPlus) { 3404 MaybeParseCXX0XAttributes(attrs); 3405 3406 // Parse cv-qualifier-seq[opt]. 3407 ParseTypeQualifierListOpt(DS, false /*no attributes*/); 3408 if (!DS.getSourceRange().getEnd().isInvalid()) 3409 EndLoc = DS.getSourceRange().getEnd(); 3410 3411 // Parse ref-qualifier[opt] 3412 if (Tok.is(tok::amp) || Tok.is(tok::ampamp)) { 3413 if (!getLang().CPlusPlus0x) 3414 Diag(Tok, diag::ext_ref_qualifier); 3415 3416 RefQualifierIsLValueRef = Tok.is(tok::amp); 3417 RefQualifierLoc = ConsumeToken(); 3418 EndLoc = RefQualifierLoc; 3419 } 3420 3421 // Parse exception-specification[opt]. 3422 if (Tok.is(tok::kw_throw)) { 3423 hasExceptionSpec = true; 3424 ThrowLoc = Tok.getLocation(); 3425 ParseExceptionSpecification(EndLoc, Exceptions, ExceptionRanges, 3426 hasAnyExceptionSpec); 3427 assert(Exceptions.size() == ExceptionRanges.size() && 3428 "Produced different number of exception types and ranges."); 3429 } 3430 3431 // Parse trailing-return-type. 3432 if (getLang().CPlusPlus0x && Tok.is(tok::arrow)) { 3433 TrailingReturnType = ParseTrailingReturnType().get(); 3434 } 3435 } 3436 3437 // FIXME: We should leave the prototype scope before parsing the exception 3438 // specification, and then reenter it when parsing the trailing return type. 3439 3440 // Leave prototype scope. 3441 PrototypeScope.Exit(); 3442 3443 // Remember that we parsed a function type, and remember the attributes. 3444 D.AddTypeInfo(DeclaratorChunk::getFunction(attrs, 3445 /*proto*/true, IsVariadic, 3446 EllipsisLoc, 3447 ParamInfo.data(), ParamInfo.size(), 3448 DS.getTypeQualifiers(), 3449 RefQualifierIsLValueRef, 3450 RefQualifierLoc, 3451 hasExceptionSpec, ThrowLoc, 3452 hasAnyExceptionSpec, 3453 Exceptions.data(), 3454 ExceptionRanges.data(), 3455 Exceptions.size(), 3456 LParenLoc, RParenLoc, D, 3457 TrailingReturnType), 3458 EndLoc); 3459} 3460 3461/// ParseFunctionDeclaratorIdentifierList - While parsing a function declarator 3462/// we found a K&R-style identifier list instead of a type argument list. The 3463/// first identifier has already been consumed, and the current token is the 3464/// token right after it. 3465/// 3466/// identifier-list: [C99 6.7.5] 3467/// identifier 3468/// identifier-list ',' identifier 3469/// 3470void Parser::ParseFunctionDeclaratorIdentifierList(SourceLocation LParenLoc, 3471 IdentifierInfo *FirstIdent, 3472 SourceLocation FirstIdentLoc, 3473 Declarator &D) { 3474 // Build up an array of information about the parsed arguments. 3475 llvm::SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo; 3476 llvm::SmallSet<const IdentifierInfo*, 16> ParamsSoFar; 3477 3478 // If there was no identifier specified for the declarator, either we are in 3479 // an abstract-declarator, or we are in a parameter declarator which was found 3480 // to be abstract. In abstract-declarators, identifier lists are not valid: 3481 // diagnose this. 3482 if (!D.getIdentifier()) 3483 Diag(FirstIdentLoc, diag::ext_ident_list_in_param); 3484 3485 // The first identifier was already read, and is known to be the first 3486 // identifier in the list. Remember this identifier in ParamInfo. 3487 ParamsSoFar.insert(FirstIdent); 3488 ParamInfo.push_back(DeclaratorChunk::ParamInfo(FirstIdent, FirstIdentLoc, 0)); 3489 3490 while (Tok.is(tok::comma)) { 3491 // Eat the comma. 3492 ConsumeToken(); 3493 3494 // If this isn't an identifier, report the error and skip until ')'. 3495 if (Tok.isNot(tok::identifier)) { 3496 Diag(Tok, diag::err_expected_ident); 3497 SkipUntil(tok::r_paren); 3498 return; 3499 } 3500 3501 IdentifierInfo *ParmII = Tok.getIdentifierInfo(); 3502 3503 // Reject 'typedef int y; int test(x, y)', but continue parsing. 3504 if (Actions.getTypeName(*ParmII, Tok.getLocation(), getCurScope())) 3505 Diag(Tok, diag::err_unexpected_typedef_ident) << ParmII; 3506 3507 // Verify that the argument identifier has not already been mentioned. 3508 if (!ParamsSoFar.insert(ParmII)) { 3509 Diag(Tok, diag::err_param_redefinition) << ParmII; 3510 } else { 3511 // Remember this identifier in ParamInfo. 3512 ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII, 3513 Tok.getLocation(), 3514 0)); 3515 } 3516 3517 // Eat the identifier. 3518 ConsumeToken(); 3519 } 3520 3521 // If we have the closing ')', eat it and we're done. 3522 SourceLocation RLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc); 3523 3524 // Remember that we parsed a function type, and remember the attributes. This 3525 // function type is always a K&R style function type, which is not varargs and 3526 // has no prototype. 3527 D.AddTypeInfo(DeclaratorChunk::getFunction(ParsedAttributes(), 3528 /*proto*/false, /*varargs*/false, 3529 SourceLocation(), 3530 &ParamInfo[0], ParamInfo.size(), 3531 /*TypeQuals*/0, 3532 true, SourceLocation(), 3533 /*exception*/false, 3534 SourceLocation(), false, 0, 0, 0, 3535 LParenLoc, RLoc, D), 3536 RLoc); 3537} 3538 3539/// [C90] direct-declarator '[' constant-expression[opt] ']' 3540/// [C99] direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']' 3541/// [C99] direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']' 3542/// [C99] direct-declarator '[' type-qual-list 'static' assignment-expr ']' 3543/// [C99] direct-declarator '[' type-qual-list[opt] '*' ']' 3544void Parser::ParseBracketDeclarator(Declarator &D) { 3545 SourceLocation StartLoc = ConsumeBracket(); 3546 3547 // C array syntax has many features, but by-far the most common is [] and [4]. 3548 // This code does a fast path to handle some of the most obvious cases. 3549 if (Tok.getKind() == tok::r_square) { 3550 SourceLocation EndLoc = MatchRHSPunctuation(tok::r_square, StartLoc); 3551 ParsedAttributes attrs; 3552 MaybeParseCXX0XAttributes(attrs); 3553 3554 // Remember that we parsed the empty array type. 3555 ExprResult NumElements; 3556 D.AddTypeInfo(DeclaratorChunk::getArray(0, attrs, false, false, 0, 3557 StartLoc, EndLoc), 3558 EndLoc); 3559 return; 3560 } else if (Tok.getKind() == tok::numeric_constant && 3561 GetLookAheadToken(1).is(tok::r_square)) { 3562 // [4] is very common. Parse the numeric constant expression. 3563 ExprResult ExprRes(Actions.ActOnNumericConstant(Tok)); 3564 ConsumeToken(); 3565 3566 SourceLocation EndLoc = MatchRHSPunctuation(tok::r_square, StartLoc); 3567 ParsedAttributes attrs; 3568 MaybeParseCXX0XAttributes(attrs); 3569 3570 // Remember that we parsed a array type, and remember its features. 3571 D.AddTypeInfo(DeclaratorChunk::getArray(0, attrs, false, 0, 3572 ExprRes.release(), 3573 StartLoc, EndLoc), 3574 EndLoc); 3575 return; 3576 } 3577 3578 // If valid, this location is the position where we read the 'static' keyword. 3579 SourceLocation StaticLoc; 3580 if (Tok.is(tok::kw_static)) 3581 StaticLoc = ConsumeToken(); 3582 3583 // If there is a type-qualifier-list, read it now. 3584 // Type qualifiers in an array subscript are a C99 feature. 3585 DeclSpec DS; 3586 ParseTypeQualifierListOpt(DS, false /*no attributes*/); 3587 3588 // If we haven't already read 'static', check to see if there is one after the 3589 // type-qualifier-list. 3590 if (!StaticLoc.isValid() && Tok.is(tok::kw_static)) 3591 StaticLoc = ConsumeToken(); 3592 3593 // Handle "direct-declarator [ type-qual-list[opt] * ]". 3594 bool isStar = false; 3595 ExprResult NumElements; 3596 3597 // Handle the case where we have '[*]' as the array size. However, a leading 3598 // star could be the start of an expression, for example 'X[*p + 4]'. Verify 3599 // the the token after the star is a ']'. Since stars in arrays are 3600 // infrequent, use of lookahead is not costly here. 3601 if (Tok.is(tok::star) && GetLookAheadToken(1).is(tok::r_square)) { 3602 ConsumeToken(); // Eat the '*'. 3603 3604 if (StaticLoc.isValid()) { 3605 Diag(StaticLoc, diag::err_unspecified_vla_size_with_static); 3606 StaticLoc = SourceLocation(); // Drop the static. 3607 } 3608 isStar = true; 3609 } else if (Tok.isNot(tok::r_square)) { 3610 // Note, in C89, this production uses the constant-expr production instead 3611 // of assignment-expr. The only difference is that assignment-expr allows 3612 // things like '=' and '*='. Sema rejects these in C89 mode because they 3613 // are not i-c-e's, so we don't need to distinguish between the two here. 3614 3615 // Parse the constant-expression or assignment-expression now (depending 3616 // on dialect). 3617 if (getLang().CPlusPlus) 3618 NumElements = ParseConstantExpression(); 3619 else 3620 NumElements = ParseAssignmentExpression(); 3621 } 3622 3623 // If there was an error parsing the assignment-expression, recover. 3624 if (NumElements.isInvalid()) { 3625 D.setInvalidType(true); 3626 // If the expression was invalid, skip it. 3627 SkipUntil(tok::r_square); 3628 return; 3629 } 3630 3631 SourceLocation EndLoc = MatchRHSPunctuation(tok::r_square, StartLoc); 3632 3633 ParsedAttributes attrs; 3634 MaybeParseCXX0XAttributes(attrs); 3635 3636 // Remember that we parsed a array type, and remember its features. 3637 D.AddTypeInfo(DeclaratorChunk::getArray(DS.getTypeQualifiers(), attrs, 3638 StaticLoc.isValid(), isStar, 3639 NumElements.release(), 3640 StartLoc, EndLoc), 3641 EndLoc); 3642} 3643 3644/// [GNU] typeof-specifier: 3645/// typeof ( expressions ) 3646/// typeof ( type-name ) 3647/// [GNU/C++] typeof unary-expression 3648/// 3649void Parser::ParseTypeofSpecifier(DeclSpec &DS) { 3650 assert(Tok.is(tok::kw_typeof) && "Not a typeof specifier"); 3651 Token OpTok = Tok; 3652 SourceLocation StartLoc = ConsumeToken(); 3653 3654 const bool hasParens = Tok.is(tok::l_paren); 3655 3656 bool isCastExpr; 3657 ParsedType CastTy; 3658 SourceRange CastRange; 3659 ExprResult Operand = ParseExprAfterTypeofSizeofAlignof(OpTok, 3660 isCastExpr, 3661 CastTy, 3662 CastRange); 3663 if (hasParens) 3664 DS.setTypeofParensRange(CastRange); 3665 3666 if (CastRange.getEnd().isInvalid()) 3667 // FIXME: Not accurate, the range gets one token more than it should. 3668 DS.SetRangeEnd(Tok.getLocation()); 3669 else 3670 DS.SetRangeEnd(CastRange.getEnd()); 3671 3672 if (isCastExpr) { 3673 if (!CastTy) { 3674 DS.SetTypeSpecError(); 3675 return; 3676 } 3677 3678 const char *PrevSpec = 0; 3679 unsigned DiagID; 3680 // Check for duplicate type specifiers (e.g. "int typeof(int)"). 3681 if (DS.SetTypeSpecType(DeclSpec::TST_typeofType, StartLoc, PrevSpec, 3682 DiagID, CastTy)) 3683 Diag(StartLoc, DiagID) << PrevSpec; 3684 return; 3685 } 3686 3687 // If we get here, the operand to the typeof was an expresion. 3688 if (Operand.isInvalid()) { 3689 DS.SetTypeSpecError(); 3690 return; 3691 } 3692 3693 const char *PrevSpec = 0; 3694 unsigned DiagID; 3695 // Check for duplicate type specifiers (e.g. "int typeof(int)"). 3696 if (DS.SetTypeSpecType(DeclSpec::TST_typeofExpr, StartLoc, PrevSpec, 3697 DiagID, Operand.get())) 3698 Diag(StartLoc, DiagID) << PrevSpec; 3699} 3700 3701 3702/// TryAltiVecVectorTokenOutOfLine - Out of line body that should only be called 3703/// from TryAltiVecVectorToken. 3704bool Parser::TryAltiVecVectorTokenOutOfLine() { 3705 Token Next = NextToken(); 3706 switch (Next.getKind()) { 3707 default: return false; 3708 case tok::kw_short: 3709 case tok::kw_long: 3710 case tok::kw_signed: 3711 case tok::kw_unsigned: 3712 case tok::kw_void: 3713 case tok::kw_char: 3714 case tok::kw_int: 3715 case tok::kw_float: 3716 case tok::kw_double: 3717 case tok::kw_bool: 3718 case tok::kw___pixel: 3719 Tok.setKind(tok::kw___vector); 3720 return true; 3721 case tok::identifier: 3722 if (Next.getIdentifierInfo() == Ident_pixel) { 3723 Tok.setKind(tok::kw___vector); 3724 return true; 3725 } 3726 return false; 3727 } 3728} 3729 3730bool Parser::TryAltiVecTokenOutOfLine(DeclSpec &DS, SourceLocation Loc, 3731 const char *&PrevSpec, unsigned &DiagID, 3732 bool &isInvalid) { 3733 if (Tok.getIdentifierInfo() == Ident_vector) { 3734 Token Next = NextToken(); 3735 switch (Next.getKind()) { 3736 case tok::kw_short: 3737 case tok::kw_long: 3738 case tok::kw_signed: 3739 case tok::kw_unsigned: 3740 case tok::kw_void: 3741 case tok::kw_char: 3742 case tok::kw_int: 3743 case tok::kw_float: 3744 case tok::kw_double: 3745 case tok::kw_bool: 3746 case tok::kw___pixel: 3747 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID); 3748 return true; 3749 case tok::identifier: 3750 if (Next.getIdentifierInfo() == Ident_pixel) { 3751 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID); 3752 return true; 3753 } 3754 break; 3755 default: 3756 break; 3757 } 3758 } else if ((Tok.getIdentifierInfo() == Ident_pixel) && 3759 DS.isTypeAltiVecVector()) { 3760 isInvalid = DS.SetTypeAltiVecPixel(true, Loc, PrevSpec, DiagID); 3761 return true; 3762 } 3763 return false; 3764} 3765