ParseDecl.cpp revision d9bafa76f8d6eb9e4f4974ed322217f8df6bb82e
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 "paramterized" attribute 114 if (Tok.is(tok::l_paren)) { 115 ConsumeParen(); // ignore the left paren loc for now 116 117 if (Tok.is(tok::identifier)) { 118 IdentifierInfo *ParmName = Tok.getIdentifierInfo(); 119 SourceLocation ParmLoc = ConsumeToken(); 120 121 if (Tok.is(tok::r_paren)) { 122 // __attribute__(( mode(byte) )) 123 ConsumeParen(); // ignore the right paren loc for now 124 CurrAttr = new AttributeList(AttrName, AttrNameLoc, 0, AttrNameLoc, 125 ParmName, ParmLoc, 0, 0, CurrAttr); 126 } else if (Tok.is(tok::comma)) { 127 ConsumeToken(); 128 // __attribute__(( format(printf, 1, 2) )) 129 ExprVector ArgExprs(Actions); 130 bool ArgExprsOk = true; 131 132 // now parse the non-empty comma separated list of expressions 133 while (1) { 134 OwningExprResult ArgExpr(ParseAssignmentExpression()); 135 if (ArgExpr.isInvalid()) { 136 ArgExprsOk = false; 137 SkipUntil(tok::r_paren); 138 break; 139 } else { 140 ArgExprs.push_back(ArgExpr.release()); 141 } 142 if (Tok.isNot(tok::comma)) 143 break; 144 ConsumeToken(); // Eat the comma, move to the next argument 145 } 146 if (ArgExprsOk && Tok.is(tok::r_paren)) { 147 ConsumeParen(); // ignore the right paren loc for now 148 CurrAttr = new AttributeList(AttrName, AttrNameLoc, 0, 149 AttrNameLoc, ParmName, ParmLoc, 150 ArgExprs.take(), ArgExprs.size(), 151 CurrAttr); 152 } 153 } 154 } else { // not an identifier 155 switch (Tok.getKind()) { 156 case tok::r_paren: 157 // parse a possibly empty comma separated list of expressions 158 // __attribute__(( nonnull() )) 159 ConsumeParen(); // ignore the right paren loc for now 160 CurrAttr = new AttributeList(AttrName, AttrNameLoc, 0, AttrNameLoc, 161 0, SourceLocation(), 0, 0, CurrAttr); 162 break; 163 case tok::kw_char: 164 case tok::kw_wchar_t: 165 case tok::kw_char16_t: 166 case tok::kw_char32_t: 167 case tok::kw_bool: 168 case tok::kw_short: 169 case tok::kw_int: 170 case tok::kw_long: 171 case tok::kw_signed: 172 case tok::kw_unsigned: 173 case tok::kw_float: 174 case tok::kw_double: 175 case tok::kw_void: 176 case tok::kw_typeof: 177 // If it's a builtin type name, eat it and expect a rparen 178 // __attribute__(( vec_type_hint(char) )) 179 ConsumeToken(); 180 CurrAttr = new AttributeList(AttrName, AttrNameLoc, 0, AttrNameLoc, 181 0, SourceLocation(), 0, 0, CurrAttr); 182 if (Tok.is(tok::r_paren)) 183 ConsumeParen(); 184 break; 185 default: 186 // __attribute__(( aligned(16) )) 187 ExprVector ArgExprs(Actions); 188 bool ArgExprsOk = true; 189 190 // now parse the list of expressions 191 while (1) { 192 OwningExprResult ArgExpr(ParseAssignmentExpression()); 193 if (ArgExpr.isInvalid()) { 194 ArgExprsOk = false; 195 SkipUntil(tok::r_paren); 196 break; 197 } else { 198 ArgExprs.push_back(ArgExpr.release()); 199 } 200 if (Tok.isNot(tok::comma)) 201 break; 202 ConsumeToken(); // Eat the comma, move to the next argument 203 } 204 // Match the ')'. 205 if (ArgExprsOk && Tok.is(tok::r_paren)) { 206 ConsumeParen(); // ignore the right paren loc for now 207 CurrAttr = new AttributeList(AttrName, AttrNameLoc, 0, 208 AttrNameLoc, 0, SourceLocation(), ArgExprs.take(), 209 ArgExprs.size(), 210 CurrAttr); 211 } 212 break; 213 } 214 } 215 } else { 216 CurrAttr = new AttributeList(AttrName, AttrNameLoc, 0, AttrNameLoc, 217 0, SourceLocation(), 0, 0, CurrAttr); 218 } 219 } 220 if (ExpectAndConsume(tok::r_paren, diag::err_expected_rparen)) 221 SkipUntil(tok::r_paren, false); 222 SourceLocation Loc = Tok.getLocation(); 223 if (ExpectAndConsume(tok::r_paren, diag::err_expected_rparen)) { 224 SkipUntil(tok::r_paren, false); 225 } 226 if (EndLoc) 227 *EndLoc = Loc; 228 } 229 return CurrAttr; 230} 231 232/// ParseMicrosoftDeclSpec - Parse an __declspec construct 233/// 234/// [MS] decl-specifier: 235/// __declspec ( extended-decl-modifier-seq ) 236/// 237/// [MS] extended-decl-modifier-seq: 238/// extended-decl-modifier[opt] 239/// extended-decl-modifier extended-decl-modifier-seq 240 241AttributeList* Parser::ParseMicrosoftDeclSpec(AttributeList *CurrAttr) { 242 assert(Tok.is(tok::kw___declspec) && "Not a declspec!"); 243 244 ConsumeToken(); 245 if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after, 246 "declspec")) { 247 SkipUntil(tok::r_paren, true); // skip until ) or ; 248 return CurrAttr; 249 } 250 while (Tok.getIdentifierInfo()) { 251 IdentifierInfo *AttrName = Tok.getIdentifierInfo(); 252 SourceLocation AttrNameLoc = ConsumeToken(); 253 if (Tok.is(tok::l_paren)) { 254 ConsumeParen(); 255 // FIXME: This doesn't parse __declspec(property(get=get_func_name)) 256 // correctly. 257 OwningExprResult ArgExpr(ParseAssignmentExpression()); 258 if (!ArgExpr.isInvalid()) { 259 ExprTy* ExprList = ArgExpr.take(); 260 CurrAttr = new AttributeList(AttrName, AttrNameLoc, 0, AttrNameLoc, 0, 261 SourceLocation(), &ExprList, 1, 262 CurrAttr, true); 263 } 264 if (ExpectAndConsume(tok::r_paren, diag::err_expected_rparen)) 265 SkipUntil(tok::r_paren, false); 266 } else { 267 CurrAttr = new AttributeList(AttrName, AttrNameLoc, 0, AttrNameLoc, 268 0, SourceLocation(), 0, 0, CurrAttr, true); 269 } 270 } 271 if (ExpectAndConsume(tok::r_paren, diag::err_expected_rparen)) 272 SkipUntil(tok::r_paren, false); 273 return CurrAttr; 274} 275 276AttributeList* Parser::ParseMicrosoftTypeAttributes(AttributeList *CurrAttr) { 277 // Treat these like attributes 278 // FIXME: Allow Sema to distinguish between these and real attributes! 279 while (Tok.is(tok::kw___fastcall) || Tok.is(tok::kw___stdcall) || 280 Tok.is(tok::kw___cdecl) || Tok.is(tok::kw___ptr64) || 281 Tok.is(tok::kw___w64)) { 282 IdentifierInfo *AttrName = Tok.getIdentifierInfo(); 283 SourceLocation AttrNameLoc = ConsumeToken(); 284 if (Tok.is(tok::kw___ptr64) || Tok.is(tok::kw___w64)) 285 // FIXME: Support these properly! 286 continue; 287 CurrAttr = new AttributeList(AttrName, AttrNameLoc, 0, AttrNameLoc, 0, 288 SourceLocation(), 0, 0, CurrAttr, true); 289 } 290 return CurrAttr; 291} 292 293/// ParseDeclaration - Parse a full 'declaration', which consists of 294/// declaration-specifiers, some number of declarators, and a semicolon. 295/// 'Context' should be a Declarator::TheContext value. This returns the 296/// location of the semicolon in DeclEnd. 297/// 298/// declaration: [C99 6.7] 299/// block-declaration -> 300/// simple-declaration 301/// others [FIXME] 302/// [C++] template-declaration 303/// [C++] namespace-definition 304/// [C++] using-directive 305/// [C++] using-declaration 306/// [C++0x] static_assert-declaration 307/// others... [FIXME] 308/// 309Parser::DeclGroupPtrTy Parser::ParseDeclaration(unsigned Context, 310 SourceLocation &DeclEnd, 311 CXX0XAttributeList Attr) { 312 DeclPtrTy SingleDecl; 313 switch (Tok.getKind()) { 314 case tok::kw_template: 315 case tok::kw_export: 316 if (Attr.HasAttr) 317 Diag(Attr.Range.getBegin(), diag::err_attributes_not_allowed) 318 << Attr.Range; 319 SingleDecl = ParseDeclarationStartingWithTemplate(Context, DeclEnd); 320 break; 321 case tok::kw_namespace: 322 if (Attr.HasAttr) 323 Diag(Attr.Range.getBegin(), diag::err_attributes_not_allowed) 324 << Attr.Range; 325 SingleDecl = ParseNamespace(Context, DeclEnd); 326 break; 327 case tok::kw_using: 328 SingleDecl = ParseUsingDirectiveOrDeclaration(Context, DeclEnd, Attr); 329 break; 330 case tok::kw_static_assert: 331 if (Attr.HasAttr) 332 Diag(Attr.Range.getBegin(), diag::err_attributes_not_allowed) 333 << Attr.Range; 334 SingleDecl = ParseStaticAssertDeclaration(DeclEnd); 335 break; 336 default: 337 return ParseSimpleDeclaration(Context, DeclEnd, Attr.AttrList); 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. 352Parser::DeclGroupPtrTy Parser::ParseSimpleDeclaration(unsigned Context, 353 SourceLocation &DeclEnd, 354 AttributeList *Attr) { 355 // Parse the common declaration-specifiers piece. 356 ParsingDeclSpec DS(*this); 357 if (Attr) 358 DS.AddAttributes(Attr); 359 ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS_none, 360 getDeclSpecContextFromDeclaratorContext(Context)); 361 362 // C99 6.7.2.3p6: Handle "struct-or-union identifier;", "enum { X };" 363 // declaration-specifiers init-declarator-list[opt] ';' 364 if (Tok.is(tok::semi)) { 365 ConsumeToken(); 366 DeclPtrTy TheDecl = Actions.ParsedFreeStandingDeclSpec(CurScope, DS); 367 DS.complete(TheDecl); 368 return Actions.ConvertDeclToDeclGroup(TheDecl); 369 } 370 371 DeclGroupPtrTy DG = ParseDeclGroup(DS, Context, /*FunctionDefs=*/ false, 372 &DeclEnd); 373 return DG; 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::semi, true, true); 568 return DeclPtrTy(); 569 } 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 737 << CodeModificationHint::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, 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 // Annotate C++ scope specifiers. If we get one, loop. 863 if (TryAnnotateCXXScopeToken(true)) 864 continue; 865 goto DoneWithDeclSpec; 866 867 case tok::annot_cxxscope: { 868 if (DS.hasTypeSpecifier()) 869 goto DoneWithDeclSpec; 870 871 CXXScopeSpec SS; 872 SS.setScopeRep(Tok.getAnnotationValue()); 873 SS.setRange(Tok.getAnnotationRange()); 874 875 // We are looking for a qualified typename. 876 Token Next = NextToken(); 877 if (Next.is(tok::annot_template_id) && 878 static_cast<TemplateIdAnnotation *>(Next.getAnnotationValue()) 879 ->Kind == TNK_Type_template) { 880 // We have a qualified template-id, e.g., N::A<int> 881 882 // C++ [class.qual]p2: 883 // In a lookup in which the constructor is an acceptable lookup 884 // result and the nested-name-specifier nominates a class C: 885 // 886 // - if the name specified after the 887 // nested-name-specifier, when looked up in C, is the 888 // injected-class-name of C (Clause 9), or 889 // 890 // - if the name specified after the nested-name-specifier 891 // is the same as the identifier or the 892 // simple-template-id's template-name in the last 893 // component of the nested-name-specifier, 894 // 895 // the name is instead considered to name the constructor of 896 // class C. 897 // 898 // Thus, if the template-name is actually the constructor 899 // name, then the code is ill-formed; this interpretation is 900 // reinforced by the NAD status of core issue 635. 901 TemplateIdAnnotation *TemplateId 902 = static_cast<TemplateIdAnnotation *>(Next.getAnnotationValue()); 903 if (DSContext == DSC_top_level && TemplateId->Name && 904 Actions.isCurrentClassName(*TemplateId->Name, CurScope, &SS)) { 905 if (isConstructorDeclarator()) { 906 // The user meant this to be an out-of-line constructor 907 // definition, but template arguments are not allowed 908 // there. Just allow this as a constructor; we'll 909 // complain about it later. 910 goto DoneWithDeclSpec; 911 } 912 913 // The user meant this to name a type, but it actually names 914 // a constructor with some extraneous template 915 // arguments. Complain, then parse it as a type as the user 916 // intended. 917 Diag(TemplateId->TemplateNameLoc, 918 diag::err_out_of_line_template_id_names_constructor) 919 << TemplateId->Name; 920 } 921 922 DS.getTypeSpecScope() = SS; 923 ConsumeToken(); // The C++ scope. 924 assert(Tok.is(tok::annot_template_id) && 925 "ParseOptionalCXXScopeSpecifier not working"); 926 AnnotateTemplateIdTokenAsType(&SS); 927 continue; 928 } 929 930 if (Next.is(tok::annot_typename)) { 931 DS.getTypeSpecScope() = SS; 932 ConsumeToken(); // The C++ scope. 933 if (Tok.getAnnotationValue()) 934 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, 935 PrevSpec, DiagID, 936 Tok.getAnnotationValue()); 937 else 938 DS.SetTypeSpecError(); 939 DS.SetRangeEnd(Tok.getAnnotationEndLoc()); 940 ConsumeToken(); // The typename 941 } 942 943 if (Next.isNot(tok::identifier)) 944 goto DoneWithDeclSpec; 945 946 // If we're in a context where the identifier could be a class name, 947 // check whether this is a constructor declaration. 948 if (DSContext == DSC_top_level && 949 Actions.isCurrentClassName(*Next.getIdentifierInfo(), CurScope, 950 &SS)) { 951 if (isConstructorDeclarator()) 952 goto DoneWithDeclSpec; 953 954 // As noted in C++ [class.qual]p2 (cited above), when the name 955 // of the class is qualified in a context where it could name 956 // a constructor, its a constructor name. However, we've 957 // looked at the declarator, and the user probably meant this 958 // to be a type. Complain that it isn't supposed to be treated 959 // as a type, then proceed to parse it as a type. 960 Diag(Next.getLocation(), diag::err_out_of_line_type_names_constructor) 961 << Next.getIdentifierInfo(); 962 } 963 964 TypeTy *TypeRep = Actions.getTypeName(*Next.getIdentifierInfo(), 965 Next.getLocation(), CurScope, &SS); 966 967 // If the referenced identifier is not a type, then this declspec is 968 // erroneous: We already checked about that it has no type specifier, and 969 // C++ doesn't have implicit int. Diagnose it as a typo w.r.t. to the 970 // typename. 971 if (TypeRep == 0) { 972 ConsumeToken(); // Eat the scope spec so the identifier is current. 973 if (ParseImplicitInt(DS, &SS, TemplateInfo, AS)) continue; 974 goto DoneWithDeclSpec; 975 } 976 977 DS.getTypeSpecScope() = SS; 978 ConsumeToken(); // The C++ scope. 979 980 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, 981 DiagID, TypeRep); 982 if (isInvalid) 983 break; 984 985 DS.SetRangeEnd(Tok.getLocation()); 986 ConsumeToken(); // The typename. 987 988 continue; 989 } 990 991 case tok::annot_typename: { 992 if (Tok.getAnnotationValue()) 993 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, 994 DiagID, Tok.getAnnotationValue()); 995 else 996 DS.SetTypeSpecError(); 997 DS.SetRangeEnd(Tok.getAnnotationEndLoc()); 998 ConsumeToken(); // The typename 999 1000 // Objective-C supports syntax of the form 'id<proto1,proto2>' where 'id' 1001 // is a specific typedef and 'itf<proto1,proto2>' where 'itf' is an 1002 // Objective-C interface. If we don't have Objective-C or a '<', this is 1003 // just a normal reference to a typedef name. 1004 if (!Tok.is(tok::less) || !getLang().ObjC1) 1005 continue; 1006 1007 SourceLocation LAngleLoc, EndProtoLoc; 1008 llvm::SmallVector<DeclPtrTy, 8> ProtocolDecl; 1009 llvm::SmallVector<SourceLocation, 8> ProtocolLocs; 1010 ParseObjCProtocolReferences(ProtocolDecl, ProtocolLocs, false, 1011 LAngleLoc, EndProtoLoc); 1012 DS.setProtocolQualifiers(ProtocolDecl.data(), ProtocolDecl.size(), 1013 ProtocolLocs.data(), LAngleLoc); 1014 1015 DS.SetRangeEnd(EndProtoLoc); 1016 continue; 1017 } 1018 1019 // typedef-name 1020 case tok::identifier: { 1021 // In C++, check to see if this is a scope specifier like foo::bar::, if 1022 // so handle it as such. This is important for ctor parsing. 1023 if (getLang().CPlusPlus && TryAnnotateCXXScopeToken(true)) 1024 continue; 1025 1026 // This identifier can only be a typedef name if we haven't already seen 1027 // a type-specifier. Without this check we misparse: 1028 // typedef int X; struct Y { short X; }; as 'short int'. 1029 if (DS.hasTypeSpecifier()) 1030 goto DoneWithDeclSpec; 1031 1032 // It has to be available as a typedef too! 1033 TypeTy *TypeRep = Actions.getTypeName(*Tok.getIdentifierInfo(), 1034 Tok.getLocation(), CurScope); 1035 1036 // If this is not a typedef name, don't parse it as part of the declspec, 1037 // it must be an implicit int or an error. 1038 if (TypeRep == 0) { 1039 if (ParseImplicitInt(DS, 0, TemplateInfo, AS)) continue; 1040 goto DoneWithDeclSpec; 1041 } 1042 1043 // If we're in a context where the identifier could be a class name, 1044 // check whether this is a constructor declaration. 1045 if (getLang().CPlusPlus && DSContext == DSC_class && 1046 Actions.isCurrentClassName(*Tok.getIdentifierInfo(), CurScope) && 1047 isConstructorDeclarator()) 1048 goto DoneWithDeclSpec; 1049 1050 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, 1051 DiagID, TypeRep); 1052 if (isInvalid) 1053 break; 1054 1055 DS.SetRangeEnd(Tok.getLocation()); 1056 ConsumeToken(); // The identifier 1057 1058 // Objective-C supports syntax of the form 'id<proto1,proto2>' where 'id' 1059 // is a specific typedef and 'itf<proto1,proto2>' where 'itf' is an 1060 // Objective-C interface. If we don't have Objective-C or a '<', this is 1061 // just a normal reference to a typedef name. 1062 if (!Tok.is(tok::less) || !getLang().ObjC1) 1063 continue; 1064 1065 SourceLocation LAngleLoc, EndProtoLoc; 1066 llvm::SmallVector<DeclPtrTy, 8> ProtocolDecl; 1067 llvm::SmallVector<SourceLocation, 8> ProtocolLocs; 1068 ParseObjCProtocolReferences(ProtocolDecl, ProtocolLocs, false, 1069 LAngleLoc, EndProtoLoc); 1070 DS.setProtocolQualifiers(ProtocolDecl.data(), ProtocolDecl.size(), 1071 ProtocolLocs.data(), LAngleLoc); 1072 1073 DS.SetRangeEnd(EndProtoLoc); 1074 1075 // Need to support trailing type qualifiers (e.g. "id<p> const"). 1076 // If a type specifier follows, it will be diagnosed elsewhere. 1077 continue; 1078 } 1079 1080 // type-name 1081 case tok::annot_template_id: { 1082 TemplateIdAnnotation *TemplateId 1083 = static_cast<TemplateIdAnnotation *>(Tok.getAnnotationValue()); 1084 if (TemplateId->Kind != TNK_Type_template) { 1085 // This template-id does not refer to a type name, so we're 1086 // done with the type-specifiers. 1087 goto DoneWithDeclSpec; 1088 } 1089 1090 // If we're in a context where the template-id could be a 1091 // constructor name or specialization, check whether this is a 1092 // constructor declaration. 1093 if (getLang().CPlusPlus && DSContext == DSC_class && 1094 Actions.isCurrentClassName(*TemplateId->Name, CurScope) && 1095 isConstructorDeclarator()) 1096 goto DoneWithDeclSpec; 1097 1098 // Turn the template-id annotation token into a type annotation 1099 // token, then try again to parse it as a type-specifier. 1100 AnnotateTemplateIdTokenAsType(); 1101 continue; 1102 } 1103 1104 // GNU attributes support. 1105 case tok::kw___attribute: 1106 DS.AddAttributes(ParseGNUAttributes()); 1107 continue; 1108 1109 // Microsoft declspec support. 1110 case tok::kw___declspec: 1111 DS.AddAttributes(ParseMicrosoftDeclSpec()); 1112 continue; 1113 1114 // Microsoft single token adornments. 1115 case tok::kw___forceinline: 1116 // FIXME: Add handling here! 1117 break; 1118 1119 case tok::kw___ptr64: 1120 case tok::kw___w64: 1121 case tok::kw___cdecl: 1122 case tok::kw___stdcall: 1123 case tok::kw___fastcall: 1124 DS.AddAttributes(ParseMicrosoftTypeAttributes()); 1125 continue; 1126 1127 // storage-class-specifier 1128 case tok::kw_typedef: 1129 isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_typedef, Loc, PrevSpec, 1130 DiagID); 1131 break; 1132 case tok::kw_extern: 1133 if (DS.isThreadSpecified()) 1134 Diag(Tok, diag::ext_thread_before) << "extern"; 1135 isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_extern, Loc, PrevSpec, 1136 DiagID); 1137 break; 1138 case tok::kw___private_extern__: 1139 isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_private_extern, Loc, 1140 PrevSpec, DiagID); 1141 break; 1142 case tok::kw_static: 1143 if (DS.isThreadSpecified()) 1144 Diag(Tok, diag::ext_thread_before) << "static"; 1145 isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_static, Loc, PrevSpec, 1146 DiagID); 1147 break; 1148 case tok::kw_auto: 1149 if (getLang().CPlusPlus0x) 1150 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_auto, Loc, PrevSpec, 1151 DiagID); 1152 else 1153 isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_auto, Loc, PrevSpec, 1154 DiagID); 1155 break; 1156 case tok::kw_register: 1157 isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_register, Loc, PrevSpec, 1158 DiagID); 1159 break; 1160 case tok::kw_mutable: 1161 isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_mutable, Loc, PrevSpec, 1162 DiagID); 1163 break; 1164 case tok::kw___thread: 1165 isInvalid = DS.SetStorageClassSpecThread(Loc, PrevSpec, DiagID); 1166 break; 1167 1168 // function-specifier 1169 case tok::kw_inline: 1170 isInvalid = DS.SetFunctionSpecInline(Loc, PrevSpec, DiagID); 1171 break; 1172 case tok::kw_virtual: 1173 isInvalid = DS.SetFunctionSpecVirtual(Loc, PrevSpec, DiagID); 1174 break; 1175 case tok::kw_explicit: 1176 isInvalid = DS.SetFunctionSpecExplicit(Loc, PrevSpec, DiagID); 1177 break; 1178 1179 // friend 1180 case tok::kw_friend: 1181 if (DSContext == DSC_class) 1182 isInvalid = DS.SetFriendSpec(Loc, PrevSpec, DiagID); 1183 else { 1184 PrevSpec = ""; // not actually used by the diagnostic 1185 DiagID = diag::err_friend_invalid_in_context; 1186 isInvalid = true; 1187 } 1188 break; 1189 1190 // constexpr 1191 case tok::kw_constexpr: 1192 isInvalid = DS.SetConstexprSpec(Loc, PrevSpec, DiagID); 1193 break; 1194 1195 // type-specifier 1196 case tok::kw_short: 1197 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_short, Loc, PrevSpec, 1198 DiagID); 1199 break; 1200 case tok::kw_long: 1201 if (DS.getTypeSpecWidth() != DeclSpec::TSW_long) 1202 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_long, Loc, PrevSpec, 1203 DiagID); 1204 else 1205 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec, 1206 DiagID); 1207 break; 1208 case tok::kw_signed: 1209 isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_signed, Loc, PrevSpec, 1210 DiagID); 1211 break; 1212 case tok::kw_unsigned: 1213 isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_unsigned, Loc, PrevSpec, 1214 DiagID); 1215 break; 1216 case tok::kw__Complex: 1217 isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_complex, Loc, PrevSpec, 1218 DiagID); 1219 break; 1220 case tok::kw__Imaginary: 1221 isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_imaginary, Loc, PrevSpec, 1222 DiagID); 1223 break; 1224 case tok::kw_void: 1225 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec, 1226 DiagID); 1227 break; 1228 case tok::kw_char: 1229 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec, 1230 DiagID); 1231 break; 1232 case tok::kw_int: 1233 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec, 1234 DiagID); 1235 break; 1236 case tok::kw_float: 1237 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec, 1238 DiagID); 1239 break; 1240 case tok::kw_double: 1241 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec, 1242 DiagID); 1243 break; 1244 case tok::kw_wchar_t: 1245 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec, 1246 DiagID); 1247 break; 1248 case tok::kw_char16_t: 1249 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char16, Loc, PrevSpec, 1250 DiagID); 1251 break; 1252 case tok::kw_char32_t: 1253 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char32, Loc, PrevSpec, 1254 DiagID); 1255 break; 1256 case tok::kw_bool: 1257 case tok::kw__Bool: 1258 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec, 1259 DiagID); 1260 break; 1261 case tok::kw__Decimal32: 1262 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal32, Loc, PrevSpec, 1263 DiagID); 1264 break; 1265 case tok::kw__Decimal64: 1266 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal64, Loc, PrevSpec, 1267 DiagID); 1268 break; 1269 case tok::kw__Decimal128: 1270 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal128, Loc, PrevSpec, 1271 DiagID); 1272 break; 1273 1274 // class-specifier: 1275 case tok::kw_class: 1276 case tok::kw_struct: 1277 case tok::kw_union: { 1278 tok::TokenKind Kind = Tok.getKind(); 1279 ConsumeToken(); 1280 ParseClassSpecifier(Kind, Loc, DS, TemplateInfo, AS); 1281 continue; 1282 } 1283 1284 // enum-specifier: 1285 case tok::kw_enum: 1286 ConsumeToken(); 1287 ParseEnumSpecifier(Loc, DS, AS); 1288 continue; 1289 1290 // cv-qualifier: 1291 case tok::kw_const: 1292 isInvalid = DS.SetTypeQual(DeclSpec::TQ_const, Loc, PrevSpec, DiagID, 1293 getLang()); 1294 break; 1295 case tok::kw_volatile: 1296 isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, DiagID, 1297 getLang()); 1298 break; 1299 case tok::kw_restrict: 1300 isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, DiagID, 1301 getLang()); 1302 break; 1303 1304 // C++ typename-specifier: 1305 case tok::kw_typename: 1306 if (TryAnnotateTypeOrScopeToken()) 1307 continue; 1308 break; 1309 1310 // GNU typeof support. 1311 case tok::kw_typeof: 1312 ParseTypeofSpecifier(DS); 1313 continue; 1314 1315 case tok::kw_decltype: 1316 ParseDecltypeSpecifier(DS); 1317 continue; 1318 1319 case tok::less: 1320 // GCC ObjC supports types like "<SomeProtocol>" as a synonym for 1321 // "id<SomeProtocol>". This is hopelessly old fashioned and dangerous, 1322 // but we support it. 1323 if (DS.hasTypeSpecifier() || !getLang().ObjC1) 1324 goto DoneWithDeclSpec; 1325 1326 { 1327 SourceLocation LAngleLoc, EndProtoLoc; 1328 llvm::SmallVector<DeclPtrTy, 8> ProtocolDecl; 1329 llvm::SmallVector<SourceLocation, 8> ProtocolLocs; 1330 ParseObjCProtocolReferences(ProtocolDecl, ProtocolLocs, false, 1331 LAngleLoc, EndProtoLoc); 1332 DS.setProtocolQualifiers(ProtocolDecl.data(), ProtocolDecl.size(), 1333 ProtocolLocs.data(), LAngleLoc); 1334 DS.SetRangeEnd(EndProtoLoc); 1335 1336 Diag(Loc, diag::warn_objc_protocol_qualifier_missing_id) 1337 << CodeModificationHint::CreateInsertion(Loc, "id") 1338 << SourceRange(Loc, EndProtoLoc); 1339 // Need to support trailing type qualifiers (e.g. "id<p> const"). 1340 // If a type specifier follows, it will be diagnosed elsewhere. 1341 continue; 1342 } 1343 } 1344 // If the specifier wasn't legal, issue a diagnostic. 1345 if (isInvalid) { 1346 assert(PrevSpec && "Method did not return previous specifier!"); 1347 assert(DiagID); 1348 Diag(Tok, DiagID) << PrevSpec; 1349 } 1350 DS.SetRangeEnd(Tok.getLocation()); 1351 ConsumeToken(); 1352 } 1353} 1354 1355/// ParseOptionalTypeSpecifier - Try to parse a single type-specifier. We 1356/// primarily follow the C++ grammar with additions for C99 and GNU, 1357/// which together subsume the C grammar. Note that the C++ 1358/// type-specifier also includes the C type-qualifier (for const, 1359/// volatile, and C99 restrict). Returns true if a type-specifier was 1360/// found (and parsed), false otherwise. 1361/// 1362/// type-specifier: [C++ 7.1.5] 1363/// simple-type-specifier 1364/// class-specifier 1365/// enum-specifier 1366/// elaborated-type-specifier [TODO] 1367/// cv-qualifier 1368/// 1369/// cv-qualifier: [C++ 7.1.5.1] 1370/// 'const' 1371/// 'volatile' 1372/// [C99] 'restrict' 1373/// 1374/// simple-type-specifier: [ C++ 7.1.5.2] 1375/// '::'[opt] nested-name-specifier[opt] type-name [TODO] 1376/// '::'[opt] nested-name-specifier 'template' template-id [TODO] 1377/// 'char' 1378/// 'wchar_t' 1379/// 'bool' 1380/// 'short' 1381/// 'int' 1382/// 'long' 1383/// 'signed' 1384/// 'unsigned' 1385/// 'float' 1386/// 'double' 1387/// 'void' 1388/// [C99] '_Bool' 1389/// [C99] '_Complex' 1390/// [C99] '_Imaginary' // Removed in TC2? 1391/// [GNU] '_Decimal32' 1392/// [GNU] '_Decimal64' 1393/// [GNU] '_Decimal128' 1394/// [GNU] typeof-specifier 1395/// [OBJC] class-name objc-protocol-refs[opt] [TODO] 1396/// [OBJC] typedef-name objc-protocol-refs[opt] [TODO] 1397/// [C++0x] 'decltype' ( expression ) 1398bool Parser::ParseOptionalTypeSpecifier(DeclSpec &DS, bool& isInvalid, 1399 const char *&PrevSpec, 1400 unsigned &DiagID, 1401 const ParsedTemplateInfo &TemplateInfo, 1402 bool SuppressDeclarations) { 1403 SourceLocation Loc = Tok.getLocation(); 1404 1405 switch (Tok.getKind()) { 1406 case tok::identifier: // foo::bar 1407 case tok::kw_typename: // typename foo::bar 1408 // Annotate typenames and C++ scope specifiers. If we get one, just 1409 // recurse to handle whatever we get. 1410 if (TryAnnotateTypeOrScopeToken()) 1411 return ParseOptionalTypeSpecifier(DS, isInvalid, PrevSpec, DiagID, 1412 TemplateInfo, SuppressDeclarations); 1413 // Otherwise, not a type specifier. 1414 return false; 1415 case tok::coloncolon: // ::foo::bar 1416 if (NextToken().is(tok::kw_new) || // ::new 1417 NextToken().is(tok::kw_delete)) // ::delete 1418 return false; 1419 1420 // Annotate typenames and C++ scope specifiers. If we get one, just 1421 // recurse to handle whatever we get. 1422 if (TryAnnotateTypeOrScopeToken()) 1423 return ParseOptionalTypeSpecifier(DS, isInvalid, PrevSpec, DiagID, 1424 TemplateInfo, SuppressDeclarations); 1425 // Otherwise, not a type specifier. 1426 return false; 1427 1428 // simple-type-specifier: 1429 case tok::annot_typename: { 1430 if (Tok.getAnnotationValue()) 1431 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, 1432 DiagID, Tok.getAnnotationValue()); 1433 else 1434 DS.SetTypeSpecError(); 1435 DS.SetRangeEnd(Tok.getAnnotationEndLoc()); 1436 ConsumeToken(); // The typename 1437 1438 // Objective-C supports syntax of the form 'id<proto1,proto2>' where 'id' 1439 // is a specific typedef and 'itf<proto1,proto2>' where 'itf' is an 1440 // Objective-C interface. If we don't have Objective-C or a '<', this is 1441 // just a normal reference to a typedef name. 1442 if (!Tok.is(tok::less) || !getLang().ObjC1) 1443 return true; 1444 1445 SourceLocation LAngleLoc, EndProtoLoc; 1446 llvm::SmallVector<DeclPtrTy, 8> ProtocolDecl; 1447 llvm::SmallVector<SourceLocation, 8> ProtocolLocs; 1448 ParseObjCProtocolReferences(ProtocolDecl, ProtocolLocs, false, 1449 LAngleLoc, EndProtoLoc); 1450 DS.setProtocolQualifiers(ProtocolDecl.data(), ProtocolDecl.size(), 1451 ProtocolLocs.data(), LAngleLoc); 1452 1453 DS.SetRangeEnd(EndProtoLoc); 1454 return true; 1455 } 1456 1457 case tok::kw_short: 1458 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_short, Loc, PrevSpec, DiagID); 1459 break; 1460 case tok::kw_long: 1461 if (DS.getTypeSpecWidth() != DeclSpec::TSW_long) 1462 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_long, Loc, PrevSpec, 1463 DiagID); 1464 else 1465 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec, 1466 DiagID); 1467 break; 1468 case tok::kw_signed: 1469 isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_signed, Loc, PrevSpec, DiagID); 1470 break; 1471 case tok::kw_unsigned: 1472 isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_unsigned, Loc, PrevSpec, 1473 DiagID); 1474 break; 1475 case tok::kw__Complex: 1476 isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_complex, Loc, PrevSpec, 1477 DiagID); 1478 break; 1479 case tok::kw__Imaginary: 1480 isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_imaginary, Loc, PrevSpec, 1481 DiagID); 1482 break; 1483 case tok::kw_void: 1484 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec, DiagID); 1485 break; 1486 case tok::kw_char: 1487 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec, DiagID); 1488 break; 1489 case tok::kw_int: 1490 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec, DiagID); 1491 break; 1492 case tok::kw_float: 1493 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec, DiagID); 1494 break; 1495 case tok::kw_double: 1496 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec, DiagID); 1497 break; 1498 case tok::kw_wchar_t: 1499 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec, DiagID); 1500 break; 1501 case tok::kw_char16_t: 1502 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char16, Loc, PrevSpec, DiagID); 1503 break; 1504 case tok::kw_char32_t: 1505 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char32, Loc, PrevSpec, DiagID); 1506 break; 1507 case tok::kw_bool: 1508 case tok::kw__Bool: 1509 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec, DiagID); 1510 break; 1511 case tok::kw__Decimal32: 1512 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal32, Loc, PrevSpec, 1513 DiagID); 1514 break; 1515 case tok::kw__Decimal64: 1516 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal64, Loc, PrevSpec, 1517 DiagID); 1518 break; 1519 case tok::kw__Decimal128: 1520 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal128, Loc, PrevSpec, 1521 DiagID); 1522 break; 1523 1524 // class-specifier: 1525 case tok::kw_class: 1526 case tok::kw_struct: 1527 case tok::kw_union: { 1528 tok::TokenKind Kind = Tok.getKind(); 1529 ConsumeToken(); 1530 ParseClassSpecifier(Kind, Loc, DS, TemplateInfo, AS_none, 1531 SuppressDeclarations); 1532 return true; 1533 } 1534 1535 // enum-specifier: 1536 case tok::kw_enum: 1537 ConsumeToken(); 1538 ParseEnumSpecifier(Loc, DS); 1539 return true; 1540 1541 // cv-qualifier: 1542 case tok::kw_const: 1543 isInvalid = DS.SetTypeQual(DeclSpec::TQ_const , Loc, PrevSpec, 1544 DiagID, getLang()); 1545 break; 1546 case tok::kw_volatile: 1547 isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, 1548 DiagID, getLang()); 1549 break; 1550 case tok::kw_restrict: 1551 isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, 1552 DiagID, getLang()); 1553 break; 1554 1555 // GNU typeof support. 1556 case tok::kw_typeof: 1557 ParseTypeofSpecifier(DS); 1558 return true; 1559 1560 // C++0x decltype support. 1561 case tok::kw_decltype: 1562 ParseDecltypeSpecifier(DS); 1563 return true; 1564 1565 // C++0x auto support. 1566 case tok::kw_auto: 1567 if (!getLang().CPlusPlus0x) 1568 return false; 1569 1570 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_auto, Loc, PrevSpec, DiagID); 1571 break; 1572 case tok::kw___ptr64: 1573 case tok::kw___w64: 1574 case tok::kw___cdecl: 1575 case tok::kw___stdcall: 1576 case tok::kw___fastcall: 1577 DS.AddAttributes(ParseMicrosoftTypeAttributes()); 1578 return true; 1579 1580 default: 1581 // Not a type-specifier; do nothing. 1582 return false; 1583 } 1584 1585 // If the specifier combination wasn't legal, issue a diagnostic. 1586 if (isInvalid) { 1587 assert(PrevSpec && "Method did not return previous specifier!"); 1588 // Pick between error or extwarn. 1589 Diag(Tok, DiagID) << PrevSpec; 1590 } 1591 DS.SetRangeEnd(Tok.getLocation()); 1592 ConsumeToken(); // whatever we parsed above. 1593 return true; 1594} 1595 1596/// ParseStructDeclaration - Parse a struct declaration without the terminating 1597/// semicolon. 1598/// 1599/// struct-declaration: 1600/// specifier-qualifier-list struct-declarator-list 1601/// [GNU] __extension__ struct-declaration 1602/// [GNU] specifier-qualifier-list 1603/// struct-declarator-list: 1604/// struct-declarator 1605/// struct-declarator-list ',' struct-declarator 1606/// [GNU] struct-declarator-list ',' attributes[opt] struct-declarator 1607/// struct-declarator: 1608/// declarator 1609/// [GNU] declarator attributes[opt] 1610/// declarator[opt] ':' constant-expression 1611/// [GNU] declarator[opt] ':' constant-expression attributes[opt] 1612/// 1613void Parser:: 1614ParseStructDeclaration(DeclSpec &DS, FieldCallback &Fields) { 1615 if (Tok.is(tok::kw___extension__)) { 1616 // __extension__ silences extension warnings in the subexpression. 1617 ExtensionRAIIObject O(Diags); // Use RAII to do this. 1618 ConsumeToken(); 1619 return ParseStructDeclaration(DS, Fields); 1620 } 1621 1622 // Parse the common specifier-qualifiers-list piece. 1623 SourceLocation DSStart = Tok.getLocation(); 1624 ParseSpecifierQualifierList(DS); 1625 1626 // If there are no declarators, this is a free-standing declaration 1627 // specifier. Let the actions module cope with it. 1628 if (Tok.is(tok::semi)) { 1629 Actions.ParsedFreeStandingDeclSpec(CurScope, DS); 1630 return; 1631 } 1632 1633 // Read struct-declarators until we find the semicolon. 1634 bool FirstDeclarator = true; 1635 while (1) { 1636 ParsingDeclRAIIObject PD(*this); 1637 FieldDeclarator DeclaratorInfo(DS); 1638 1639 // Attributes are only allowed here on successive declarators. 1640 if (!FirstDeclarator && Tok.is(tok::kw___attribute)) { 1641 SourceLocation Loc; 1642 AttributeList *AttrList = ParseGNUAttributes(&Loc); 1643 DeclaratorInfo.D.AddAttributes(AttrList, Loc); 1644 } 1645 1646 /// struct-declarator: declarator 1647 /// struct-declarator: declarator[opt] ':' constant-expression 1648 if (Tok.isNot(tok::colon)) { 1649 // Don't parse FOO:BAR as if it were a typo for FOO::BAR. 1650 ColonProtectionRAIIObject X(*this); 1651 ParseDeclarator(DeclaratorInfo.D); 1652 } 1653 1654 if (Tok.is(tok::colon)) { 1655 ConsumeToken(); 1656 OwningExprResult Res(ParseConstantExpression()); 1657 if (Res.isInvalid()) 1658 SkipUntil(tok::semi, true, true); 1659 else 1660 DeclaratorInfo.BitfieldSize = Res.release(); 1661 } 1662 1663 // If attributes exist after the declarator, parse them. 1664 if (Tok.is(tok::kw___attribute)) { 1665 SourceLocation Loc; 1666 AttributeList *AttrList = ParseGNUAttributes(&Loc); 1667 DeclaratorInfo.D.AddAttributes(AttrList, Loc); 1668 } 1669 1670 // We're done with this declarator; invoke the callback. 1671 DeclPtrTy D = Fields.invoke(DeclaratorInfo); 1672 PD.complete(D); 1673 1674 // If we don't have a comma, it is either the end of the list (a ';') 1675 // or an error, bail out. 1676 if (Tok.isNot(tok::comma)) 1677 return; 1678 1679 // Consume the comma. 1680 ConsumeToken(); 1681 1682 FirstDeclarator = false; 1683 } 1684} 1685 1686/// ParseStructUnionBody 1687/// struct-contents: 1688/// struct-declaration-list 1689/// [EXT] empty 1690/// [GNU] "struct-declaration-list" without terminatoring ';' 1691/// struct-declaration-list: 1692/// struct-declaration 1693/// struct-declaration-list struct-declaration 1694/// [OBC] '@' 'defs' '(' class-name ')' 1695/// 1696void Parser::ParseStructUnionBody(SourceLocation RecordLoc, 1697 unsigned TagType, DeclPtrTy TagDecl) { 1698 PrettyStackTraceActionsDecl CrashInfo(TagDecl, RecordLoc, Actions, 1699 PP.getSourceManager(), 1700 "parsing struct/union body"); 1701 1702 SourceLocation LBraceLoc = ConsumeBrace(); 1703 1704 ParseScope StructScope(this, Scope::ClassScope|Scope::DeclScope); 1705 Actions.ActOnTagStartDefinition(CurScope, TagDecl); 1706 1707 // Empty structs are an extension in C (C99 6.7.2.1p7), but are allowed in 1708 // C++. 1709 if (Tok.is(tok::r_brace) && !getLang().CPlusPlus) 1710 Diag(Tok, diag::ext_empty_struct_union_enum) 1711 << DeclSpec::getSpecifierName((DeclSpec::TST)TagType); 1712 1713 llvm::SmallVector<DeclPtrTy, 32> FieldDecls; 1714 1715 // While we still have something to read, read the declarations in the struct. 1716 while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) { 1717 // Each iteration of this loop reads one struct-declaration. 1718 1719 // Check for extraneous top-level semicolon. 1720 if (Tok.is(tok::semi)) { 1721 Diag(Tok, diag::ext_extra_struct_semi) 1722 << CodeModificationHint::CreateRemoval(Tok.getLocation()); 1723 ConsumeToken(); 1724 continue; 1725 } 1726 1727 // Parse all the comma separated declarators. 1728 DeclSpec DS; 1729 1730 if (!Tok.is(tok::at)) { 1731 struct CFieldCallback : FieldCallback { 1732 Parser &P; 1733 DeclPtrTy TagDecl; 1734 llvm::SmallVectorImpl<DeclPtrTy> &FieldDecls; 1735 1736 CFieldCallback(Parser &P, DeclPtrTy TagDecl, 1737 llvm::SmallVectorImpl<DeclPtrTy> &FieldDecls) : 1738 P(P), TagDecl(TagDecl), FieldDecls(FieldDecls) {} 1739 1740 virtual DeclPtrTy invoke(FieldDeclarator &FD) { 1741 // Install the declarator into the current TagDecl. 1742 DeclPtrTy Field = P.Actions.ActOnField(P.CurScope, TagDecl, 1743 FD.D.getDeclSpec().getSourceRange().getBegin(), 1744 FD.D, FD.BitfieldSize); 1745 FieldDecls.push_back(Field); 1746 return Field; 1747 } 1748 } Callback(*this, TagDecl, FieldDecls); 1749 1750 ParseStructDeclaration(DS, Callback); 1751 } else { // Handle @defs 1752 ConsumeToken(); 1753 if (!Tok.isObjCAtKeyword(tok::objc_defs)) { 1754 Diag(Tok, diag::err_unexpected_at); 1755 SkipUntil(tok::semi, true); 1756 continue; 1757 } 1758 ConsumeToken(); 1759 ExpectAndConsume(tok::l_paren, diag::err_expected_lparen); 1760 if (!Tok.is(tok::identifier)) { 1761 Diag(Tok, diag::err_expected_ident); 1762 SkipUntil(tok::semi, true); 1763 continue; 1764 } 1765 llvm::SmallVector<DeclPtrTy, 16> Fields; 1766 Actions.ActOnDefs(CurScope, TagDecl, Tok.getLocation(), 1767 Tok.getIdentifierInfo(), Fields); 1768 FieldDecls.insert(FieldDecls.end(), Fields.begin(), Fields.end()); 1769 ConsumeToken(); 1770 ExpectAndConsume(tok::r_paren, diag::err_expected_rparen); 1771 } 1772 1773 if (Tok.is(tok::semi)) { 1774 ConsumeToken(); 1775 } else if (Tok.is(tok::r_brace)) { 1776 ExpectAndConsume(tok::semi, diag::ext_expected_semi_decl_list); 1777 break; 1778 } else { 1779 ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list); 1780 // Skip to end of block or statement to avoid ext-warning on extra ';'. 1781 SkipUntil(tok::r_brace, true, true); 1782 // If we stopped at a ';', eat it. 1783 if (Tok.is(tok::semi)) ConsumeToken(); 1784 } 1785 } 1786 1787 SourceLocation RBraceLoc = MatchRHSPunctuation(tok::r_brace, LBraceLoc); 1788 1789 AttributeList *AttrList = 0; 1790 // If attributes exist after struct contents, parse them. 1791 if (Tok.is(tok::kw___attribute)) 1792 AttrList = ParseGNUAttributes(); 1793 1794 Actions.ActOnFields(CurScope, 1795 RecordLoc, TagDecl, FieldDecls.data(), FieldDecls.size(), 1796 LBraceLoc, RBraceLoc, 1797 AttrList); 1798 StructScope.Exit(); 1799 Actions.ActOnTagFinishDefinition(CurScope, TagDecl, RBraceLoc); 1800} 1801 1802 1803/// ParseEnumSpecifier 1804/// enum-specifier: [C99 6.7.2.2] 1805/// 'enum' identifier[opt] '{' enumerator-list '}' 1806///[C99/C++]'enum' identifier[opt] '{' enumerator-list ',' '}' 1807/// [GNU] 'enum' attributes[opt] identifier[opt] '{' enumerator-list ',' [opt] 1808/// '}' attributes[opt] 1809/// 'enum' identifier 1810/// [GNU] 'enum' attributes[opt] identifier 1811/// 1812/// [C++] elaborated-type-specifier: 1813/// [C++] 'enum' '::'[opt] nested-name-specifier[opt] identifier 1814/// 1815void Parser::ParseEnumSpecifier(SourceLocation StartLoc, DeclSpec &DS, 1816 AccessSpecifier AS) { 1817 // Parse the tag portion of this. 1818 if (Tok.is(tok::code_completion)) { 1819 // Code completion for an enum name. 1820 Actions.CodeCompleteTag(CurScope, DeclSpec::TST_enum); 1821 ConsumeToken(); 1822 } 1823 1824 AttributeList *Attr = 0; 1825 // If attributes exist after tag, parse them. 1826 if (Tok.is(tok::kw___attribute)) 1827 Attr = ParseGNUAttributes(); 1828 1829 CXXScopeSpec SS; 1830 if (getLang().CPlusPlus && ParseOptionalCXXScopeSpecifier(SS, 0, false)) { 1831 if (Tok.isNot(tok::identifier)) { 1832 Diag(Tok, diag::err_expected_ident); 1833 if (Tok.isNot(tok::l_brace)) { 1834 // Has no name and is not a definition. 1835 // Skip the rest of this declarator, up until the comma or semicolon. 1836 SkipUntil(tok::comma, true); 1837 return; 1838 } 1839 } 1840 } 1841 1842 // Must have either 'enum name' or 'enum {...}'. 1843 if (Tok.isNot(tok::identifier) && Tok.isNot(tok::l_brace)) { 1844 Diag(Tok, diag::err_expected_ident_lbrace); 1845 1846 // Skip the rest of this declarator, up until the comma or semicolon. 1847 SkipUntil(tok::comma, true); 1848 return; 1849 } 1850 1851 // If an identifier is present, consume and remember it. 1852 IdentifierInfo *Name = 0; 1853 SourceLocation NameLoc; 1854 if (Tok.is(tok::identifier)) { 1855 Name = Tok.getIdentifierInfo(); 1856 NameLoc = ConsumeToken(); 1857 } 1858 1859 // There are three options here. If we have 'enum foo;', then this is a 1860 // forward declaration. If we have 'enum foo {...' then this is a 1861 // definition. Otherwise we have something like 'enum foo xyz', a reference. 1862 // 1863 // This is needed to handle stuff like this right (C99 6.7.2.3p11): 1864 // enum foo {..}; void bar() { enum foo; } <- new foo in bar. 1865 // enum foo {..}; void bar() { enum foo x; } <- use of old foo. 1866 // 1867 Action::TagUseKind TUK; 1868 if (Tok.is(tok::l_brace)) 1869 TUK = Action::TUK_Definition; 1870 else if (Tok.is(tok::semi)) 1871 TUK = Action::TUK_Declaration; 1872 else 1873 TUK = Action::TUK_Reference; 1874 bool Owned = false; 1875 bool IsDependent = false; 1876 DeclPtrTy TagDecl = Actions.ActOnTag(CurScope, DeclSpec::TST_enum, TUK, 1877 StartLoc, SS, Name, NameLoc, Attr, AS, 1878 Action::MultiTemplateParamsArg(Actions), 1879 Owned, IsDependent); 1880 assert(!IsDependent && "didn't expect dependent enum"); 1881 1882 if (Tok.is(tok::l_brace)) 1883 ParseEnumBody(StartLoc, TagDecl); 1884 1885 // FIXME: The DeclSpec should keep the locations of both the keyword and the 1886 // name (if there is one). 1887 SourceLocation TSTLoc = NameLoc.isValid()? NameLoc : StartLoc; 1888 const char *PrevSpec = 0; 1889 unsigned DiagID; 1890 if (DS.SetTypeSpecType(DeclSpec::TST_enum, TSTLoc, PrevSpec, DiagID, 1891 TagDecl.getAs<void>(), Owned)) 1892 Diag(StartLoc, DiagID) << PrevSpec; 1893} 1894 1895/// ParseEnumBody - Parse a {} enclosed enumerator-list. 1896/// enumerator-list: 1897/// enumerator 1898/// enumerator-list ',' enumerator 1899/// enumerator: 1900/// enumeration-constant 1901/// enumeration-constant '=' constant-expression 1902/// enumeration-constant: 1903/// identifier 1904/// 1905void Parser::ParseEnumBody(SourceLocation StartLoc, DeclPtrTy EnumDecl) { 1906 // Enter the scope of the enum body and start the definition. 1907 ParseScope EnumScope(this, Scope::DeclScope); 1908 Actions.ActOnTagStartDefinition(CurScope, EnumDecl); 1909 1910 SourceLocation LBraceLoc = ConsumeBrace(); 1911 1912 // C does not allow an empty enumerator-list, C++ does [dcl.enum]. 1913 if (Tok.is(tok::r_brace) && !getLang().CPlusPlus) 1914 Diag(Tok, diag::ext_empty_struct_union_enum) << "enum"; 1915 1916 llvm::SmallVector<DeclPtrTy, 32> EnumConstantDecls; 1917 1918 DeclPtrTy LastEnumConstDecl; 1919 1920 // Parse the enumerator-list. 1921 while (Tok.is(tok::identifier)) { 1922 IdentifierInfo *Ident = Tok.getIdentifierInfo(); 1923 SourceLocation IdentLoc = ConsumeToken(); 1924 1925 SourceLocation EqualLoc; 1926 OwningExprResult AssignedVal(Actions); 1927 if (Tok.is(tok::equal)) { 1928 EqualLoc = ConsumeToken(); 1929 AssignedVal = ParseConstantExpression(); 1930 if (AssignedVal.isInvalid()) 1931 SkipUntil(tok::comma, tok::r_brace, true, true); 1932 } 1933 1934 // Install the enumerator constant into EnumDecl. 1935 DeclPtrTy EnumConstDecl = Actions.ActOnEnumConstant(CurScope, EnumDecl, 1936 LastEnumConstDecl, 1937 IdentLoc, Ident, 1938 EqualLoc, 1939 AssignedVal.release()); 1940 EnumConstantDecls.push_back(EnumConstDecl); 1941 LastEnumConstDecl = EnumConstDecl; 1942 1943 if (Tok.isNot(tok::comma)) 1944 break; 1945 SourceLocation CommaLoc = ConsumeToken(); 1946 1947 if (Tok.isNot(tok::identifier) && 1948 !(getLang().C99 || getLang().CPlusPlus0x)) 1949 Diag(CommaLoc, diag::ext_enumerator_list_comma) 1950 << getLang().CPlusPlus 1951 << CodeModificationHint::CreateRemoval(CommaLoc); 1952 } 1953 1954 // Eat the }. 1955 SourceLocation RBraceLoc = MatchRHSPunctuation(tok::r_brace, LBraceLoc); 1956 1957 AttributeList *Attr = 0; 1958 // If attributes exist after the identifier list, parse them. 1959 if (Tok.is(tok::kw___attribute)) 1960 Attr = ParseGNUAttributes(); // FIXME: where do they do? 1961 1962 Actions.ActOnEnumBody(StartLoc, LBraceLoc, RBraceLoc, EnumDecl, 1963 EnumConstantDecls.data(), EnumConstantDecls.size(), 1964 CurScope, Attr); 1965 1966 EnumScope.Exit(); 1967 Actions.ActOnTagFinishDefinition(CurScope, EnumDecl, RBraceLoc); 1968} 1969 1970/// isTypeSpecifierQualifier - Return true if the current token could be the 1971/// start of a type-qualifier-list. 1972bool Parser::isTypeQualifier() const { 1973 switch (Tok.getKind()) { 1974 default: return false; 1975 // type-qualifier 1976 case tok::kw_const: 1977 case tok::kw_volatile: 1978 case tok::kw_restrict: 1979 return true; 1980 } 1981} 1982 1983/// isTypeSpecifierQualifier - Return true if the current token could be the 1984/// start of a specifier-qualifier-list. 1985bool Parser::isTypeSpecifierQualifier() { 1986 switch (Tok.getKind()) { 1987 default: return false; 1988 1989 case tok::identifier: // foo::bar 1990 case tok::kw_typename: // typename T::type 1991 // Annotate typenames and C++ scope specifiers. If we get one, just 1992 // recurse to handle whatever we get. 1993 if (TryAnnotateTypeOrScopeToken()) 1994 return isTypeSpecifierQualifier(); 1995 // Otherwise, not a type specifier. 1996 return false; 1997 1998 case tok::coloncolon: // ::foo::bar 1999 if (NextToken().is(tok::kw_new) || // ::new 2000 NextToken().is(tok::kw_delete)) // ::delete 2001 return false; 2002 2003 // Annotate typenames and C++ scope specifiers. If we get one, just 2004 // recurse to handle whatever we get. 2005 if (TryAnnotateTypeOrScopeToken()) 2006 return isTypeSpecifierQualifier(); 2007 // Otherwise, not a type specifier. 2008 return false; 2009 2010 // GNU attributes support. 2011 case tok::kw___attribute: 2012 // GNU typeof support. 2013 case tok::kw_typeof: 2014 2015 // type-specifiers 2016 case tok::kw_short: 2017 case tok::kw_long: 2018 case tok::kw_signed: 2019 case tok::kw_unsigned: 2020 case tok::kw__Complex: 2021 case tok::kw__Imaginary: 2022 case tok::kw_void: 2023 case tok::kw_char: 2024 case tok::kw_wchar_t: 2025 case tok::kw_char16_t: 2026 case tok::kw_char32_t: 2027 case tok::kw_int: 2028 case tok::kw_float: 2029 case tok::kw_double: 2030 case tok::kw_bool: 2031 case tok::kw__Bool: 2032 case tok::kw__Decimal32: 2033 case tok::kw__Decimal64: 2034 case tok::kw__Decimal128: 2035 2036 // struct-or-union-specifier (C99) or class-specifier (C++) 2037 case tok::kw_class: 2038 case tok::kw_struct: 2039 case tok::kw_union: 2040 // enum-specifier 2041 case tok::kw_enum: 2042 2043 // type-qualifier 2044 case tok::kw_const: 2045 case tok::kw_volatile: 2046 case tok::kw_restrict: 2047 2048 // typedef-name 2049 case tok::annot_typename: 2050 return true; 2051 2052 // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'. 2053 case tok::less: 2054 return getLang().ObjC1; 2055 2056 case tok::kw___cdecl: 2057 case tok::kw___stdcall: 2058 case tok::kw___fastcall: 2059 case tok::kw___w64: 2060 case tok::kw___ptr64: 2061 return true; 2062 } 2063} 2064 2065/// isDeclarationSpecifier() - Return true if the current token is part of a 2066/// declaration specifier. 2067bool Parser::isDeclarationSpecifier() { 2068 switch (Tok.getKind()) { 2069 default: return false; 2070 2071 case tok::identifier: // foo::bar 2072 // Unfortunate hack to support "Class.factoryMethod" notation. 2073 if (getLang().ObjC1 && NextToken().is(tok::period)) 2074 return false; 2075 // Fall through 2076 2077 case tok::kw_typename: // typename T::type 2078 // Annotate typenames and C++ scope specifiers. If we get one, just 2079 // recurse to handle whatever we get. 2080 if (TryAnnotateTypeOrScopeToken()) 2081 return isDeclarationSpecifier(); 2082 // Otherwise, not a declaration specifier. 2083 return false; 2084 case tok::coloncolon: // ::foo::bar 2085 if (NextToken().is(tok::kw_new) || // ::new 2086 NextToken().is(tok::kw_delete)) // ::delete 2087 return false; 2088 2089 // Annotate typenames and C++ scope specifiers. If we get one, just 2090 // recurse to handle whatever we get. 2091 if (TryAnnotateTypeOrScopeToken()) 2092 return isDeclarationSpecifier(); 2093 // Otherwise, not a declaration specifier. 2094 return false; 2095 2096 // storage-class-specifier 2097 case tok::kw_typedef: 2098 case tok::kw_extern: 2099 case tok::kw___private_extern__: 2100 case tok::kw_static: 2101 case tok::kw_auto: 2102 case tok::kw_register: 2103 case tok::kw___thread: 2104 2105 // type-specifiers 2106 case tok::kw_short: 2107 case tok::kw_long: 2108 case tok::kw_signed: 2109 case tok::kw_unsigned: 2110 case tok::kw__Complex: 2111 case tok::kw__Imaginary: 2112 case tok::kw_void: 2113 case tok::kw_char: 2114 case tok::kw_wchar_t: 2115 case tok::kw_char16_t: 2116 case tok::kw_char32_t: 2117 2118 case tok::kw_int: 2119 case tok::kw_float: 2120 case tok::kw_double: 2121 case tok::kw_bool: 2122 case tok::kw__Bool: 2123 case tok::kw__Decimal32: 2124 case tok::kw__Decimal64: 2125 case tok::kw__Decimal128: 2126 2127 // struct-or-union-specifier (C99) or class-specifier (C++) 2128 case tok::kw_class: 2129 case tok::kw_struct: 2130 case tok::kw_union: 2131 // enum-specifier 2132 case tok::kw_enum: 2133 2134 // type-qualifier 2135 case tok::kw_const: 2136 case tok::kw_volatile: 2137 case tok::kw_restrict: 2138 2139 // function-specifier 2140 case tok::kw_inline: 2141 case tok::kw_virtual: 2142 case tok::kw_explicit: 2143 2144 // typedef-name 2145 case tok::annot_typename: 2146 2147 // GNU typeof support. 2148 case tok::kw_typeof: 2149 2150 // GNU attributes. 2151 case tok::kw___attribute: 2152 return true; 2153 2154 // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'. 2155 case tok::less: 2156 return getLang().ObjC1; 2157 2158 case tok::kw___declspec: 2159 case tok::kw___cdecl: 2160 case tok::kw___stdcall: 2161 case tok::kw___fastcall: 2162 case tok::kw___w64: 2163 case tok::kw___ptr64: 2164 case tok::kw___forceinline: 2165 return true; 2166 } 2167} 2168 2169bool Parser::isConstructorDeclarator() { 2170 TentativeParsingAction TPA(*this); 2171 2172 // Parse the C++ scope specifier. 2173 CXXScopeSpec SS; 2174 ParseOptionalCXXScopeSpecifier(SS, 0, true); 2175 2176 // Parse the constructor name. 2177 if (Tok.is(tok::identifier) || Tok.is(tok::annot_template_id)) { 2178 // We already know that we have a constructor name; just consume 2179 // the token. 2180 ConsumeToken(); 2181 } else { 2182 TPA.Revert(); 2183 return false; 2184 } 2185 2186 // Current class name must be followed by a left parentheses. 2187 if (Tok.isNot(tok::l_paren)) { 2188 TPA.Revert(); 2189 return false; 2190 } 2191 ConsumeParen(); 2192 2193 // A right parentheses or ellipsis signals that we have a constructor. 2194 if (Tok.is(tok::r_paren) || Tok.is(tok::ellipsis)) { 2195 TPA.Revert(); 2196 return true; 2197 } 2198 2199 // If we need to, enter the specified scope. 2200 DeclaratorScopeObj DeclScopeObj(*this, SS); 2201 if (SS.isSet() && Actions.ShouldEnterDeclaratorScope(CurScope, SS)) 2202 DeclScopeObj.EnterDeclaratorScope(); 2203 2204 // Check whether the next token(s) are part of a declaration 2205 // specifier, in which case we have the start of a parameter and, 2206 // therefore, we know that this is a constructor. 2207 bool IsConstructor = isDeclarationSpecifier(); 2208 TPA.Revert(); 2209 return IsConstructor; 2210} 2211 2212/// ParseTypeQualifierListOpt 2213/// type-qualifier-list: [C99 6.7.5] 2214/// type-qualifier 2215/// [GNU] attributes [ only if AttributesAllowed=true ] 2216/// type-qualifier-list type-qualifier 2217/// [GNU] type-qualifier-list attributes [ only if AttributesAllowed=true ] 2218/// [C++0x] attribute-specifier[opt] is allowed before cv-qualifier-seq 2219/// if CXX0XAttributesAllowed = true 2220/// 2221void Parser::ParseTypeQualifierListOpt(DeclSpec &DS, bool GNUAttributesAllowed, 2222 bool CXX0XAttributesAllowed) { 2223 if (getLang().CPlusPlus0x && isCXX0XAttributeSpecifier()) { 2224 SourceLocation Loc = Tok.getLocation(); 2225 CXX0XAttributeList Attr = ParseCXX0XAttributes(); 2226 if (CXX0XAttributesAllowed) 2227 DS.AddAttributes(Attr.AttrList); 2228 else 2229 Diag(Loc, diag::err_attributes_not_allowed); 2230 } 2231 2232 while (1) { 2233 bool isInvalid = false; 2234 const char *PrevSpec = 0; 2235 unsigned DiagID = 0; 2236 SourceLocation Loc = Tok.getLocation(); 2237 2238 switch (Tok.getKind()) { 2239 case tok::kw_const: 2240 isInvalid = DS.SetTypeQual(DeclSpec::TQ_const , Loc, PrevSpec, DiagID, 2241 getLang()); 2242 break; 2243 case tok::kw_volatile: 2244 isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, DiagID, 2245 getLang()); 2246 break; 2247 case tok::kw_restrict: 2248 isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, DiagID, 2249 getLang()); 2250 break; 2251 case tok::kw___w64: 2252 case tok::kw___ptr64: 2253 case tok::kw___cdecl: 2254 case tok::kw___stdcall: 2255 case tok::kw___fastcall: 2256 if (GNUAttributesAllowed) { 2257 DS.AddAttributes(ParseMicrosoftTypeAttributes()); 2258 continue; 2259 } 2260 goto DoneWithTypeQuals; 2261 case tok::kw___attribute: 2262 if (GNUAttributesAllowed) { 2263 DS.AddAttributes(ParseGNUAttributes()); 2264 continue; // do *not* consume the next token! 2265 } 2266 // otherwise, FALL THROUGH! 2267 default: 2268 DoneWithTypeQuals: 2269 // If this is not a type-qualifier token, we're done reading type 2270 // qualifiers. First verify that DeclSpec's are consistent. 2271 DS.Finish(Diags, PP); 2272 return; 2273 } 2274 2275 // If the specifier combination wasn't legal, issue a diagnostic. 2276 if (isInvalid) { 2277 assert(PrevSpec && "Method did not return previous specifier!"); 2278 Diag(Tok, DiagID) << PrevSpec; 2279 } 2280 ConsumeToken(); 2281 } 2282} 2283 2284 2285/// ParseDeclarator - Parse and verify a newly-initialized declarator. 2286/// 2287void Parser::ParseDeclarator(Declarator &D) { 2288 /// This implements the 'declarator' production in the C grammar, then checks 2289 /// for well-formedness and issues diagnostics. 2290 ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator); 2291} 2292 2293/// ParseDeclaratorInternal - Parse a C or C++ declarator. The direct-declarator 2294/// is parsed by the function passed to it. Pass null, and the direct-declarator 2295/// isn't parsed at all, making this function effectively parse the C++ 2296/// ptr-operator production. 2297/// 2298/// declarator: [C99 6.7.5] [C++ 8p4, dcl.decl] 2299/// [C] pointer[opt] direct-declarator 2300/// [C++] direct-declarator 2301/// [C++] ptr-operator declarator 2302/// 2303/// pointer: [C99 6.7.5] 2304/// '*' type-qualifier-list[opt] 2305/// '*' type-qualifier-list[opt] pointer 2306/// 2307/// ptr-operator: 2308/// '*' cv-qualifier-seq[opt] 2309/// '&' 2310/// [C++0x] '&&' 2311/// [GNU] '&' restrict[opt] attributes[opt] 2312/// [GNU?] '&&' restrict[opt] attributes[opt] 2313/// '::'[opt] nested-name-specifier '*' cv-qualifier-seq[opt] 2314void Parser::ParseDeclaratorInternal(Declarator &D, 2315 DirectDeclParseFunction DirectDeclParser) { 2316 if (Diags.hasAllExtensionsSilenced()) 2317 D.setExtension(); 2318 // C++ member pointers start with a '::' or a nested-name. 2319 // Member pointers get special handling, since there's no place for the 2320 // scope spec in the generic path below. 2321 if (getLang().CPlusPlus && 2322 (Tok.is(tok::coloncolon) || Tok.is(tok::identifier) || 2323 Tok.is(tok::annot_cxxscope))) { 2324 CXXScopeSpec SS; 2325 if (ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/0, true)) { 2326 if (Tok.isNot(tok::star)) { 2327 // The scope spec really belongs to the direct-declarator. 2328 D.getCXXScopeSpec() = SS; 2329 if (DirectDeclParser) 2330 (this->*DirectDeclParser)(D); 2331 return; 2332 } 2333 2334 SourceLocation Loc = ConsumeToken(); 2335 D.SetRangeEnd(Loc); 2336 DeclSpec DS; 2337 ParseTypeQualifierListOpt(DS); 2338 D.ExtendWithDeclSpec(DS); 2339 2340 // Recurse to parse whatever is left. 2341 ParseDeclaratorInternal(D, DirectDeclParser); 2342 2343 // Sema will have to catch (syntactically invalid) pointers into global 2344 // scope. It has to catch pointers into namespace scope anyway. 2345 D.AddTypeInfo(DeclaratorChunk::getMemberPointer(SS,DS.getTypeQualifiers(), 2346 Loc, DS.TakeAttributes()), 2347 /* Don't replace range end. */SourceLocation()); 2348 return; 2349 } 2350 } 2351 2352 tok::TokenKind Kind = Tok.getKind(); 2353 // Not a pointer, C++ reference, or block. 2354 if (Kind != tok::star && Kind != tok::caret && 2355 (Kind != tok::amp || !getLang().CPlusPlus) && 2356 // We parse rvalue refs in C++03, because otherwise the errors are scary. 2357 (Kind != tok::ampamp || !getLang().CPlusPlus)) { 2358 if (DirectDeclParser) 2359 (this->*DirectDeclParser)(D); 2360 return; 2361 } 2362 2363 // Otherwise, '*' -> pointer, '^' -> block, '&' -> lvalue reference, 2364 // '&&' -> rvalue reference 2365 SourceLocation Loc = ConsumeToken(); // Eat the *, ^, & or &&. 2366 D.SetRangeEnd(Loc); 2367 2368 if (Kind == tok::star || Kind == tok::caret) { 2369 // Is a pointer. 2370 DeclSpec DS; 2371 2372 ParseTypeQualifierListOpt(DS); 2373 D.ExtendWithDeclSpec(DS); 2374 2375 // Recursively parse the declarator. 2376 ParseDeclaratorInternal(D, DirectDeclParser); 2377 if (Kind == tok::star) 2378 // Remember that we parsed a pointer type, and remember the type-quals. 2379 D.AddTypeInfo(DeclaratorChunk::getPointer(DS.getTypeQualifiers(), Loc, 2380 DS.TakeAttributes()), 2381 SourceLocation()); 2382 else 2383 // Remember that we parsed a Block type, and remember the type-quals. 2384 D.AddTypeInfo(DeclaratorChunk::getBlockPointer(DS.getTypeQualifiers(), 2385 Loc, DS.TakeAttributes()), 2386 SourceLocation()); 2387 } else { 2388 // Is a reference 2389 DeclSpec DS; 2390 2391 // Complain about rvalue references in C++03, but then go on and build 2392 // the declarator. 2393 if (Kind == tok::ampamp && !getLang().CPlusPlus0x) 2394 Diag(Loc, diag::err_rvalue_reference); 2395 2396 // C++ 8.3.2p1: cv-qualified references are ill-formed except when the 2397 // cv-qualifiers are introduced through the use of a typedef or of a 2398 // template type argument, in which case the cv-qualifiers are ignored. 2399 // 2400 // [GNU] Retricted references are allowed. 2401 // [GNU] Attributes on references are allowed. 2402 // [C++0x] Attributes on references are not allowed. 2403 ParseTypeQualifierListOpt(DS, true, false); 2404 D.ExtendWithDeclSpec(DS); 2405 2406 if (DS.getTypeQualifiers() != DeclSpec::TQ_unspecified) { 2407 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 2408 Diag(DS.getConstSpecLoc(), 2409 diag::err_invalid_reference_qualifier_application) << "const"; 2410 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 2411 Diag(DS.getVolatileSpecLoc(), 2412 diag::err_invalid_reference_qualifier_application) << "volatile"; 2413 } 2414 2415 // Recursively parse the declarator. 2416 ParseDeclaratorInternal(D, DirectDeclParser); 2417 2418 if (D.getNumTypeObjects() > 0) { 2419 // C++ [dcl.ref]p4: There shall be no references to references. 2420 DeclaratorChunk& InnerChunk = D.getTypeObject(D.getNumTypeObjects() - 1); 2421 if (InnerChunk.Kind == DeclaratorChunk::Reference) { 2422 if (const IdentifierInfo *II = D.getIdentifier()) 2423 Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference) 2424 << II; 2425 else 2426 Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference) 2427 << "type name"; 2428 2429 // Once we've complained about the reference-to-reference, we 2430 // can go ahead and build the (technically ill-formed) 2431 // declarator: reference collapsing will take care of it. 2432 } 2433 } 2434 2435 // Remember that we parsed a reference type. It doesn't have type-quals. 2436 D.AddTypeInfo(DeclaratorChunk::getReference(DS.getTypeQualifiers(), Loc, 2437 DS.TakeAttributes(), 2438 Kind == tok::amp), 2439 SourceLocation()); 2440 } 2441} 2442 2443/// ParseDirectDeclarator 2444/// direct-declarator: [C99 6.7.5] 2445/// [C99] identifier 2446/// '(' declarator ')' 2447/// [GNU] '(' attributes declarator ')' 2448/// [C90] direct-declarator '[' constant-expression[opt] ']' 2449/// [C99] direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']' 2450/// [C99] direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']' 2451/// [C99] direct-declarator '[' type-qual-list 'static' assignment-expr ']' 2452/// [C99] direct-declarator '[' type-qual-list[opt] '*' ']' 2453/// direct-declarator '(' parameter-type-list ')' 2454/// direct-declarator '(' identifier-list[opt] ')' 2455/// [GNU] direct-declarator '(' parameter-forward-declarations 2456/// parameter-type-list[opt] ')' 2457/// [C++] direct-declarator '(' parameter-declaration-clause ')' 2458/// cv-qualifier-seq[opt] exception-specification[opt] 2459/// [C++] declarator-id 2460/// 2461/// declarator-id: [C++ 8] 2462/// id-expression 2463/// '::'[opt] nested-name-specifier[opt] type-name 2464/// 2465/// id-expression: [C++ 5.1] 2466/// unqualified-id 2467/// qualified-id 2468/// 2469/// unqualified-id: [C++ 5.1] 2470/// identifier 2471/// operator-function-id 2472/// conversion-function-id 2473/// '~' class-name 2474/// template-id 2475/// 2476void Parser::ParseDirectDeclarator(Declarator &D) { 2477 DeclaratorScopeObj DeclScopeObj(*this, D.getCXXScopeSpec()); 2478 2479 if (getLang().CPlusPlus && D.mayHaveIdentifier()) { 2480 // ParseDeclaratorInternal might already have parsed the scope. 2481 bool afterCXXScope = D.getCXXScopeSpec().isSet() || 2482 ParseOptionalCXXScopeSpecifier(D.getCXXScopeSpec(), /*ObjectType=*/0, 2483 true); 2484 if (afterCXXScope) { 2485 if (Actions.ShouldEnterDeclaratorScope(CurScope, D.getCXXScopeSpec())) 2486 // Change the declaration context for name lookup, until this function 2487 // is exited (and the declarator has been parsed). 2488 DeclScopeObj.EnterDeclaratorScope(); 2489 } 2490 2491 if (Tok.is(tok::identifier) || Tok.is(tok::kw_operator) || 2492 Tok.is(tok::annot_template_id) || Tok.is(tok::tilde)) { 2493 // We found something that indicates the start of an unqualified-id. 2494 // Parse that unqualified-id. 2495 bool AllowConstructorName 2496 = ((D.getCXXScopeSpec().isSet() && 2497 D.getContext() == Declarator::FileContext) || 2498 (!D.getCXXScopeSpec().isSet() && 2499 D.getContext() == Declarator::MemberContext)) && 2500 !D.getDeclSpec().hasTypeSpecifier(); 2501 if (ParseUnqualifiedId(D.getCXXScopeSpec(), 2502 /*EnteringContext=*/true, 2503 /*AllowDestructorName=*/true, 2504 AllowConstructorName, 2505 /*ObjectType=*/0, 2506 D.getName())) { 2507 D.SetIdentifier(0, Tok.getLocation()); 2508 D.setInvalidType(true); 2509 } else { 2510 // Parsed the unqualified-id; update range information and move along. 2511 if (D.getSourceRange().getBegin().isInvalid()) 2512 D.SetRangeBegin(D.getName().getSourceRange().getBegin()); 2513 D.SetRangeEnd(D.getName().getSourceRange().getEnd()); 2514 } 2515 goto PastIdentifier; 2516 } 2517 } else if (Tok.is(tok::identifier) && D.mayHaveIdentifier()) { 2518 assert(!getLang().CPlusPlus && 2519 "There's a C++-specific check for tok::identifier above"); 2520 assert(Tok.getIdentifierInfo() && "Not an identifier?"); 2521 D.SetIdentifier(Tok.getIdentifierInfo(), Tok.getLocation()); 2522 ConsumeToken(); 2523 goto PastIdentifier; 2524 } 2525 2526 if (Tok.is(tok::l_paren)) { 2527 // direct-declarator: '(' declarator ')' 2528 // direct-declarator: '(' attributes declarator ')' 2529 // Example: 'char (*X)' or 'int (*XX)(void)' 2530 ParseParenDeclarator(D); 2531 2532 // If the declarator was parenthesized, we entered the declarator 2533 // scope when parsing the parenthesized declarator, then exited 2534 // the scope already. Re-enter the scope, if we need to. 2535 if (D.getCXXScopeSpec().isSet()) { 2536 if (Actions.ShouldEnterDeclaratorScope(CurScope, D.getCXXScopeSpec())) 2537 // Change the declaration context for name lookup, until this function 2538 // is exited (and the declarator has been parsed). 2539 DeclScopeObj.EnterDeclaratorScope(); 2540 } 2541 } else if (D.mayOmitIdentifier()) { 2542 // This could be something simple like "int" (in which case the declarator 2543 // portion is empty), if an abstract-declarator is allowed. 2544 D.SetIdentifier(0, Tok.getLocation()); 2545 } else { 2546 if (D.getContext() == Declarator::MemberContext) 2547 Diag(Tok, diag::err_expected_member_name_or_semi) 2548 << D.getDeclSpec().getSourceRange(); 2549 else if (getLang().CPlusPlus) 2550 Diag(Tok, diag::err_expected_unqualified_id) << getLang().CPlusPlus; 2551 else 2552 Diag(Tok, diag::err_expected_ident_lparen); 2553 D.SetIdentifier(0, Tok.getLocation()); 2554 D.setInvalidType(true); 2555 } 2556 2557 PastIdentifier: 2558 assert(D.isPastIdentifier() && 2559 "Haven't past the location of the identifier yet?"); 2560 2561 // Don't parse attributes unless we have an identifier. 2562 if (D.getIdentifier() && getLang().CPlusPlus 2563 && isCXX0XAttributeSpecifier(true)) { 2564 SourceLocation AttrEndLoc; 2565 CXX0XAttributeList Attr = ParseCXX0XAttributes(); 2566 D.AddAttributes(Attr.AttrList, AttrEndLoc); 2567 } 2568 2569 while (1) { 2570 if (Tok.is(tok::l_paren)) { 2571 // The paren may be part of a C++ direct initializer, eg. "int x(1);". 2572 // In such a case, check if we actually have a function declarator; if it 2573 // is not, the declarator has been fully parsed. 2574 if (getLang().CPlusPlus && D.mayBeFollowedByCXXDirectInit()) { 2575 // When not in file scope, warn for ambiguous function declarators, just 2576 // in case the author intended it as a variable definition. 2577 bool warnIfAmbiguous = D.getContext() != Declarator::FileContext; 2578 if (!isCXXFunctionDeclarator(warnIfAmbiguous)) 2579 break; 2580 } 2581 ParseFunctionDeclarator(ConsumeParen(), D); 2582 } else if (Tok.is(tok::l_square)) { 2583 ParseBracketDeclarator(D); 2584 } else { 2585 break; 2586 } 2587 } 2588} 2589 2590/// ParseParenDeclarator - We parsed the declarator D up to a paren. This is 2591/// only called before the identifier, so these are most likely just grouping 2592/// parens for precedence. If we find that these are actually function 2593/// parameter parens in an abstract-declarator, we call ParseFunctionDeclarator. 2594/// 2595/// direct-declarator: 2596/// '(' declarator ')' 2597/// [GNU] '(' attributes declarator ')' 2598/// direct-declarator '(' parameter-type-list ')' 2599/// direct-declarator '(' identifier-list[opt] ')' 2600/// [GNU] direct-declarator '(' parameter-forward-declarations 2601/// parameter-type-list[opt] ')' 2602/// 2603void Parser::ParseParenDeclarator(Declarator &D) { 2604 SourceLocation StartLoc = ConsumeParen(); 2605 assert(!D.isPastIdentifier() && "Should be called before passing identifier"); 2606 2607 // Eat any attributes before we look at whether this is a grouping or function 2608 // declarator paren. If this is a grouping paren, the attribute applies to 2609 // the type being built up, for example: 2610 // int (__attribute__(()) *x)(long y) 2611 // If this ends up not being a grouping paren, the attribute applies to the 2612 // first argument, for example: 2613 // int (__attribute__(()) int x) 2614 // In either case, we need to eat any attributes to be able to determine what 2615 // sort of paren this is. 2616 // 2617 AttributeList *AttrList = 0; 2618 bool RequiresArg = false; 2619 if (Tok.is(tok::kw___attribute)) { 2620 AttrList = ParseGNUAttributes(); 2621 2622 // We require that the argument list (if this is a non-grouping paren) be 2623 // present even if the attribute list was empty. 2624 RequiresArg = true; 2625 } 2626 // Eat any Microsoft extensions. 2627 if (Tok.is(tok::kw___cdecl) || Tok.is(tok::kw___stdcall) || 2628 Tok.is(tok::kw___fastcall) || Tok.is(tok::kw___w64) || 2629 Tok.is(tok::kw___ptr64)) { 2630 AttrList = ParseMicrosoftTypeAttributes(AttrList); 2631 } 2632 2633 // If we haven't past the identifier yet (or where the identifier would be 2634 // stored, if this is an abstract declarator), then this is probably just 2635 // grouping parens. However, if this could be an abstract-declarator, then 2636 // this could also be the start of function arguments (consider 'void()'). 2637 bool isGrouping; 2638 2639 if (!D.mayOmitIdentifier()) { 2640 // If this can't be an abstract-declarator, this *must* be a grouping 2641 // paren, because we haven't seen the identifier yet. 2642 isGrouping = true; 2643 } else if (Tok.is(tok::r_paren) || // 'int()' is a function. 2644 (getLang().CPlusPlus && Tok.is(tok::ellipsis)) || // C++ int(...) 2645 isDeclarationSpecifier()) { // 'int(int)' is a function. 2646 // This handles C99 6.7.5.3p11: in "typedef int X; void foo(X)", X is 2647 // considered to be a type, not a K&R identifier-list. 2648 isGrouping = false; 2649 } else { 2650 // Otherwise, this is a grouping paren, e.g. 'int (*X)' or 'int(X)'. 2651 isGrouping = true; 2652 } 2653 2654 // If this is a grouping paren, handle: 2655 // direct-declarator: '(' declarator ')' 2656 // direct-declarator: '(' attributes declarator ')' 2657 if (isGrouping) { 2658 bool hadGroupingParens = D.hasGroupingParens(); 2659 D.setGroupingParens(true); 2660 if (AttrList) 2661 D.AddAttributes(AttrList, SourceLocation()); 2662 2663 ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator); 2664 // Match the ')'. 2665 SourceLocation Loc = MatchRHSPunctuation(tok::r_paren, StartLoc); 2666 2667 D.setGroupingParens(hadGroupingParens); 2668 D.SetRangeEnd(Loc); 2669 return; 2670 } 2671 2672 // Okay, if this wasn't a grouping paren, it must be the start of a function 2673 // argument list. Recognize that this declarator will never have an 2674 // identifier (and remember where it would have been), then call into 2675 // ParseFunctionDeclarator to handle of argument list. 2676 D.SetIdentifier(0, Tok.getLocation()); 2677 2678 ParseFunctionDeclarator(StartLoc, D, AttrList, RequiresArg); 2679} 2680 2681/// ParseFunctionDeclarator - We are after the identifier and have parsed the 2682/// declarator D up to a paren, which indicates that we are parsing function 2683/// arguments. 2684/// 2685/// If AttrList is non-null, then the caller parsed those arguments immediately 2686/// after the open paren - they should be considered to be the first argument of 2687/// a parameter. If RequiresArg is true, then the first argument of the 2688/// function is required to be present and required to not be an identifier 2689/// list. 2690/// 2691/// This method also handles this portion of the grammar: 2692/// parameter-type-list: [C99 6.7.5] 2693/// parameter-list 2694/// parameter-list ',' '...' 2695/// [C++] parameter-list '...' 2696/// 2697/// parameter-list: [C99 6.7.5] 2698/// parameter-declaration 2699/// parameter-list ',' parameter-declaration 2700/// 2701/// parameter-declaration: [C99 6.7.5] 2702/// declaration-specifiers declarator 2703/// [C++] declaration-specifiers declarator '=' assignment-expression 2704/// [GNU] declaration-specifiers declarator attributes 2705/// declaration-specifiers abstract-declarator[opt] 2706/// [C++] declaration-specifiers abstract-declarator[opt] 2707/// '=' assignment-expression 2708/// [GNU] declaration-specifiers abstract-declarator[opt] attributes 2709/// 2710/// For C++, after the parameter-list, it also parses "cv-qualifier-seq[opt]" 2711/// and "exception-specification[opt]". 2712/// 2713void Parser::ParseFunctionDeclarator(SourceLocation LParenLoc, Declarator &D, 2714 AttributeList *AttrList, 2715 bool RequiresArg) { 2716 // lparen is already consumed! 2717 assert(D.isPastIdentifier() && "Should not call before identifier!"); 2718 2719 // This parameter list may be empty. 2720 if (Tok.is(tok::r_paren)) { 2721 if (RequiresArg) { 2722 Diag(Tok, diag::err_argument_required_after_attribute); 2723 delete AttrList; 2724 } 2725 2726 SourceLocation RParenLoc = ConsumeParen(); // Eat the closing ')'. 2727 SourceLocation EndLoc = RParenLoc; 2728 2729 // cv-qualifier-seq[opt]. 2730 DeclSpec DS; 2731 bool hasExceptionSpec = false; 2732 SourceLocation ThrowLoc; 2733 bool hasAnyExceptionSpec = false; 2734 llvm::SmallVector<TypeTy*, 2> Exceptions; 2735 llvm::SmallVector<SourceRange, 2> ExceptionRanges; 2736 if (getLang().CPlusPlus) { 2737 ParseTypeQualifierListOpt(DS, false /*no attributes*/); 2738 if (!DS.getSourceRange().getEnd().isInvalid()) 2739 EndLoc = DS.getSourceRange().getEnd(); 2740 2741 // Parse exception-specification[opt]. 2742 if (Tok.is(tok::kw_throw)) { 2743 hasExceptionSpec = true; 2744 ThrowLoc = Tok.getLocation(); 2745 ParseExceptionSpecification(EndLoc, Exceptions, ExceptionRanges, 2746 hasAnyExceptionSpec); 2747 assert(Exceptions.size() == ExceptionRanges.size() && 2748 "Produced different number of exception types and ranges."); 2749 } 2750 } 2751 2752 // Remember that we parsed a function type, and remember the attributes. 2753 // int() -> no prototype, no '...'. 2754 D.AddTypeInfo(DeclaratorChunk::getFunction(/*prototype*/getLang().CPlusPlus, 2755 /*variadic*/ false, 2756 SourceLocation(), 2757 /*arglist*/ 0, 0, 2758 DS.getTypeQualifiers(), 2759 hasExceptionSpec, ThrowLoc, 2760 hasAnyExceptionSpec, 2761 Exceptions.data(), 2762 ExceptionRanges.data(), 2763 Exceptions.size(), 2764 LParenLoc, RParenLoc, D), 2765 EndLoc); 2766 return; 2767 } 2768 2769 // Alternatively, this parameter list may be an identifier list form for a 2770 // K&R-style function: void foo(a,b,c) 2771 if (!getLang().CPlusPlus && Tok.is(tok::identifier)) { 2772 if (!TryAnnotateTypeOrScopeToken()) { 2773 // K&R identifier lists can't have typedefs as identifiers, per 2774 // C99 6.7.5.3p11. 2775 if (RequiresArg) { 2776 Diag(Tok, diag::err_argument_required_after_attribute); 2777 delete AttrList; 2778 } 2779 // Identifier list. Note that '(' identifier-list ')' is only allowed for 2780 // normal declarators, not for abstract-declarators. 2781 return ParseFunctionDeclaratorIdentifierList(LParenLoc, D); 2782 } 2783 } 2784 2785 // Finally, a normal, non-empty parameter type list. 2786 2787 // Build up an array of information about the parsed arguments. 2788 llvm::SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo; 2789 2790 // Enter function-declaration scope, limiting any declarators to the 2791 // function prototype scope, including parameter declarators. 2792 ParseScope PrototypeScope(this, 2793 Scope::FunctionPrototypeScope|Scope::DeclScope); 2794 2795 bool IsVariadic = false; 2796 SourceLocation EllipsisLoc; 2797 while (1) { 2798 if (Tok.is(tok::ellipsis)) { 2799 IsVariadic = true; 2800 EllipsisLoc = ConsumeToken(); // Consume the ellipsis. 2801 break; 2802 } 2803 2804 SourceLocation DSStart = Tok.getLocation(); 2805 2806 // Parse the declaration-specifiers. 2807 // Just use the ParsingDeclaration "scope" of the declarator. 2808 DeclSpec DS; 2809 2810 // If the caller parsed attributes for the first argument, add them now. 2811 if (AttrList) { 2812 DS.AddAttributes(AttrList); 2813 AttrList = 0; // Only apply the attributes to the first parameter. 2814 } 2815 ParseDeclarationSpecifiers(DS); 2816 2817 // Parse the declarator. This is "PrototypeContext", because we must 2818 // accept either 'declarator' or 'abstract-declarator' here. 2819 Declarator ParmDecl(DS, Declarator::PrototypeContext); 2820 ParseDeclarator(ParmDecl); 2821 2822 // Parse GNU attributes, if present. 2823 if (Tok.is(tok::kw___attribute)) { 2824 SourceLocation Loc; 2825 AttributeList *AttrList = ParseGNUAttributes(&Loc); 2826 ParmDecl.AddAttributes(AttrList, Loc); 2827 } 2828 2829 // Remember this parsed parameter in ParamInfo. 2830 IdentifierInfo *ParmII = ParmDecl.getIdentifier(); 2831 2832 // DefArgToks is used when the parsing of default arguments needs 2833 // to be delayed. 2834 CachedTokens *DefArgToks = 0; 2835 2836 // If no parameter was specified, verify that *something* was specified, 2837 // otherwise we have a missing type and identifier. 2838 if (DS.isEmpty() && ParmDecl.getIdentifier() == 0 && 2839 ParmDecl.getNumTypeObjects() == 0) { 2840 // Completely missing, emit error. 2841 Diag(DSStart, diag::err_missing_param); 2842 } else { 2843 // Otherwise, we have something. Add it and let semantic analysis try 2844 // to grok it and add the result to the ParamInfo we are building. 2845 2846 // Inform the actions module about the parameter declarator, so it gets 2847 // added to the current scope. 2848 DeclPtrTy Param = Actions.ActOnParamDeclarator(CurScope, ParmDecl); 2849 2850 // Parse the default argument, if any. We parse the default 2851 // arguments in all dialects; the semantic analysis in 2852 // ActOnParamDefaultArgument will reject the default argument in 2853 // C. 2854 if (Tok.is(tok::equal)) { 2855 SourceLocation EqualLoc = Tok.getLocation(); 2856 2857 // Parse the default argument 2858 if (D.getContext() == Declarator::MemberContext) { 2859 // If we're inside a class definition, cache the tokens 2860 // corresponding to the default argument. We'll actually parse 2861 // them when we see the end of the class definition. 2862 // FIXME: Templates will require something similar. 2863 // FIXME: Can we use a smart pointer for Toks? 2864 DefArgToks = new CachedTokens; 2865 2866 if (!ConsumeAndStoreUntil(tok::comma, tok::r_paren, *DefArgToks, 2867 tok::semi, false)) { 2868 delete DefArgToks; 2869 DefArgToks = 0; 2870 Actions.ActOnParamDefaultArgumentError(Param); 2871 } else 2872 Actions.ActOnParamUnparsedDefaultArgument(Param, EqualLoc, 2873 (*DefArgToks)[1].getLocation()); 2874 } else { 2875 // Consume the '='. 2876 ConsumeToken(); 2877 2878 OwningExprResult DefArgResult(ParseAssignmentExpression()); 2879 if (DefArgResult.isInvalid()) { 2880 Actions.ActOnParamDefaultArgumentError(Param); 2881 SkipUntil(tok::comma, tok::r_paren, true, true); 2882 } else { 2883 // Inform the actions module about the default argument 2884 Actions.ActOnParamDefaultArgument(Param, EqualLoc, 2885 move(DefArgResult)); 2886 } 2887 } 2888 } 2889 2890 ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII, 2891 ParmDecl.getIdentifierLoc(), Param, 2892 DefArgToks)); 2893 } 2894 2895 // If the next token is a comma, consume it and keep reading arguments. 2896 if (Tok.isNot(tok::comma)) { 2897 if (Tok.is(tok::ellipsis)) { 2898 IsVariadic = true; 2899 EllipsisLoc = ConsumeToken(); // Consume the ellipsis. 2900 2901 if (!getLang().CPlusPlus) { 2902 // We have ellipsis without a preceding ',', which is ill-formed 2903 // in C. Complain and provide the fix. 2904 Diag(EllipsisLoc, diag::err_missing_comma_before_ellipsis) 2905 << CodeModificationHint::CreateInsertion(EllipsisLoc, ", "); 2906 } 2907 } 2908 2909 break; 2910 } 2911 2912 // Consume the comma. 2913 ConsumeToken(); 2914 } 2915 2916 // Leave prototype scope. 2917 PrototypeScope.Exit(); 2918 2919 // If we have the closing ')', eat it. 2920 SourceLocation RParenLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc); 2921 SourceLocation EndLoc = RParenLoc; 2922 2923 DeclSpec DS; 2924 bool hasExceptionSpec = false; 2925 SourceLocation ThrowLoc; 2926 bool hasAnyExceptionSpec = false; 2927 llvm::SmallVector<TypeTy*, 2> Exceptions; 2928 llvm::SmallVector<SourceRange, 2> ExceptionRanges; 2929 2930 if (getLang().CPlusPlus) { 2931 // Parse cv-qualifier-seq[opt]. 2932 ParseTypeQualifierListOpt(DS, false /*no attributes*/); 2933 if (!DS.getSourceRange().getEnd().isInvalid()) 2934 EndLoc = DS.getSourceRange().getEnd(); 2935 2936 // Parse exception-specification[opt]. 2937 if (Tok.is(tok::kw_throw)) { 2938 hasExceptionSpec = true; 2939 ThrowLoc = Tok.getLocation(); 2940 ParseExceptionSpecification(EndLoc, Exceptions, ExceptionRanges, 2941 hasAnyExceptionSpec); 2942 assert(Exceptions.size() == ExceptionRanges.size() && 2943 "Produced different number of exception types and ranges."); 2944 } 2945 } 2946 2947 // Remember that we parsed a function type, and remember the attributes. 2948 D.AddTypeInfo(DeclaratorChunk::getFunction(/*proto*/true, IsVariadic, 2949 EllipsisLoc, 2950 ParamInfo.data(), ParamInfo.size(), 2951 DS.getTypeQualifiers(), 2952 hasExceptionSpec, ThrowLoc, 2953 hasAnyExceptionSpec, 2954 Exceptions.data(), 2955 ExceptionRanges.data(), 2956 Exceptions.size(), 2957 LParenLoc, RParenLoc, D), 2958 EndLoc); 2959} 2960 2961/// ParseFunctionDeclaratorIdentifierList - While parsing a function declarator 2962/// we found a K&R-style identifier list instead of a type argument list. The 2963/// current token is known to be the first identifier in the list. 2964/// 2965/// identifier-list: [C99 6.7.5] 2966/// identifier 2967/// identifier-list ',' identifier 2968/// 2969void Parser::ParseFunctionDeclaratorIdentifierList(SourceLocation LParenLoc, 2970 Declarator &D) { 2971 // Build up an array of information about the parsed arguments. 2972 llvm::SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo; 2973 llvm::SmallSet<const IdentifierInfo*, 16> ParamsSoFar; 2974 2975 // If there was no identifier specified for the declarator, either we are in 2976 // an abstract-declarator, or we are in a parameter declarator which was found 2977 // to be abstract. In abstract-declarators, identifier lists are not valid: 2978 // diagnose this. 2979 if (!D.getIdentifier()) 2980 Diag(Tok, diag::ext_ident_list_in_param); 2981 2982 // Tok is known to be the first identifier in the list. Remember this 2983 // identifier in ParamInfo. 2984 ParamsSoFar.insert(Tok.getIdentifierInfo()); 2985 ParamInfo.push_back(DeclaratorChunk::ParamInfo(Tok.getIdentifierInfo(), 2986 Tok.getLocation(), 2987 DeclPtrTy())); 2988 2989 ConsumeToken(); // eat the first identifier. 2990 2991 while (Tok.is(tok::comma)) { 2992 // Eat the comma. 2993 ConsumeToken(); 2994 2995 // If this isn't an identifier, report the error and skip until ')'. 2996 if (Tok.isNot(tok::identifier)) { 2997 Diag(Tok, diag::err_expected_ident); 2998 SkipUntil(tok::r_paren); 2999 return; 3000 } 3001 3002 IdentifierInfo *ParmII = Tok.getIdentifierInfo(); 3003 3004 // Reject 'typedef int y; int test(x, y)', but continue parsing. 3005 if (Actions.getTypeName(*ParmII, Tok.getLocation(), CurScope)) 3006 Diag(Tok, diag::err_unexpected_typedef_ident) << ParmII; 3007 3008 // Verify that the argument identifier has not already been mentioned. 3009 if (!ParamsSoFar.insert(ParmII)) { 3010 Diag(Tok, diag::err_param_redefinition) << ParmII; 3011 } else { 3012 // Remember this identifier in ParamInfo. 3013 ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII, 3014 Tok.getLocation(), 3015 DeclPtrTy())); 3016 } 3017 3018 // Eat the identifier. 3019 ConsumeToken(); 3020 } 3021 3022 // If we have the closing ')', eat it and we're done. 3023 SourceLocation RLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc); 3024 3025 // Remember that we parsed a function type, and remember the attributes. This 3026 // function type is always a K&R style function type, which is not varargs and 3027 // has no prototype. 3028 D.AddTypeInfo(DeclaratorChunk::getFunction(/*proto*/false, /*varargs*/false, 3029 SourceLocation(), 3030 &ParamInfo[0], ParamInfo.size(), 3031 /*TypeQuals*/0, 3032 /*exception*/false, 3033 SourceLocation(), false, 0, 0, 0, 3034 LParenLoc, RLoc, D), 3035 RLoc); 3036} 3037 3038/// [C90] direct-declarator '[' constant-expression[opt] ']' 3039/// [C99] direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']' 3040/// [C99] direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']' 3041/// [C99] direct-declarator '[' type-qual-list 'static' assignment-expr ']' 3042/// [C99] direct-declarator '[' type-qual-list[opt] '*' ']' 3043void Parser::ParseBracketDeclarator(Declarator &D) { 3044 SourceLocation StartLoc = ConsumeBracket(); 3045 3046 // C array syntax has many features, but by-far the most common is [] and [4]. 3047 // This code does a fast path to handle some of the most obvious cases. 3048 if (Tok.getKind() == tok::r_square) { 3049 SourceLocation EndLoc = MatchRHSPunctuation(tok::r_square, StartLoc); 3050 //FIXME: Use these 3051 CXX0XAttributeList Attr; 3052 if (getLang().CPlusPlus0x && isCXX0XAttributeSpecifier(true)) { 3053 Attr = ParseCXX0XAttributes(); 3054 } 3055 3056 // Remember that we parsed the empty array type. 3057 OwningExprResult NumElements(Actions); 3058 D.AddTypeInfo(DeclaratorChunk::getArray(0, false, false, 0, 3059 StartLoc, EndLoc), 3060 EndLoc); 3061 return; 3062 } else if (Tok.getKind() == tok::numeric_constant && 3063 GetLookAheadToken(1).is(tok::r_square)) { 3064 // [4] is very common. Parse the numeric constant expression. 3065 OwningExprResult ExprRes(Actions.ActOnNumericConstant(Tok)); 3066 ConsumeToken(); 3067 3068 SourceLocation EndLoc = MatchRHSPunctuation(tok::r_square, StartLoc); 3069 //FIXME: Use these 3070 CXX0XAttributeList Attr; 3071 if (getLang().CPlusPlus0x && isCXX0XAttributeSpecifier()) { 3072 Attr = ParseCXX0XAttributes(); 3073 } 3074 3075 // If there was an error parsing the assignment-expression, recover. 3076 if (ExprRes.isInvalid()) 3077 ExprRes.release(); // Deallocate expr, just use []. 3078 3079 // Remember that we parsed a array type, and remember its features. 3080 D.AddTypeInfo(DeclaratorChunk::getArray(0, false, 0, ExprRes.release(), 3081 StartLoc, EndLoc), 3082 EndLoc); 3083 return; 3084 } 3085 3086 // If valid, this location is the position where we read the 'static' keyword. 3087 SourceLocation StaticLoc; 3088 if (Tok.is(tok::kw_static)) 3089 StaticLoc = ConsumeToken(); 3090 3091 // If there is a type-qualifier-list, read it now. 3092 // Type qualifiers in an array subscript are a C99 feature. 3093 DeclSpec DS; 3094 ParseTypeQualifierListOpt(DS, false /*no attributes*/); 3095 3096 // If we haven't already read 'static', check to see if there is one after the 3097 // type-qualifier-list. 3098 if (!StaticLoc.isValid() && Tok.is(tok::kw_static)) 3099 StaticLoc = ConsumeToken(); 3100 3101 // Handle "direct-declarator [ type-qual-list[opt] * ]". 3102 bool isStar = false; 3103 OwningExprResult NumElements(Actions); 3104 3105 // Handle the case where we have '[*]' as the array size. However, a leading 3106 // star could be the start of an expression, for example 'X[*p + 4]'. Verify 3107 // the the token after the star is a ']'. Since stars in arrays are 3108 // infrequent, use of lookahead is not costly here. 3109 if (Tok.is(tok::star) && GetLookAheadToken(1).is(tok::r_square)) { 3110 ConsumeToken(); // Eat the '*'. 3111 3112 if (StaticLoc.isValid()) { 3113 Diag(StaticLoc, diag::err_unspecified_vla_size_with_static); 3114 StaticLoc = SourceLocation(); // Drop the static. 3115 } 3116 isStar = true; 3117 } else if (Tok.isNot(tok::r_square)) { 3118 // Note, in C89, this production uses the constant-expr production instead 3119 // of assignment-expr. The only difference is that assignment-expr allows 3120 // things like '=' and '*='. Sema rejects these in C89 mode because they 3121 // are not i-c-e's, so we don't need to distinguish between the two here. 3122 3123 // Parse the constant-expression or assignment-expression now (depending 3124 // on dialect). 3125 if (getLang().CPlusPlus) 3126 NumElements = ParseConstantExpression(); 3127 else 3128 NumElements = ParseAssignmentExpression(); 3129 } 3130 3131 // If there was an error parsing the assignment-expression, recover. 3132 if (NumElements.isInvalid()) { 3133 D.setInvalidType(true); 3134 // If the expression was invalid, skip it. 3135 SkipUntil(tok::r_square); 3136 return; 3137 } 3138 3139 SourceLocation EndLoc = MatchRHSPunctuation(tok::r_square, StartLoc); 3140 3141 //FIXME: Use these 3142 CXX0XAttributeList Attr; 3143 if (getLang().CPlusPlus0x && isCXX0XAttributeSpecifier()) { 3144 Attr = ParseCXX0XAttributes(); 3145 } 3146 3147 // Remember that we parsed a array type, and remember its features. 3148 D.AddTypeInfo(DeclaratorChunk::getArray(DS.getTypeQualifiers(), 3149 StaticLoc.isValid(), isStar, 3150 NumElements.release(), 3151 StartLoc, EndLoc), 3152 EndLoc); 3153} 3154 3155/// [GNU] typeof-specifier: 3156/// typeof ( expressions ) 3157/// typeof ( type-name ) 3158/// [GNU/C++] typeof unary-expression 3159/// 3160void Parser::ParseTypeofSpecifier(DeclSpec &DS) { 3161 assert(Tok.is(tok::kw_typeof) && "Not a typeof specifier"); 3162 Token OpTok = Tok; 3163 SourceLocation StartLoc = ConsumeToken(); 3164 3165 const bool hasParens = Tok.is(tok::l_paren); 3166 3167 bool isCastExpr; 3168 TypeTy *CastTy; 3169 SourceRange CastRange; 3170 OwningExprResult Operand = ParseExprAfterTypeofSizeofAlignof(OpTok, 3171 isCastExpr, 3172 CastTy, 3173 CastRange); 3174 if (hasParens) 3175 DS.setTypeofParensRange(CastRange); 3176 3177 if (CastRange.getEnd().isInvalid()) 3178 // FIXME: Not accurate, the range gets one token more than it should. 3179 DS.SetRangeEnd(Tok.getLocation()); 3180 else 3181 DS.SetRangeEnd(CastRange.getEnd()); 3182 3183 if (isCastExpr) { 3184 if (!CastTy) { 3185 DS.SetTypeSpecError(); 3186 return; 3187 } 3188 3189 const char *PrevSpec = 0; 3190 unsigned DiagID; 3191 // Check for duplicate type specifiers (e.g. "int typeof(int)"). 3192 if (DS.SetTypeSpecType(DeclSpec::TST_typeofType, StartLoc, PrevSpec, 3193 DiagID, CastTy)) 3194 Diag(StartLoc, DiagID) << PrevSpec; 3195 return; 3196 } 3197 3198 // If we get here, the operand to the typeof was an expresion. 3199 if (Operand.isInvalid()) { 3200 DS.SetTypeSpecError(); 3201 return; 3202 } 3203 3204 const char *PrevSpec = 0; 3205 unsigned DiagID; 3206 // Check for duplicate type specifiers (e.g. "int typeof(int)"). 3207 if (DS.SetTypeSpecType(DeclSpec::TST_typeofExpr, StartLoc, PrevSpec, 3208 DiagID, Operand.release())) 3209 Diag(StartLoc, DiagID) << PrevSpec; 3210} 3211