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