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