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