ParseDecl.cpp revision 31a19b6989bbf326d2de5ae12e712e2a65ca9c34
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 "ExtensionRAIIObject.h" 18#include "AstGuard.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() { 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 40 if (DeclaratorInfo.getInvalidType()) 41 return true; 42 43 return Actions.ActOnTypeName(CurScope, DeclaratorInfo); 44} 45 46/// ParseAttributes - Parse a non-empty attributes list. 47/// 48/// [GNU] attributes: 49/// attribute 50/// attributes attribute 51/// 52/// [GNU] attribute: 53/// '__attribute__' '(' '(' attribute-list ')' ')' 54/// 55/// [GNU] attribute-list: 56/// attrib 57/// attribute_list ',' attrib 58/// 59/// [GNU] attrib: 60/// empty 61/// attrib-name 62/// attrib-name '(' identifier ')' 63/// attrib-name '(' identifier ',' nonempty-expr-list ')' 64/// attrib-name '(' argument-expression-list [C99 6.5.2] ')' 65/// 66/// [GNU] attrib-name: 67/// identifier 68/// typespec 69/// typequal 70/// storageclass 71/// 72/// FIXME: The GCC grammar/code for this construct implies we need two 73/// token lookahead. Comment from gcc: "If they start with an identifier 74/// which is followed by a comma or close parenthesis, then the arguments 75/// start with that identifier; otherwise they are an expression list." 76/// 77/// At the moment, I am not doing 2 token lookahead. I am also unaware of 78/// any attributes that don't work (based on my limited testing). Most 79/// attributes are very simple in practice. Until we find a bug, I don't see 80/// a pressing need to implement the 2 token lookahead. 81 82AttributeList *Parser::ParseAttributes(SourceLocation *EndLoc) { 83 assert(Tok.is(tok::kw___attribute) && "Not an attribute list!"); 84 85 AttributeList *CurrAttr = 0; 86 87 while (Tok.is(tok::kw___attribute)) { 88 ConsumeToken(); 89 if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after, 90 "attribute")) { 91 SkipUntil(tok::r_paren, true); // skip until ) or ; 92 return CurrAttr; 93 } 94 if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after, "(")) { 95 SkipUntil(tok::r_paren, true); // skip until ) or ; 96 return CurrAttr; 97 } 98 // Parse the attribute-list. e.g. __attribute__(( weak, alias("__f") )) 99 while (Tok.is(tok::identifier) || isDeclarationSpecifier() || 100 Tok.is(tok::comma)) { 101 102 if (Tok.is(tok::comma)) { 103 // allows for empty/non-empty attributes. ((__vector_size__(16),,,,)) 104 ConsumeToken(); 105 continue; 106 } 107 // we have an identifier or declaration specifier (const, int, etc.) 108 IdentifierInfo *AttrName = Tok.getIdentifierInfo(); 109 SourceLocation AttrNameLoc = ConsumeToken(); 110 111 // check if we have a "paramterized" attribute 112 if (Tok.is(tok::l_paren)) { 113 ConsumeParen(); // ignore the left paren loc for now 114 115 if (Tok.is(tok::identifier)) { 116 IdentifierInfo *ParmName = Tok.getIdentifierInfo(); 117 SourceLocation ParmLoc = ConsumeToken(); 118 119 if (Tok.is(tok::r_paren)) { 120 // __attribute__(( mode(byte) )) 121 ConsumeParen(); // ignore the right paren loc for now 122 CurrAttr = new AttributeList(AttrName, AttrNameLoc, 123 ParmName, ParmLoc, 0, 0, CurrAttr); 124 } else if (Tok.is(tok::comma)) { 125 ConsumeToken(); 126 // __attribute__(( format(printf, 1, 2) )) 127 ExprVector ArgExprs(Actions); 128 bool ArgExprsOk = true; 129 130 // now parse the non-empty comma separated list of expressions 131 while (1) { 132 OwningExprResult ArgExpr(ParseAssignmentExpression()); 133 if (ArgExpr.isInvalid()) { 134 ArgExprsOk = false; 135 SkipUntil(tok::r_paren); 136 break; 137 } else { 138 ArgExprs.push_back(ArgExpr.release()); 139 } 140 if (Tok.isNot(tok::comma)) 141 break; 142 ConsumeToken(); // Eat the comma, move to the next argument 143 } 144 if (ArgExprsOk && Tok.is(tok::r_paren)) { 145 ConsumeParen(); // ignore the right paren loc for now 146 CurrAttr = new AttributeList(AttrName, AttrNameLoc, ParmName, 147 ParmLoc, ArgExprs.take(), ArgExprs.size(), CurrAttr); 148 } 149 } 150 } else { // not an identifier 151 // parse a possibly empty comma separated list of expressions 152 if (Tok.is(tok::r_paren)) { 153 // __attribute__(( nonnull() )) 154 ConsumeParen(); // ignore the right paren loc for now 155 CurrAttr = new AttributeList(AttrName, AttrNameLoc, 156 0, SourceLocation(), 0, 0, CurrAttr); 157 } else { 158 // __attribute__(( aligned(16) )) 159 ExprVector ArgExprs(Actions); 160 bool ArgExprsOk = true; 161 162 // now parse the list of expressions 163 while (1) { 164 OwningExprResult ArgExpr(ParseAssignmentExpression()); 165 if (ArgExpr.isInvalid()) { 166 ArgExprsOk = false; 167 SkipUntil(tok::r_paren); 168 break; 169 } else { 170 ArgExprs.push_back(ArgExpr.release()); 171 } 172 if (Tok.isNot(tok::comma)) 173 break; 174 ConsumeToken(); // Eat the comma, move to the next argument 175 } 176 // Match the ')'. 177 if (ArgExprsOk && Tok.is(tok::r_paren)) { 178 ConsumeParen(); // ignore the right paren loc for now 179 CurrAttr = new AttributeList(AttrName, AttrNameLoc, 0, 180 SourceLocation(), ArgExprs.take(), ArgExprs.size(), 181 CurrAttr); 182 } 183 } 184 } 185 } else { 186 CurrAttr = new AttributeList(AttrName, AttrNameLoc, 187 0, SourceLocation(), 0, 0, CurrAttr); 188 } 189 } 190 if (ExpectAndConsume(tok::r_paren, diag::err_expected_rparen)) 191 SkipUntil(tok::r_paren, false); 192 SourceLocation Loc = Tok.getLocation();; 193 if (ExpectAndConsume(tok::r_paren, diag::err_expected_rparen)) { 194 SkipUntil(tok::r_paren, false); 195 } 196 if (EndLoc) 197 *EndLoc = Loc; 198 } 199 return CurrAttr; 200} 201 202/// FuzzyParseMicrosoftDeclSpec. When -fms-extensions is enabled, this 203/// routine is called to skip/ignore tokens that comprise the MS declspec. 204void Parser::FuzzyParseMicrosoftDeclSpec() { 205 assert(Tok.is(tok::kw___declspec) && "Not a declspec!"); 206 ConsumeToken(); 207 if (Tok.is(tok::l_paren)) { 208 unsigned short savedParenCount = ParenCount; 209 do { 210 ConsumeAnyToken(); 211 } while (ParenCount > savedParenCount && Tok.isNot(tok::eof)); 212 } 213 return; 214} 215 216/// ParseDeclaration - Parse a full 'declaration', which consists of 217/// declaration-specifiers, some number of declarators, and a semicolon. 218/// 'Context' should be a Declarator::TheContext value. 219/// 220/// declaration: [C99 6.7] 221/// block-declaration -> 222/// simple-declaration 223/// others [FIXME] 224/// [C++] template-declaration 225/// [C++] namespace-definition 226/// [C++] using-directive 227/// [C++] using-declaration [TODO] 228/// [C++0x] static_assert-declaration 229/// others... [FIXME] 230/// 231Parser::DeclGroupPtrTy Parser::ParseDeclaration(unsigned Context) { 232 DeclPtrTy SingleDecl; 233 switch (Tok.getKind()) { 234 case tok::kw_export: 235 case tok::kw_template: 236 SingleDecl = ParseTemplateDeclarationOrSpecialization(Context); 237 break; 238 case tok::kw_namespace: 239 SingleDecl = ParseNamespace(Context); 240 break; 241 case tok::kw_using: 242 SingleDecl = ParseUsingDirectiveOrDeclaration(Context); 243 break; 244 case tok::kw_static_assert: 245 SingleDecl = ParseStaticAssertDeclaration(); 246 break; 247 default: 248 return ParseSimpleDeclaration(Context); 249 } 250 251 // This routine returns a DeclGroup, if the thing we parsed only contains a 252 // single decl, convert it now. 253 return Actions.ConvertDeclToDeclGroup(SingleDecl); 254} 255 256/// simple-declaration: [C99 6.7: declaration] [C++ 7p1: dcl.dcl] 257/// declaration-specifiers init-declarator-list[opt] ';' 258///[C90/C++]init-declarator-list ';' [TODO] 259/// [OMP] threadprivate-directive [TODO] 260/// 261/// If RequireSemi is false, this does not check for a ';' at the end of the 262/// declaration. 263Parser::DeclGroupPtrTy Parser::ParseSimpleDeclaration(unsigned Context, 264 bool RequireSemi) { 265 // Parse the common declaration-specifiers piece. 266 DeclSpec DS; 267 ParseDeclarationSpecifiers(DS); 268 269 // C99 6.7.2.3p6: Handle "struct-or-union identifier;", "enum { X };" 270 // declaration-specifiers init-declarator-list[opt] ';' 271 if (Tok.is(tok::semi)) { 272 ConsumeToken(); 273 DeclPtrTy TheDecl = Actions.ParsedFreeStandingDeclSpec(CurScope, DS); 274 return Actions.ConvertDeclToDeclGroup(TheDecl); 275 } 276 277 Declarator DeclaratorInfo(DS, (Declarator::TheContext)Context); 278 ParseDeclarator(DeclaratorInfo); 279 280 DeclGroupPtrTy DG = 281 ParseInitDeclaratorListAfterFirstDeclarator(DeclaratorInfo); 282 283 // If the client wants to check what comes after the declaration, just return 284 // immediately without checking anything! 285 if (!RequireSemi) return DG; 286 287 if (Tok.is(tok::semi)) { 288 ConsumeToken(); 289 return DG; 290 } 291 292 Diag(Tok, diag::err_expected_semi_declation); 293 // Skip to end of block or statement 294 SkipUntil(tok::r_brace, true, true); 295 if (Tok.is(tok::semi)) 296 ConsumeToken(); 297 return DG; 298} 299 300 301/// ParseInitDeclaratorListAfterFirstDeclarator - Parse 'declaration' after 302/// parsing 'declaration-specifiers declarator'. This method is split out this 303/// way to handle the ambiguity between top-level function-definitions and 304/// declarations. 305/// 306/// init-declarator-list: [C99 6.7] 307/// init-declarator 308/// init-declarator-list ',' init-declarator 309/// init-declarator: [C99 6.7] 310/// declarator 311/// declarator '=' initializer 312/// [GNU] declarator simple-asm-expr[opt] attributes[opt] 313/// [GNU] declarator simple-asm-expr[opt] attributes[opt] '=' initializer 314/// [C++] declarator initializer[opt] 315/// 316/// [C++] initializer: 317/// [C++] '=' initializer-clause 318/// [C++] '(' expression-list ')' 319/// [C++0x] '=' 'default' [TODO] 320/// [C++0x] '=' 'delete' 321/// 322/// According to the standard grammar, =default and =delete are function 323/// definitions, but that definitely doesn't fit with the parser here. 324/// 325Parser::DeclGroupPtrTy Parser:: 326ParseInitDeclaratorListAfterFirstDeclarator(Declarator &D) { 327 // Declarators may be grouped together ("int X, *Y, Z();"). Remember the decls 328 // that we parse together here. 329 llvm::SmallVector<DeclPtrTy, 8> DeclsInGroup; 330 331 // At this point, we know that it is not a function definition. Parse the 332 // rest of the init-declarator-list. 333 while (1) { 334 // If a simple-asm-expr is present, parse it. 335 if (Tok.is(tok::kw_asm)) { 336 SourceLocation Loc; 337 OwningExprResult AsmLabel(ParseSimpleAsm(&Loc)); 338 if (AsmLabel.isInvalid()) { 339 SkipUntil(tok::semi, true, true); 340 return DeclGroupPtrTy(); 341 } 342 343 D.setAsmLabel(AsmLabel.release()); 344 D.SetRangeEnd(Loc); 345 } 346 347 // If attributes are present, parse them. 348 if (Tok.is(tok::kw___attribute)) { 349 SourceLocation Loc; 350 AttributeList *AttrList = ParseAttributes(&Loc); 351 D.AddAttributes(AttrList, Loc); 352 } 353 354 // Inform the current actions module that we just parsed this declarator. 355 DeclPtrTy ThisDecl = Actions.ActOnDeclarator(CurScope, D); 356 DeclsInGroup.push_back(ThisDecl); 357 358 // Parse declarator '=' initializer. 359 if (Tok.is(tok::equal)) { 360 ConsumeToken(); 361 if (getLang().CPlusPlus0x && Tok.is(tok::kw_delete)) { 362 SourceLocation DelLoc = ConsumeToken(); 363 Actions.SetDeclDeleted(ThisDecl, DelLoc); 364 } else { 365 OwningExprResult Init(ParseInitializer()); 366 if (Init.isInvalid()) { 367 SkipUntil(tok::semi, true, true); 368 return DeclGroupPtrTy(); 369 } 370 Actions.AddInitializerToDecl(ThisDecl, move(Init)); 371 } 372 } else if (Tok.is(tok::l_paren)) { 373 // Parse C++ direct initializer: '(' expression-list ')' 374 SourceLocation LParenLoc = ConsumeParen(); 375 ExprVector Exprs(Actions); 376 CommaLocsTy CommaLocs; 377 378 bool InvalidExpr = false; 379 if (ParseExpressionList(Exprs, CommaLocs)) { 380 SkipUntil(tok::r_paren); 381 InvalidExpr = true; 382 } 383 // Match the ')'. 384 SourceLocation RParenLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc); 385 386 if (!InvalidExpr) { 387 assert(!Exprs.empty() && Exprs.size()-1 == CommaLocs.size() && 388 "Unexpected number of commas!"); 389 Actions.AddCXXDirectInitializerToDecl(ThisDecl, LParenLoc, 390 move_arg(Exprs), 391 &CommaLocs[0], RParenLoc); 392 } 393 } else { 394 Actions.ActOnUninitializedDecl(ThisDecl); 395 } 396 397 // If we don't have a comma, it is either the end of the list (a ';') or an 398 // error, bail out. 399 if (Tok.isNot(tok::comma)) 400 break; 401 402 // Consume the comma. 403 ConsumeToken(); 404 405 // Parse the next declarator. 406 D.clear(); 407 408 // Accept attributes in an init-declarator. In the first declarator in a 409 // declaration, these would be part of the declspec. In subsequent 410 // declarators, they become part of the declarator itself, so that they 411 // don't apply to declarators after *this* one. Examples: 412 // short __attribute__((common)) var; -> declspec 413 // short var __attribute__((common)); -> declarator 414 // short x, __attribute__((common)) var; -> declarator 415 if (Tok.is(tok::kw___attribute)) { 416 SourceLocation Loc; 417 AttributeList *AttrList = ParseAttributes(&Loc); 418 D.AddAttributes(AttrList, Loc); 419 } 420 421 ParseDeclarator(D); 422 } 423 424 return Actions.FinalizeDeclaratorGroup(CurScope, &DeclsInGroup[0], 425 DeclsInGroup.size()); 426} 427 428/// ParseSpecifierQualifierList 429/// specifier-qualifier-list: 430/// type-specifier specifier-qualifier-list[opt] 431/// type-qualifier specifier-qualifier-list[opt] 432/// [GNU] attributes specifier-qualifier-list[opt] 433/// 434void Parser::ParseSpecifierQualifierList(DeclSpec &DS) { 435 /// specifier-qualifier-list is a subset of declaration-specifiers. Just 436 /// parse declaration-specifiers and complain about extra stuff. 437 ParseDeclarationSpecifiers(DS); 438 439 // Validate declspec for type-name. 440 unsigned Specs = DS.getParsedSpecifiers(); 441 if (Specs == DeclSpec::PQ_None && !DS.getNumProtocolQualifiers()) 442 Diag(Tok, diag::err_typename_requires_specqual); 443 444 // Issue diagnostic and remove storage class if present. 445 if (Specs & DeclSpec::PQ_StorageClassSpecifier) { 446 if (DS.getStorageClassSpecLoc().isValid()) 447 Diag(DS.getStorageClassSpecLoc(),diag::err_typename_invalid_storageclass); 448 else 449 Diag(DS.getThreadSpecLoc(), diag::err_typename_invalid_storageclass); 450 DS.ClearStorageClassSpecs(); 451 } 452 453 // Issue diagnostic and remove function specfier if present. 454 if (Specs & DeclSpec::PQ_FunctionSpecifier) { 455 if (DS.isInlineSpecified()) 456 Diag(DS.getInlineSpecLoc(), diag::err_typename_invalid_functionspec); 457 if (DS.isVirtualSpecified()) 458 Diag(DS.getVirtualSpecLoc(), diag::err_typename_invalid_functionspec); 459 if (DS.isExplicitSpecified()) 460 Diag(DS.getExplicitSpecLoc(), diag::err_typename_invalid_functionspec); 461 DS.ClearFunctionSpecs(); 462 } 463} 464 465/// ParseDeclarationSpecifiers 466/// declaration-specifiers: [C99 6.7] 467/// storage-class-specifier declaration-specifiers[opt] 468/// type-specifier declaration-specifiers[opt] 469/// [C99] function-specifier declaration-specifiers[opt] 470/// [GNU] attributes declaration-specifiers[opt] 471/// 472/// storage-class-specifier: [C99 6.7.1] 473/// 'typedef' 474/// 'extern' 475/// 'static' 476/// 'auto' 477/// 'register' 478/// [C++] 'mutable' 479/// [GNU] '__thread' 480/// function-specifier: [C99 6.7.4] 481/// [C99] 'inline' 482/// [C++] 'virtual' 483/// [C++] 'explicit' 484/// 485void Parser::ParseDeclarationSpecifiers(DeclSpec &DS, 486 TemplateParameterLists *TemplateParams, 487 AccessSpecifier AS){ 488 DS.SetRangeStart(Tok.getLocation()); 489 while (1) { 490 int isInvalid = false; 491 const char *PrevSpec = 0; 492 SourceLocation Loc = Tok.getLocation(); 493 494 switch (Tok.getKind()) { 495 default: 496 DoneWithDeclSpec: 497 // If this is not a declaration specifier token, we're done reading decl 498 // specifiers. First verify that DeclSpec's are consistent. 499 DS.Finish(Diags, PP.getSourceManager(), getLang()); 500 return; 501 502 case tok::coloncolon: // ::foo::bar 503 // Annotate C++ scope specifiers. If we get one, loop. 504 if (TryAnnotateCXXScopeToken()) 505 continue; 506 goto DoneWithDeclSpec; 507 508 case tok::annot_cxxscope: { 509 if (DS.hasTypeSpecifier()) 510 goto DoneWithDeclSpec; 511 512 // We are looking for a qualified typename. 513 Token Next = NextToken(); 514 if (Next.is(tok::annot_template_id) && 515 static_cast<TemplateIdAnnotation *>(Next.getAnnotationValue()) 516 ->Kind == TNK_Type_template) { 517 // We have a qualified template-id, e.g., N::A<int> 518 CXXScopeSpec SS; 519 ParseOptionalCXXScopeSpecifier(SS); 520 assert(Tok.is(tok::annot_template_id) && 521 "ParseOptionalCXXScopeSpecifier not working"); 522 AnnotateTemplateIdTokenAsType(&SS); 523 continue; 524 } 525 526 if (Next.isNot(tok::identifier)) 527 goto DoneWithDeclSpec; 528 529 CXXScopeSpec SS; 530 SS.setScopeRep(Tok.getAnnotationValue()); 531 SS.setRange(Tok.getAnnotationRange()); 532 533 // If the next token is the name of the class type that the C++ scope 534 // denotes, followed by a '(', then this is a constructor declaration. 535 // We're done with the decl-specifiers. 536 if (Actions.isCurrentClassName(*NextToken().getIdentifierInfo(), 537 CurScope, &SS) && 538 GetLookAheadToken(2).is(tok::l_paren)) 539 goto DoneWithDeclSpec; 540 541 TypeTy *TypeRep = Actions.getTypeName(*Next.getIdentifierInfo(), 542 Next.getLocation(), CurScope, &SS); 543 544 if (TypeRep == 0) 545 goto DoneWithDeclSpec; 546 547 ConsumeToken(); // The C++ scope. 548 549 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, 550 TypeRep); 551 if (isInvalid) 552 break; 553 554 DS.SetRangeEnd(Tok.getLocation()); 555 ConsumeToken(); // The typename. 556 557 continue; 558 } 559 560 case tok::annot_typename: { 561 if (Tok.getAnnotationValue()) 562 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, 563 Tok.getAnnotationValue()); 564 else 565 DS.SetTypeSpecError(); 566 DS.SetRangeEnd(Tok.getAnnotationEndLoc()); 567 ConsumeToken(); // The typename 568 569 // Objective-C supports syntax of the form 'id<proto1,proto2>' where 'id' 570 // is a specific typedef and 'itf<proto1,proto2>' where 'itf' is an 571 // Objective-C interface. If we don't have Objective-C or a '<', this is 572 // just a normal reference to a typedef name. 573 if (!Tok.is(tok::less) || !getLang().ObjC1) 574 continue; 575 576 SourceLocation EndProtoLoc; 577 llvm::SmallVector<DeclPtrTy, 8> ProtocolDecl; 578 ParseObjCProtocolReferences(ProtocolDecl, false, EndProtoLoc); 579 DS.setProtocolQualifiers(&ProtocolDecl[0], ProtocolDecl.size()); 580 581 DS.SetRangeEnd(EndProtoLoc); 582 continue; 583 } 584 585 // typedef-name 586 case tok::identifier: { 587 // In C++, check to see if this is a scope specifier like foo::bar::, if 588 // so handle it as such. This is important for ctor parsing. 589 if (getLang().CPlusPlus && TryAnnotateCXXScopeToken()) 590 continue; 591 592 // This identifier can only be a typedef name if we haven't already seen 593 // a type-specifier. Without this check we misparse: 594 // typedef int X; struct Y { short X; }; as 'short int'. 595 if (DS.hasTypeSpecifier()) 596 goto DoneWithDeclSpec; 597 598 // It has to be available as a typedef too! 599 TypeTy *TypeRep = Actions.getTypeName(*Tok.getIdentifierInfo(), 600 Tok.getLocation(), CurScope); 601 602 if (TypeRep == 0) 603 goto DoneWithDeclSpec; 604 605 // C++: If the identifier is actually the name of the class type 606 // being defined and the next token is a '(', then this is a 607 // constructor declaration. We're done with the decl-specifiers 608 // and will treat this token as an identifier. 609 if (getLang().CPlusPlus && 610 CurScope->isClassScope() && 611 Actions.isCurrentClassName(*Tok.getIdentifierInfo(), CurScope) && 612 NextToken().getKind() == tok::l_paren) 613 goto DoneWithDeclSpec; 614 615 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, 616 TypeRep); 617 if (isInvalid) 618 break; 619 620 DS.SetRangeEnd(Tok.getLocation()); 621 ConsumeToken(); // The identifier 622 623 // Objective-C supports syntax of the form 'id<proto1,proto2>' where 'id' 624 // is a specific typedef and 'itf<proto1,proto2>' where 'itf' is an 625 // Objective-C interface. If we don't have Objective-C or a '<', this is 626 // just a normal reference to a typedef name. 627 if (!Tok.is(tok::less) || !getLang().ObjC1) 628 continue; 629 630 SourceLocation EndProtoLoc; 631 llvm::SmallVector<DeclPtrTy, 8> ProtocolDecl; 632 ParseObjCProtocolReferences(ProtocolDecl, false, EndProtoLoc); 633 DS.setProtocolQualifiers(&ProtocolDecl[0], ProtocolDecl.size()); 634 635 DS.SetRangeEnd(EndProtoLoc); 636 637 // Need to support trailing type qualifiers (e.g. "id<p> const"). 638 // If a type specifier follows, it will be diagnosed elsewhere. 639 continue; 640 } 641 642 // type-name 643 case tok::annot_template_id: { 644 TemplateIdAnnotation *TemplateId 645 = static_cast<TemplateIdAnnotation *>(Tok.getAnnotationValue()); 646 if (TemplateId->Kind != TNK_Type_template) { 647 // This template-id does not refer to a type name, so we're 648 // done with the type-specifiers. 649 goto DoneWithDeclSpec; 650 } 651 652 // Turn the template-id annotation token into a type annotation 653 // token, then try again to parse it as a type-specifier. 654 AnnotateTemplateIdTokenAsType(); 655 continue; 656 } 657 658 // GNU attributes support. 659 case tok::kw___attribute: 660 DS.AddAttributes(ParseAttributes()); 661 continue; 662 663 // Microsoft declspec support. 664 case tok::kw___declspec: 665 if (!PP.getLangOptions().Microsoft) 666 goto DoneWithDeclSpec; 667 FuzzyParseMicrosoftDeclSpec(); 668 continue; 669 670 // Microsoft single token adornments. 671 case tok::kw___forceinline: 672 case tok::kw___w64: 673 case tok::kw___cdecl: 674 case tok::kw___stdcall: 675 case tok::kw___fastcall: 676 if (!PP.getLangOptions().Microsoft) 677 goto DoneWithDeclSpec; 678 // Just ignore it. 679 break; 680 681 // storage-class-specifier 682 case tok::kw_typedef: 683 isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_typedef, Loc, PrevSpec); 684 break; 685 case tok::kw_extern: 686 if (DS.isThreadSpecified()) 687 Diag(Tok, diag::ext_thread_before) << "extern"; 688 isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_extern, Loc, PrevSpec); 689 break; 690 case tok::kw___private_extern__: 691 isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_private_extern, Loc, 692 PrevSpec); 693 break; 694 case tok::kw_static: 695 if (DS.isThreadSpecified()) 696 Diag(Tok, diag::ext_thread_before) << "static"; 697 isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_static, Loc, PrevSpec); 698 break; 699 case tok::kw_auto: 700 isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_auto, Loc, PrevSpec); 701 break; 702 case tok::kw_register: 703 isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_register, Loc, PrevSpec); 704 break; 705 case tok::kw_mutable: 706 isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_mutable, Loc, PrevSpec); 707 break; 708 case tok::kw___thread: 709 isInvalid = DS.SetStorageClassSpecThread(Loc, PrevSpec)*2; 710 break; 711 712 continue; 713 714 // function-specifier 715 case tok::kw_inline: 716 isInvalid = DS.SetFunctionSpecInline(Loc, PrevSpec); 717 break; 718 case tok::kw_virtual: 719 isInvalid = DS.SetFunctionSpecVirtual(Loc, PrevSpec); 720 break; 721 case tok::kw_explicit: 722 isInvalid = DS.SetFunctionSpecExplicit(Loc, PrevSpec); 723 break; 724 725 // type-specifier 726 case tok::kw_short: 727 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_short, Loc, PrevSpec); 728 break; 729 case tok::kw_long: 730 if (DS.getTypeSpecWidth() != DeclSpec::TSW_long) 731 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_long, Loc, PrevSpec); 732 else 733 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec); 734 break; 735 case tok::kw_signed: 736 isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_signed, Loc, PrevSpec); 737 break; 738 case tok::kw_unsigned: 739 isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_unsigned, Loc, PrevSpec); 740 break; 741 case tok::kw__Complex: 742 isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_complex, Loc, PrevSpec); 743 break; 744 case tok::kw__Imaginary: 745 isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_imaginary, Loc, PrevSpec); 746 break; 747 case tok::kw_void: 748 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec); 749 break; 750 case tok::kw_char: 751 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec); 752 break; 753 case tok::kw_int: 754 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec); 755 break; 756 case tok::kw_float: 757 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec); 758 break; 759 case tok::kw_double: 760 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec); 761 break; 762 case tok::kw_wchar_t: 763 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec); 764 break; 765 case tok::kw_bool: 766 case tok::kw__Bool: 767 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec); 768 break; 769 case tok::kw__Decimal32: 770 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal32, Loc, PrevSpec); 771 break; 772 case tok::kw__Decimal64: 773 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal64, Loc, PrevSpec); 774 break; 775 case tok::kw__Decimal128: 776 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal128, Loc, PrevSpec); 777 break; 778 779 // class-specifier: 780 case tok::kw_class: 781 case tok::kw_struct: 782 case tok::kw_union: 783 ParseClassSpecifier(DS, TemplateParams, AS); 784 continue; 785 786 // enum-specifier: 787 case tok::kw_enum: 788 ParseEnumSpecifier(DS, AS); 789 continue; 790 791 // cv-qualifier: 792 case tok::kw_const: 793 isInvalid = DS.SetTypeQual(DeclSpec::TQ_const, Loc, PrevSpec,getLang())*2; 794 break; 795 case tok::kw_volatile: 796 isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, 797 getLang())*2; 798 break; 799 case tok::kw_restrict: 800 isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, 801 getLang())*2; 802 break; 803 804 // C++ typename-specifier: 805 case tok::kw_typename: 806 if (TryAnnotateTypeOrScopeToken()) 807 continue; 808 break; 809 810 // GNU typeof support. 811 case tok::kw_typeof: 812 ParseTypeofSpecifier(DS); 813 continue; 814 815 case tok::less: 816 // GCC ObjC supports types like "<SomeProtocol>" as a synonym for 817 // "id<SomeProtocol>". This is hopelessly old fashioned and dangerous, 818 // but we support it. 819 if (DS.hasTypeSpecifier() || !getLang().ObjC1) 820 goto DoneWithDeclSpec; 821 822 { 823 SourceLocation EndProtoLoc; 824 llvm::SmallVector<DeclPtrTy, 8> ProtocolDecl; 825 ParseObjCProtocolReferences(ProtocolDecl, false, EndProtoLoc); 826 DS.setProtocolQualifiers(&ProtocolDecl[0], ProtocolDecl.size()); 827 DS.SetRangeEnd(EndProtoLoc); 828 829 Diag(Loc, diag::warn_objc_protocol_qualifier_missing_id) 830 << SourceRange(Loc, EndProtoLoc); 831 // Need to support trailing type qualifiers (e.g. "id<p> const"). 832 // If a type specifier follows, it will be diagnosed elsewhere. 833 continue; 834 } 835 } 836 // If the specifier combination wasn't legal, issue a diagnostic. 837 if (isInvalid) { 838 assert(PrevSpec && "Method did not return previous specifier!"); 839 // Pick between error or extwarn. 840 unsigned DiagID = isInvalid == 1 ? diag::err_invalid_decl_spec_combination 841 : diag::ext_duplicate_declspec; 842 Diag(Tok, DiagID) << PrevSpec; 843 } 844 DS.SetRangeEnd(Tok.getLocation()); 845 ConsumeToken(); 846 } 847} 848 849/// ParseOptionalTypeSpecifier - Try to parse a single type-specifier. We 850/// primarily follow the C++ grammar with additions for C99 and GNU, 851/// which together subsume the C grammar. Note that the C++ 852/// type-specifier also includes the C type-qualifier (for const, 853/// volatile, and C99 restrict). Returns true if a type-specifier was 854/// found (and parsed), false otherwise. 855/// 856/// type-specifier: [C++ 7.1.5] 857/// simple-type-specifier 858/// class-specifier 859/// enum-specifier 860/// elaborated-type-specifier [TODO] 861/// cv-qualifier 862/// 863/// cv-qualifier: [C++ 7.1.5.1] 864/// 'const' 865/// 'volatile' 866/// [C99] 'restrict' 867/// 868/// simple-type-specifier: [ C++ 7.1.5.2] 869/// '::'[opt] nested-name-specifier[opt] type-name [TODO] 870/// '::'[opt] nested-name-specifier 'template' template-id [TODO] 871/// 'char' 872/// 'wchar_t' 873/// 'bool' 874/// 'short' 875/// 'int' 876/// 'long' 877/// 'signed' 878/// 'unsigned' 879/// 'float' 880/// 'double' 881/// 'void' 882/// [C99] '_Bool' 883/// [C99] '_Complex' 884/// [C99] '_Imaginary' // Removed in TC2? 885/// [GNU] '_Decimal32' 886/// [GNU] '_Decimal64' 887/// [GNU] '_Decimal128' 888/// [GNU] typeof-specifier 889/// [OBJC] class-name objc-protocol-refs[opt] [TODO] 890/// [OBJC] typedef-name objc-protocol-refs[opt] [TODO] 891bool Parser::ParseOptionalTypeSpecifier(DeclSpec &DS, int& isInvalid, 892 const char *&PrevSpec, 893 TemplateParameterLists *TemplateParams){ 894 SourceLocation Loc = Tok.getLocation(); 895 896 switch (Tok.getKind()) { 897 case tok::identifier: // foo::bar 898 case tok::kw_typename: // typename foo::bar 899 // Annotate typenames and C++ scope specifiers. If we get one, just 900 // recurse to handle whatever we get. 901 if (TryAnnotateTypeOrScopeToken()) 902 return ParseOptionalTypeSpecifier(DS, isInvalid, PrevSpec,TemplateParams); 903 // Otherwise, not a type specifier. 904 return false; 905 case tok::coloncolon: // ::foo::bar 906 if (NextToken().is(tok::kw_new) || // ::new 907 NextToken().is(tok::kw_delete)) // ::delete 908 return false; 909 910 // Annotate typenames and C++ scope specifiers. If we get one, just 911 // recurse to handle whatever we get. 912 if (TryAnnotateTypeOrScopeToken()) 913 return ParseOptionalTypeSpecifier(DS, isInvalid, PrevSpec,TemplateParams); 914 // Otherwise, not a type specifier. 915 return false; 916 917 // simple-type-specifier: 918 case tok::annot_typename: { 919 if (Tok.getAnnotationValue()) 920 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, 921 Tok.getAnnotationValue()); 922 else 923 DS.SetTypeSpecError(); 924 DS.SetRangeEnd(Tok.getAnnotationEndLoc()); 925 ConsumeToken(); // The typename 926 927 // Objective-C supports syntax of the form 'id<proto1,proto2>' where 'id' 928 // is a specific typedef and 'itf<proto1,proto2>' where 'itf' is an 929 // Objective-C interface. If we don't have Objective-C or a '<', this is 930 // just a normal reference to a typedef name. 931 if (!Tok.is(tok::less) || !getLang().ObjC1) 932 return true; 933 934 SourceLocation EndProtoLoc; 935 llvm::SmallVector<DeclPtrTy, 8> ProtocolDecl; 936 ParseObjCProtocolReferences(ProtocolDecl, false, EndProtoLoc); 937 DS.setProtocolQualifiers(&ProtocolDecl[0], ProtocolDecl.size()); 938 939 DS.SetRangeEnd(EndProtoLoc); 940 return true; 941 } 942 943 case tok::kw_short: 944 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_short, Loc, PrevSpec); 945 break; 946 case tok::kw_long: 947 if (DS.getTypeSpecWidth() != DeclSpec::TSW_long) 948 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_long, Loc, PrevSpec); 949 else 950 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec); 951 break; 952 case tok::kw_signed: 953 isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_signed, Loc, PrevSpec); 954 break; 955 case tok::kw_unsigned: 956 isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_unsigned, Loc, PrevSpec); 957 break; 958 case tok::kw__Complex: 959 isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_complex, Loc, PrevSpec); 960 break; 961 case tok::kw__Imaginary: 962 isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_imaginary, Loc, PrevSpec); 963 break; 964 case tok::kw_void: 965 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec); 966 break; 967 case tok::kw_char: 968 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec); 969 break; 970 case tok::kw_int: 971 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec); 972 break; 973 case tok::kw_float: 974 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec); 975 break; 976 case tok::kw_double: 977 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec); 978 break; 979 case tok::kw_wchar_t: 980 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec); 981 break; 982 case tok::kw_bool: 983 case tok::kw__Bool: 984 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec); 985 break; 986 case tok::kw__Decimal32: 987 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal32, Loc, PrevSpec); 988 break; 989 case tok::kw__Decimal64: 990 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal64, Loc, PrevSpec); 991 break; 992 case tok::kw__Decimal128: 993 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal128, Loc, PrevSpec); 994 break; 995 996 // class-specifier: 997 case tok::kw_class: 998 case tok::kw_struct: 999 case tok::kw_union: 1000 ParseClassSpecifier(DS, TemplateParams); 1001 return true; 1002 1003 // enum-specifier: 1004 case tok::kw_enum: 1005 ParseEnumSpecifier(DS); 1006 return true; 1007 1008 // cv-qualifier: 1009 case tok::kw_const: 1010 isInvalid = DS.SetTypeQual(DeclSpec::TQ_const , Loc, PrevSpec, 1011 getLang())*2; 1012 break; 1013 case tok::kw_volatile: 1014 isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, 1015 getLang())*2; 1016 break; 1017 case tok::kw_restrict: 1018 isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, 1019 getLang())*2; 1020 break; 1021 1022 // GNU typeof support. 1023 case tok::kw_typeof: 1024 ParseTypeofSpecifier(DS); 1025 return true; 1026 1027 case tok::kw___cdecl: 1028 case tok::kw___stdcall: 1029 case tok::kw___fastcall: 1030 if (!PP.getLangOptions().Microsoft) return false; 1031 ConsumeToken(); 1032 return true; 1033 1034 default: 1035 // Not a type-specifier; do nothing. 1036 return false; 1037 } 1038 1039 // If the specifier combination wasn't legal, issue a diagnostic. 1040 if (isInvalid) { 1041 assert(PrevSpec && "Method did not return previous specifier!"); 1042 // Pick between error or extwarn. 1043 unsigned DiagID = isInvalid == 1 ? diag::err_invalid_decl_spec_combination 1044 : diag::ext_duplicate_declspec; 1045 Diag(Tok, DiagID) << PrevSpec; 1046 } 1047 DS.SetRangeEnd(Tok.getLocation()); 1048 ConsumeToken(); // whatever we parsed above. 1049 return true; 1050} 1051 1052/// ParseStructDeclaration - Parse a struct declaration without the terminating 1053/// semicolon. 1054/// 1055/// struct-declaration: 1056/// specifier-qualifier-list struct-declarator-list 1057/// [GNU] __extension__ struct-declaration 1058/// [GNU] specifier-qualifier-list 1059/// struct-declarator-list: 1060/// struct-declarator 1061/// struct-declarator-list ',' struct-declarator 1062/// [GNU] struct-declarator-list ',' attributes[opt] struct-declarator 1063/// struct-declarator: 1064/// declarator 1065/// [GNU] declarator attributes[opt] 1066/// declarator[opt] ':' constant-expression 1067/// [GNU] declarator[opt] ':' constant-expression attributes[opt] 1068/// 1069void Parser:: 1070ParseStructDeclaration(DeclSpec &DS, 1071 llvm::SmallVectorImpl<FieldDeclarator> &Fields) { 1072 if (Tok.is(tok::kw___extension__)) { 1073 // __extension__ silences extension warnings in the subexpression. 1074 ExtensionRAIIObject O(Diags); // Use RAII to do this. 1075 ConsumeToken(); 1076 return ParseStructDeclaration(DS, Fields); 1077 } 1078 1079 // Parse the common specifier-qualifiers-list piece. 1080 SourceLocation DSStart = Tok.getLocation(); 1081 ParseSpecifierQualifierList(DS); 1082 1083 // If there are no declarators, this is a free-standing declaration 1084 // specifier. Let the actions module cope with it. 1085 if (Tok.is(tok::semi)) { 1086 Actions.ParsedFreeStandingDeclSpec(CurScope, DS); 1087 return; 1088 } 1089 1090 // Read struct-declarators until we find the semicolon. 1091 Fields.push_back(FieldDeclarator(DS)); 1092 while (1) { 1093 FieldDeclarator &DeclaratorInfo = Fields.back(); 1094 1095 /// struct-declarator: declarator 1096 /// struct-declarator: declarator[opt] ':' constant-expression 1097 if (Tok.isNot(tok::colon)) 1098 ParseDeclarator(DeclaratorInfo.D); 1099 1100 if (Tok.is(tok::colon)) { 1101 ConsumeToken(); 1102 OwningExprResult Res(ParseConstantExpression()); 1103 if (Res.isInvalid()) 1104 SkipUntil(tok::semi, true, true); 1105 else 1106 DeclaratorInfo.BitfieldSize = Res.release(); 1107 } 1108 1109 // If attributes exist after the declarator, parse them. 1110 if (Tok.is(tok::kw___attribute)) { 1111 SourceLocation Loc; 1112 AttributeList *AttrList = ParseAttributes(&Loc); 1113 DeclaratorInfo.D.AddAttributes(AttrList, Loc); 1114 } 1115 1116 // If we don't have a comma, it is either the end of the list (a ';') 1117 // or an error, bail out. 1118 if (Tok.isNot(tok::comma)) 1119 return; 1120 1121 // Consume the comma. 1122 ConsumeToken(); 1123 1124 // Parse the next declarator. 1125 Fields.push_back(FieldDeclarator(DS)); 1126 1127 // Attributes are only allowed on the second declarator. 1128 if (Tok.is(tok::kw___attribute)) { 1129 SourceLocation Loc; 1130 AttributeList *AttrList = ParseAttributes(&Loc); 1131 Fields.back().D.AddAttributes(AttrList, Loc); 1132 } 1133 } 1134} 1135 1136/// ParseStructUnionBody 1137/// struct-contents: 1138/// struct-declaration-list 1139/// [EXT] empty 1140/// [GNU] "struct-declaration-list" without terminatoring ';' 1141/// struct-declaration-list: 1142/// struct-declaration 1143/// struct-declaration-list struct-declaration 1144/// [OBC] '@' 'defs' '(' class-name ')' 1145/// 1146void Parser::ParseStructUnionBody(SourceLocation RecordLoc, 1147 unsigned TagType, DeclPtrTy TagDecl) { 1148 PrettyStackTraceActionsDecl CrashInfo(TagDecl, RecordLoc, Actions, 1149 PP.getSourceManager(), 1150 "parsing struct/union body"); 1151 1152 SourceLocation LBraceLoc = ConsumeBrace(); 1153 1154 ParseScope StructScope(this, Scope::ClassScope|Scope::DeclScope); 1155 Actions.ActOnTagStartDefinition(CurScope, TagDecl); 1156 1157 // Empty structs are an extension in C (C99 6.7.2.1p7), but are allowed in 1158 // C++. 1159 if (Tok.is(tok::r_brace) && !getLang().CPlusPlus) 1160 Diag(Tok, diag::ext_empty_struct_union_enum) 1161 << DeclSpec::getSpecifierName((DeclSpec::TST)TagType); 1162 1163 llvm::SmallVector<DeclPtrTy, 32> FieldDecls; 1164 llvm::SmallVector<FieldDeclarator, 8> FieldDeclarators; 1165 1166 // While we still have something to read, read the declarations in the struct. 1167 while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) { 1168 // Each iteration of this loop reads one struct-declaration. 1169 1170 // Check for extraneous top-level semicolon. 1171 if (Tok.is(tok::semi)) { 1172 Diag(Tok, diag::ext_extra_struct_semi); 1173 ConsumeToken(); 1174 continue; 1175 } 1176 1177 // Parse all the comma separated declarators. 1178 DeclSpec DS; 1179 FieldDeclarators.clear(); 1180 if (!Tok.is(tok::at)) { 1181 ParseStructDeclaration(DS, FieldDeclarators); 1182 1183 // Convert them all to fields. 1184 for (unsigned i = 0, e = FieldDeclarators.size(); i != e; ++i) { 1185 FieldDeclarator &FD = FieldDeclarators[i]; 1186 // Install the declarator into the current TagDecl. 1187 DeclPtrTy Field = Actions.ActOnField(CurScope, TagDecl, 1188 DS.getSourceRange().getBegin(), 1189 FD.D, FD.BitfieldSize); 1190 FieldDecls.push_back(Field); 1191 } 1192 } else { // Handle @defs 1193 ConsumeToken(); 1194 if (!Tok.isObjCAtKeyword(tok::objc_defs)) { 1195 Diag(Tok, diag::err_unexpected_at); 1196 SkipUntil(tok::semi, true, true); 1197 continue; 1198 } 1199 ConsumeToken(); 1200 ExpectAndConsume(tok::l_paren, diag::err_expected_lparen); 1201 if (!Tok.is(tok::identifier)) { 1202 Diag(Tok, diag::err_expected_ident); 1203 SkipUntil(tok::semi, true, true); 1204 continue; 1205 } 1206 llvm::SmallVector<DeclPtrTy, 16> Fields; 1207 Actions.ActOnDefs(CurScope, TagDecl, Tok.getLocation(), 1208 Tok.getIdentifierInfo(), Fields); 1209 FieldDecls.insert(FieldDecls.end(), Fields.begin(), Fields.end()); 1210 ConsumeToken(); 1211 ExpectAndConsume(tok::r_paren, diag::err_expected_rparen); 1212 } 1213 1214 if (Tok.is(tok::semi)) { 1215 ConsumeToken(); 1216 } else if (Tok.is(tok::r_brace)) { 1217 Diag(Tok, diag::ext_expected_semi_decl_list); 1218 break; 1219 } else { 1220 Diag(Tok, diag::err_expected_semi_decl_list); 1221 // Skip to end of block or statement 1222 SkipUntil(tok::r_brace, true, true); 1223 } 1224 } 1225 1226 SourceLocation RBraceLoc = MatchRHSPunctuation(tok::r_brace, LBraceLoc); 1227 1228 AttributeList *AttrList = 0; 1229 // If attributes exist after struct contents, parse them. 1230 if (Tok.is(tok::kw___attribute)) 1231 AttrList = ParseAttributes(); 1232 1233 Actions.ActOnFields(CurScope, 1234 RecordLoc,TagDecl,&FieldDecls[0],FieldDecls.size(), 1235 LBraceLoc, RBraceLoc, 1236 AttrList); 1237 StructScope.Exit(); 1238 Actions.ActOnTagFinishDefinition(CurScope, TagDecl); 1239} 1240 1241 1242/// ParseEnumSpecifier 1243/// enum-specifier: [C99 6.7.2.2] 1244/// 'enum' identifier[opt] '{' enumerator-list '}' 1245///[C99/C++]'enum' identifier[opt] '{' enumerator-list ',' '}' 1246/// [GNU] 'enum' attributes[opt] identifier[opt] '{' enumerator-list ',' [opt] 1247/// '}' attributes[opt] 1248/// 'enum' identifier 1249/// [GNU] 'enum' attributes[opt] identifier 1250/// 1251/// [C++] elaborated-type-specifier: 1252/// [C++] 'enum' '::'[opt] nested-name-specifier[opt] identifier 1253/// 1254void Parser::ParseEnumSpecifier(DeclSpec &DS, AccessSpecifier AS) { 1255 assert(Tok.is(tok::kw_enum) && "Not an enum specifier"); 1256 SourceLocation StartLoc = ConsumeToken(); 1257 1258 // Parse the tag portion of this. 1259 1260 AttributeList *Attr = 0; 1261 // If attributes exist after tag, parse them. 1262 if (Tok.is(tok::kw___attribute)) 1263 Attr = ParseAttributes(); 1264 1265 CXXScopeSpec SS; 1266 if (getLang().CPlusPlus && ParseOptionalCXXScopeSpecifier(SS)) { 1267 if (Tok.isNot(tok::identifier)) { 1268 Diag(Tok, diag::err_expected_ident); 1269 if (Tok.isNot(tok::l_brace)) { 1270 // Has no name and is not a definition. 1271 // Skip the rest of this declarator, up until the comma or semicolon. 1272 SkipUntil(tok::comma, true); 1273 return; 1274 } 1275 } 1276 } 1277 1278 // Must have either 'enum name' or 'enum {...}'. 1279 if (Tok.isNot(tok::identifier) && Tok.isNot(tok::l_brace)) { 1280 Diag(Tok, diag::err_expected_ident_lbrace); 1281 1282 // Skip the rest of this declarator, up until the comma or semicolon. 1283 SkipUntil(tok::comma, true); 1284 return; 1285 } 1286 1287 // If an identifier is present, consume and remember it. 1288 IdentifierInfo *Name = 0; 1289 SourceLocation NameLoc; 1290 if (Tok.is(tok::identifier)) { 1291 Name = Tok.getIdentifierInfo(); 1292 NameLoc = ConsumeToken(); 1293 } 1294 1295 // There are three options here. If we have 'enum foo;', then this is a 1296 // forward declaration. If we have 'enum foo {...' then this is a 1297 // definition. Otherwise we have something like 'enum foo xyz', a reference. 1298 // 1299 // This is needed to handle stuff like this right (C99 6.7.2.3p11): 1300 // enum foo {..}; void bar() { enum foo; } <- new foo in bar. 1301 // enum foo {..}; void bar() { enum foo x; } <- use of old foo. 1302 // 1303 Action::TagKind TK; 1304 if (Tok.is(tok::l_brace)) 1305 TK = Action::TK_Definition; 1306 else if (Tok.is(tok::semi)) 1307 TK = Action::TK_Declaration; 1308 else 1309 TK = Action::TK_Reference; 1310 DeclPtrTy TagDecl = Actions.ActOnTag(CurScope, DeclSpec::TST_enum, TK, 1311 StartLoc, SS, Name, NameLoc, Attr, AS); 1312 1313 if (Tok.is(tok::l_brace)) 1314 ParseEnumBody(StartLoc, TagDecl); 1315 1316 // TODO: semantic analysis on the declspec for enums. 1317 const char *PrevSpec = 0; 1318 if (DS.SetTypeSpecType(DeclSpec::TST_enum, StartLoc, PrevSpec, 1319 TagDecl.getAs<void>())) 1320 Diag(StartLoc, diag::err_invalid_decl_spec_combination) << PrevSpec; 1321} 1322 1323/// ParseEnumBody - Parse a {} enclosed enumerator-list. 1324/// enumerator-list: 1325/// enumerator 1326/// enumerator-list ',' enumerator 1327/// enumerator: 1328/// enumeration-constant 1329/// enumeration-constant '=' constant-expression 1330/// enumeration-constant: 1331/// identifier 1332/// 1333void Parser::ParseEnumBody(SourceLocation StartLoc, DeclPtrTy EnumDecl) { 1334 // Enter the scope of the enum body and start the definition. 1335 ParseScope EnumScope(this, Scope::DeclScope); 1336 Actions.ActOnTagStartDefinition(CurScope, EnumDecl); 1337 1338 SourceLocation LBraceLoc = ConsumeBrace(); 1339 1340 // C does not allow an empty enumerator-list, C++ does [dcl.enum]. 1341 if (Tok.is(tok::r_brace) && !getLang().CPlusPlus) 1342 Diag(Tok, diag::ext_empty_struct_union_enum) << "enum"; 1343 1344 llvm::SmallVector<DeclPtrTy, 32> EnumConstantDecls; 1345 1346 DeclPtrTy LastEnumConstDecl; 1347 1348 // Parse the enumerator-list. 1349 while (Tok.is(tok::identifier)) { 1350 IdentifierInfo *Ident = Tok.getIdentifierInfo(); 1351 SourceLocation IdentLoc = ConsumeToken(); 1352 1353 SourceLocation EqualLoc; 1354 OwningExprResult AssignedVal(Actions); 1355 if (Tok.is(tok::equal)) { 1356 EqualLoc = ConsumeToken(); 1357 AssignedVal = ParseConstantExpression(); 1358 if (AssignedVal.isInvalid()) 1359 SkipUntil(tok::comma, tok::r_brace, true, true); 1360 } 1361 1362 // Install the enumerator constant into EnumDecl. 1363 DeclPtrTy EnumConstDecl = Actions.ActOnEnumConstant(CurScope, EnumDecl, 1364 LastEnumConstDecl, 1365 IdentLoc, Ident, 1366 EqualLoc, 1367 AssignedVal.release()); 1368 EnumConstantDecls.push_back(EnumConstDecl); 1369 LastEnumConstDecl = EnumConstDecl; 1370 1371 if (Tok.isNot(tok::comma)) 1372 break; 1373 SourceLocation CommaLoc = ConsumeToken(); 1374 1375 if (Tok.isNot(tok::identifier) && !getLang().C99) 1376 Diag(CommaLoc, diag::ext_c99_enumerator_list_comma); 1377 } 1378 1379 // Eat the }. 1380 MatchRHSPunctuation(tok::r_brace, LBraceLoc); 1381 1382 Actions.ActOnEnumBody(StartLoc, EnumDecl, &EnumConstantDecls[0], 1383 EnumConstantDecls.size()); 1384 1385 Action::AttrTy *AttrList = 0; 1386 // If attributes exist after the identifier list, parse them. 1387 if (Tok.is(tok::kw___attribute)) 1388 AttrList = ParseAttributes(); // FIXME: where do they do? 1389 1390 EnumScope.Exit(); 1391 Actions.ActOnTagFinishDefinition(CurScope, EnumDecl); 1392} 1393 1394/// isTypeSpecifierQualifier - Return true if the current token could be the 1395/// start of a type-qualifier-list. 1396bool Parser::isTypeQualifier() const { 1397 switch (Tok.getKind()) { 1398 default: return false; 1399 // type-qualifier 1400 case tok::kw_const: 1401 case tok::kw_volatile: 1402 case tok::kw_restrict: 1403 return true; 1404 } 1405} 1406 1407/// isTypeSpecifierQualifier - Return true if the current token could be the 1408/// start of a specifier-qualifier-list. 1409bool Parser::isTypeSpecifierQualifier() { 1410 switch (Tok.getKind()) { 1411 default: return false; 1412 1413 case tok::identifier: // foo::bar 1414 case tok::kw_typename: // typename T::type 1415 // Annotate typenames and C++ scope specifiers. If we get one, just 1416 // recurse to handle whatever we get. 1417 if (TryAnnotateTypeOrScopeToken()) 1418 return isTypeSpecifierQualifier(); 1419 // Otherwise, not a type specifier. 1420 return false; 1421 1422 case tok::coloncolon: // ::foo::bar 1423 if (NextToken().is(tok::kw_new) || // ::new 1424 NextToken().is(tok::kw_delete)) // ::delete 1425 return false; 1426 1427 // Annotate typenames and C++ scope specifiers. If we get one, just 1428 // recurse to handle whatever we get. 1429 if (TryAnnotateTypeOrScopeToken()) 1430 return isTypeSpecifierQualifier(); 1431 // Otherwise, not a type specifier. 1432 return false; 1433 1434 // GNU attributes support. 1435 case tok::kw___attribute: 1436 // GNU typeof support. 1437 case tok::kw_typeof: 1438 1439 // type-specifiers 1440 case tok::kw_short: 1441 case tok::kw_long: 1442 case tok::kw_signed: 1443 case tok::kw_unsigned: 1444 case tok::kw__Complex: 1445 case tok::kw__Imaginary: 1446 case tok::kw_void: 1447 case tok::kw_char: 1448 case tok::kw_wchar_t: 1449 case tok::kw_int: 1450 case tok::kw_float: 1451 case tok::kw_double: 1452 case tok::kw_bool: 1453 case tok::kw__Bool: 1454 case tok::kw__Decimal32: 1455 case tok::kw__Decimal64: 1456 case tok::kw__Decimal128: 1457 1458 // struct-or-union-specifier (C99) or class-specifier (C++) 1459 case tok::kw_class: 1460 case tok::kw_struct: 1461 case tok::kw_union: 1462 // enum-specifier 1463 case tok::kw_enum: 1464 1465 // type-qualifier 1466 case tok::kw_const: 1467 case tok::kw_volatile: 1468 case tok::kw_restrict: 1469 1470 // typedef-name 1471 case tok::annot_typename: 1472 return true; 1473 1474 // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'. 1475 case tok::less: 1476 return getLang().ObjC1; 1477 1478 case tok::kw___cdecl: 1479 case tok::kw___stdcall: 1480 case tok::kw___fastcall: 1481 return PP.getLangOptions().Microsoft; 1482 } 1483} 1484 1485/// isDeclarationSpecifier() - Return true if the current token is part of a 1486/// declaration specifier. 1487bool Parser::isDeclarationSpecifier() { 1488 switch (Tok.getKind()) { 1489 default: return false; 1490 1491 case tok::identifier: // foo::bar 1492 // Unfortunate hack to support "Class.factoryMethod" notation. 1493 if (getLang().ObjC1 && NextToken().is(tok::period)) 1494 return false; 1495 // Fall through 1496 1497 case tok::kw_typename: // typename T::type 1498 // Annotate typenames and C++ scope specifiers. If we get one, just 1499 // recurse to handle whatever we get. 1500 if (TryAnnotateTypeOrScopeToken()) 1501 return isDeclarationSpecifier(); 1502 // Otherwise, not a declaration specifier. 1503 return false; 1504 case tok::coloncolon: // ::foo::bar 1505 if (NextToken().is(tok::kw_new) || // ::new 1506 NextToken().is(tok::kw_delete)) // ::delete 1507 return false; 1508 1509 // Annotate typenames and C++ scope specifiers. If we get one, just 1510 // recurse to handle whatever we get. 1511 if (TryAnnotateTypeOrScopeToken()) 1512 return isDeclarationSpecifier(); 1513 // Otherwise, not a declaration specifier. 1514 return false; 1515 1516 // storage-class-specifier 1517 case tok::kw_typedef: 1518 case tok::kw_extern: 1519 case tok::kw___private_extern__: 1520 case tok::kw_static: 1521 case tok::kw_auto: 1522 case tok::kw_register: 1523 case tok::kw___thread: 1524 1525 // type-specifiers 1526 case tok::kw_short: 1527 case tok::kw_long: 1528 case tok::kw_signed: 1529 case tok::kw_unsigned: 1530 case tok::kw__Complex: 1531 case tok::kw__Imaginary: 1532 case tok::kw_void: 1533 case tok::kw_char: 1534 case tok::kw_wchar_t: 1535 case tok::kw_int: 1536 case tok::kw_float: 1537 case tok::kw_double: 1538 case tok::kw_bool: 1539 case tok::kw__Bool: 1540 case tok::kw__Decimal32: 1541 case tok::kw__Decimal64: 1542 case tok::kw__Decimal128: 1543 1544 // struct-or-union-specifier (C99) or class-specifier (C++) 1545 case tok::kw_class: 1546 case tok::kw_struct: 1547 case tok::kw_union: 1548 // enum-specifier 1549 case tok::kw_enum: 1550 1551 // type-qualifier 1552 case tok::kw_const: 1553 case tok::kw_volatile: 1554 case tok::kw_restrict: 1555 1556 // function-specifier 1557 case tok::kw_inline: 1558 case tok::kw_virtual: 1559 case tok::kw_explicit: 1560 1561 // typedef-name 1562 case tok::annot_typename: 1563 1564 // GNU typeof support. 1565 case tok::kw_typeof: 1566 1567 // GNU attributes. 1568 case tok::kw___attribute: 1569 return true; 1570 1571 // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'. 1572 case tok::less: 1573 return getLang().ObjC1; 1574 1575 case tok::kw___declspec: 1576 case tok::kw___cdecl: 1577 case tok::kw___stdcall: 1578 case tok::kw___fastcall: 1579 return PP.getLangOptions().Microsoft; 1580 } 1581} 1582 1583 1584/// ParseTypeQualifierListOpt 1585/// type-qualifier-list: [C99 6.7.5] 1586/// type-qualifier 1587/// [GNU] attributes [ only if AttributesAllowed=true ] 1588/// type-qualifier-list type-qualifier 1589/// [GNU] type-qualifier-list attributes [ only if AttributesAllowed=true ] 1590/// 1591void Parser::ParseTypeQualifierListOpt(DeclSpec &DS, bool AttributesAllowed) { 1592 while (1) { 1593 int isInvalid = false; 1594 const char *PrevSpec = 0; 1595 SourceLocation Loc = Tok.getLocation(); 1596 1597 switch (Tok.getKind()) { 1598 case tok::kw_const: 1599 isInvalid = DS.SetTypeQual(DeclSpec::TQ_const , Loc, PrevSpec, 1600 getLang())*2; 1601 break; 1602 case tok::kw_volatile: 1603 isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, 1604 getLang())*2; 1605 break; 1606 case tok::kw_restrict: 1607 isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, 1608 getLang())*2; 1609 break; 1610 case tok::kw___ptr64: 1611 case tok::kw___cdecl: 1612 case tok::kw___stdcall: 1613 case tok::kw___fastcall: 1614 if (!PP.getLangOptions().Microsoft) 1615 goto DoneWithTypeQuals; 1616 // Just ignore it. 1617 break; 1618 case tok::kw___attribute: 1619 if (AttributesAllowed) { 1620 DS.AddAttributes(ParseAttributes()); 1621 continue; // do *not* consume the next token! 1622 } 1623 // otherwise, FALL THROUGH! 1624 default: 1625 DoneWithTypeQuals: 1626 // If this is not a type-qualifier token, we're done reading type 1627 // qualifiers. First verify that DeclSpec's are consistent. 1628 DS.Finish(Diags, PP.getSourceManager(), getLang()); 1629 return; 1630 } 1631 1632 // If the specifier combination wasn't legal, issue a diagnostic. 1633 if (isInvalid) { 1634 assert(PrevSpec && "Method did not return previous specifier!"); 1635 // Pick between error or extwarn. 1636 unsigned DiagID = isInvalid == 1 ? diag::err_invalid_decl_spec_combination 1637 : diag::ext_duplicate_declspec; 1638 Diag(Tok, DiagID) << PrevSpec; 1639 } 1640 ConsumeToken(); 1641 } 1642} 1643 1644 1645/// ParseDeclarator - Parse and verify a newly-initialized declarator. 1646/// 1647void Parser::ParseDeclarator(Declarator &D) { 1648 /// This implements the 'declarator' production in the C grammar, then checks 1649 /// for well-formedness and issues diagnostics. 1650 ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator); 1651} 1652 1653/// ParseDeclaratorInternal - Parse a C or C++ declarator. The direct-declarator 1654/// is parsed by the function passed to it. Pass null, and the direct-declarator 1655/// isn't parsed at all, making this function effectively parse the C++ 1656/// ptr-operator production. 1657/// 1658/// declarator: [C99 6.7.5] [C++ 8p4, dcl.decl] 1659/// [C] pointer[opt] direct-declarator 1660/// [C++] direct-declarator 1661/// [C++] ptr-operator declarator 1662/// 1663/// pointer: [C99 6.7.5] 1664/// '*' type-qualifier-list[opt] 1665/// '*' type-qualifier-list[opt] pointer 1666/// 1667/// ptr-operator: 1668/// '*' cv-qualifier-seq[opt] 1669/// '&' 1670/// [C++0x] '&&' 1671/// [GNU] '&' restrict[opt] attributes[opt] 1672/// [GNU?] '&&' restrict[opt] attributes[opt] 1673/// '::'[opt] nested-name-specifier '*' cv-qualifier-seq[opt] 1674void Parser::ParseDeclaratorInternal(Declarator &D, 1675 DirectDeclParseFunction DirectDeclParser) { 1676 1677 // C++ member pointers start with a '::' or a nested-name. 1678 // Member pointers get special handling, since there's no place for the 1679 // scope spec in the generic path below. 1680 if (getLang().CPlusPlus && 1681 (Tok.is(tok::coloncolon) || Tok.is(tok::identifier) || 1682 Tok.is(tok::annot_cxxscope))) { 1683 CXXScopeSpec SS; 1684 if (ParseOptionalCXXScopeSpecifier(SS)) { 1685 if(Tok.isNot(tok::star)) { 1686 // The scope spec really belongs to the direct-declarator. 1687 D.getCXXScopeSpec() = SS; 1688 if (DirectDeclParser) 1689 (this->*DirectDeclParser)(D); 1690 return; 1691 } 1692 1693 SourceLocation Loc = ConsumeToken(); 1694 D.SetRangeEnd(Loc); 1695 DeclSpec DS; 1696 ParseTypeQualifierListOpt(DS); 1697 D.ExtendWithDeclSpec(DS); 1698 1699 // Recurse to parse whatever is left. 1700 ParseDeclaratorInternal(D, DirectDeclParser); 1701 1702 // Sema will have to catch (syntactically invalid) pointers into global 1703 // scope. It has to catch pointers into namespace scope anyway. 1704 D.AddTypeInfo(DeclaratorChunk::getMemberPointer(SS,DS.getTypeQualifiers(), 1705 Loc, DS.TakeAttributes()), 1706 /* Don't replace range end. */SourceLocation()); 1707 return; 1708 } 1709 } 1710 1711 tok::TokenKind Kind = Tok.getKind(); 1712 // Not a pointer, C++ reference, or block. 1713 if (Kind != tok::star && Kind != tok::caret && 1714 (Kind != tok::amp || !getLang().CPlusPlus) && 1715 // We parse rvalue refs in C++03, because otherwise the errors are scary. 1716 (Kind != tok::ampamp || !getLang().CPlusPlus)) { 1717 if (DirectDeclParser) 1718 (this->*DirectDeclParser)(D); 1719 return; 1720 } 1721 1722 // Otherwise, '*' -> pointer, '^' -> block, '&' -> lvalue reference, 1723 // '&&' -> rvalue reference 1724 SourceLocation Loc = ConsumeToken(); // Eat the *, ^, & or &&. 1725 D.SetRangeEnd(Loc); 1726 1727 if (Kind == tok::star || Kind == tok::caret) { 1728 // Is a pointer. 1729 DeclSpec DS; 1730 1731 ParseTypeQualifierListOpt(DS); 1732 D.ExtendWithDeclSpec(DS); 1733 1734 // Recursively parse the declarator. 1735 ParseDeclaratorInternal(D, DirectDeclParser); 1736 if (Kind == tok::star) 1737 // Remember that we parsed a pointer type, and remember the type-quals. 1738 D.AddTypeInfo(DeclaratorChunk::getPointer(DS.getTypeQualifiers(), Loc, 1739 DS.TakeAttributes()), 1740 SourceLocation()); 1741 else 1742 // Remember that we parsed a Block type, and remember the type-quals. 1743 D.AddTypeInfo(DeclaratorChunk::getBlockPointer(DS.getTypeQualifiers(), 1744 Loc), 1745 SourceLocation()); 1746 } else { 1747 // Is a reference 1748 DeclSpec DS; 1749 1750 // Complain about rvalue references in C++03, but then go on and build 1751 // the declarator. 1752 if (Kind == tok::ampamp && !getLang().CPlusPlus0x) 1753 Diag(Loc, diag::err_rvalue_reference); 1754 1755 // C++ 8.3.2p1: cv-qualified references are ill-formed except when the 1756 // cv-qualifiers are introduced through the use of a typedef or of a 1757 // template type argument, in which case the cv-qualifiers are ignored. 1758 // 1759 // [GNU] Retricted references are allowed. 1760 // [GNU] Attributes on references are allowed. 1761 ParseTypeQualifierListOpt(DS); 1762 D.ExtendWithDeclSpec(DS); 1763 1764 if (DS.getTypeQualifiers() != DeclSpec::TQ_unspecified) { 1765 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 1766 Diag(DS.getConstSpecLoc(), 1767 diag::err_invalid_reference_qualifier_application) << "const"; 1768 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 1769 Diag(DS.getVolatileSpecLoc(), 1770 diag::err_invalid_reference_qualifier_application) << "volatile"; 1771 } 1772 1773 // Recursively parse the declarator. 1774 ParseDeclaratorInternal(D, DirectDeclParser); 1775 1776 if (D.getNumTypeObjects() > 0) { 1777 // C++ [dcl.ref]p4: There shall be no references to references. 1778 DeclaratorChunk& InnerChunk = D.getTypeObject(D.getNumTypeObjects() - 1); 1779 if (InnerChunk.Kind == DeclaratorChunk::Reference) { 1780 if (const IdentifierInfo *II = D.getIdentifier()) 1781 Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference) 1782 << II; 1783 else 1784 Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference) 1785 << "type name"; 1786 1787 // Once we've complained about the reference-to-reference, we 1788 // can go ahead and build the (technically ill-formed) 1789 // declarator: reference collapsing will take care of it. 1790 } 1791 } 1792 1793 // Remember that we parsed a reference type. It doesn't have type-quals. 1794 D.AddTypeInfo(DeclaratorChunk::getReference(DS.getTypeQualifiers(), Loc, 1795 DS.TakeAttributes(), 1796 Kind == tok::amp), 1797 SourceLocation()); 1798 } 1799} 1800 1801/// ParseDirectDeclarator 1802/// direct-declarator: [C99 6.7.5] 1803/// [C99] identifier 1804/// '(' declarator ')' 1805/// [GNU] '(' attributes declarator ')' 1806/// [C90] direct-declarator '[' constant-expression[opt] ']' 1807/// [C99] direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']' 1808/// [C99] direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']' 1809/// [C99] direct-declarator '[' type-qual-list 'static' assignment-expr ']' 1810/// [C99] direct-declarator '[' type-qual-list[opt] '*' ']' 1811/// direct-declarator '(' parameter-type-list ')' 1812/// direct-declarator '(' identifier-list[opt] ')' 1813/// [GNU] direct-declarator '(' parameter-forward-declarations 1814/// parameter-type-list[opt] ')' 1815/// [C++] direct-declarator '(' parameter-declaration-clause ')' 1816/// cv-qualifier-seq[opt] exception-specification[opt] 1817/// [C++] declarator-id 1818/// 1819/// declarator-id: [C++ 8] 1820/// id-expression 1821/// '::'[opt] nested-name-specifier[opt] type-name 1822/// 1823/// id-expression: [C++ 5.1] 1824/// unqualified-id 1825/// qualified-id [TODO] 1826/// 1827/// unqualified-id: [C++ 5.1] 1828/// identifier 1829/// operator-function-id 1830/// conversion-function-id [TODO] 1831/// '~' class-name 1832/// template-id 1833/// 1834void Parser::ParseDirectDeclarator(Declarator &D) { 1835 DeclaratorScopeObj DeclScopeObj(*this, D.getCXXScopeSpec()); 1836 1837 if (getLang().CPlusPlus) { 1838 if (D.mayHaveIdentifier()) { 1839 // ParseDeclaratorInternal might already have parsed the scope. 1840 bool afterCXXScope = D.getCXXScopeSpec().isSet() || 1841 ParseOptionalCXXScopeSpecifier(D.getCXXScopeSpec()); 1842 if (afterCXXScope) { 1843 // Change the declaration context for name lookup, until this function 1844 // is exited (and the declarator has been parsed). 1845 DeclScopeObj.EnterDeclaratorScope(); 1846 } 1847 1848 if (Tok.is(tok::identifier)) { 1849 assert(Tok.getIdentifierInfo() && "Not an identifier?"); 1850 1851 // If this identifier is the name of the current class, it's a 1852 // constructor name. 1853 if (Actions.isCurrentClassName(*Tok.getIdentifierInfo(),CurScope)){ 1854 D.setConstructor(Actions.getTypeName(*Tok.getIdentifierInfo(), 1855 Tok.getLocation(), CurScope), 1856 Tok.getLocation()); 1857 // This is a normal identifier. 1858 } else 1859 D.SetIdentifier(Tok.getIdentifierInfo(), Tok.getLocation()); 1860 ConsumeToken(); 1861 goto PastIdentifier; 1862 } else if (Tok.is(tok::annot_template_id)) { 1863 TemplateIdAnnotation *TemplateId 1864 = static_cast<TemplateIdAnnotation *>(Tok.getAnnotationValue()); 1865 1866 // FIXME: Could this template-id name a constructor? 1867 1868 // FIXME: This is an egregious hack, where we silently ignore 1869 // the specialization (which should be a function template 1870 // specialization name) and use the name instead. This hack 1871 // will go away when we have support for function 1872 // specializations. 1873 D.SetIdentifier(TemplateId->Name, Tok.getLocation()); 1874 TemplateId->Destroy(); 1875 ConsumeToken(); 1876 goto PastIdentifier; 1877 } else if (Tok.is(tok::kw_operator)) { 1878 SourceLocation OperatorLoc = Tok.getLocation(); 1879 SourceLocation EndLoc; 1880 1881 // First try the name of an overloaded operator 1882 if (OverloadedOperatorKind Op = TryParseOperatorFunctionId(&EndLoc)) { 1883 D.setOverloadedOperator(Op, OperatorLoc, EndLoc); 1884 } else { 1885 // This must be a conversion function (C++ [class.conv.fct]). 1886 if (TypeTy *ConvType = ParseConversionFunctionId(&EndLoc)) 1887 D.setConversionFunction(ConvType, OperatorLoc, EndLoc); 1888 else { 1889 D.SetIdentifier(0, Tok.getLocation()); 1890 } 1891 } 1892 goto PastIdentifier; 1893 } else if (Tok.is(tok::tilde)) { 1894 // This should be a C++ destructor. 1895 SourceLocation TildeLoc = ConsumeToken(); 1896 if (Tok.is(tok::identifier)) { 1897 // FIXME: Inaccurate. 1898 SourceLocation NameLoc = Tok.getLocation(); 1899 SourceLocation EndLoc; 1900 TypeResult Type = ParseClassName(EndLoc); 1901 if (Type.isInvalid()) 1902 D.SetIdentifier(0, TildeLoc); 1903 else 1904 D.setDestructor(Type.get(), TildeLoc, NameLoc); 1905 } else { 1906 Diag(Tok, diag::err_expected_class_name); 1907 D.SetIdentifier(0, TildeLoc); 1908 } 1909 goto PastIdentifier; 1910 } 1911 1912 // If we reached this point, token is not identifier and not '~'. 1913 1914 if (afterCXXScope) { 1915 Diag(Tok, diag::err_expected_unqualified_id); 1916 D.SetIdentifier(0, Tok.getLocation()); 1917 D.setInvalidType(true); 1918 goto PastIdentifier; 1919 } 1920 } 1921 } 1922 1923 // If we reached this point, we are either in C/ObjC or the token didn't 1924 // satisfy any of the C++-specific checks. 1925 if (Tok.is(tok::identifier) && D.mayHaveIdentifier()) { 1926 assert(!getLang().CPlusPlus && 1927 "There's a C++-specific check for tok::identifier above"); 1928 assert(Tok.getIdentifierInfo() && "Not an identifier?"); 1929 D.SetIdentifier(Tok.getIdentifierInfo(), Tok.getLocation()); 1930 ConsumeToken(); 1931 } else if (Tok.is(tok::l_paren)) { 1932 // direct-declarator: '(' declarator ')' 1933 // direct-declarator: '(' attributes declarator ')' 1934 // Example: 'char (*X)' or 'int (*XX)(void)' 1935 ParseParenDeclarator(D); 1936 } else if (D.mayOmitIdentifier()) { 1937 // This could be something simple like "int" (in which case the declarator 1938 // portion is empty), if an abstract-declarator is allowed. 1939 D.SetIdentifier(0, Tok.getLocation()); 1940 } else { 1941 if (D.getContext() == Declarator::MemberContext) 1942 Diag(Tok, diag::err_expected_member_name_or_semi) 1943 << D.getDeclSpec().getSourceRange(); 1944 else if (getLang().CPlusPlus) 1945 Diag(Tok, diag::err_expected_unqualified_id); 1946 else 1947 Diag(Tok, diag::err_expected_ident_lparen); 1948 D.SetIdentifier(0, Tok.getLocation()); 1949 D.setInvalidType(true); 1950 } 1951 1952 PastIdentifier: 1953 assert(D.isPastIdentifier() && 1954 "Haven't past the location of the identifier yet?"); 1955 1956 while (1) { 1957 if (Tok.is(tok::l_paren)) { 1958 // The paren may be part of a C++ direct initializer, eg. "int x(1);". 1959 // In such a case, check if we actually have a function declarator; if it 1960 // is not, the declarator has been fully parsed. 1961 if (getLang().CPlusPlus && D.mayBeFollowedByCXXDirectInit()) { 1962 // When not in file scope, warn for ambiguous function declarators, just 1963 // in case the author intended it as a variable definition. 1964 bool warnIfAmbiguous = D.getContext() != Declarator::FileContext; 1965 if (!isCXXFunctionDeclarator(warnIfAmbiguous)) 1966 break; 1967 } 1968 ParseFunctionDeclarator(ConsumeParen(), D); 1969 } else if (Tok.is(tok::l_square)) { 1970 ParseBracketDeclarator(D); 1971 } else { 1972 break; 1973 } 1974 } 1975} 1976 1977/// ParseParenDeclarator - We parsed the declarator D up to a paren. This is 1978/// only called before the identifier, so these are most likely just grouping 1979/// parens for precedence. If we find that these are actually function 1980/// parameter parens in an abstract-declarator, we call ParseFunctionDeclarator. 1981/// 1982/// direct-declarator: 1983/// '(' declarator ')' 1984/// [GNU] '(' attributes declarator ')' 1985/// direct-declarator '(' parameter-type-list ')' 1986/// direct-declarator '(' identifier-list[opt] ')' 1987/// [GNU] direct-declarator '(' parameter-forward-declarations 1988/// parameter-type-list[opt] ')' 1989/// 1990void Parser::ParseParenDeclarator(Declarator &D) { 1991 SourceLocation StartLoc = ConsumeParen(); 1992 assert(!D.isPastIdentifier() && "Should be called before passing identifier"); 1993 1994 // Eat any attributes before we look at whether this is a grouping or function 1995 // declarator paren. If this is a grouping paren, the attribute applies to 1996 // the type being built up, for example: 1997 // int (__attribute__(()) *x)(long y) 1998 // If this ends up not being a grouping paren, the attribute applies to the 1999 // first argument, for example: 2000 // int (__attribute__(()) int x) 2001 // In either case, we need to eat any attributes to be able to determine what 2002 // sort of paren this is. 2003 // 2004 AttributeList *AttrList = 0; 2005 bool RequiresArg = false; 2006 if (Tok.is(tok::kw___attribute)) { 2007 AttrList = ParseAttributes(); 2008 2009 // We require that the argument list (if this is a non-grouping paren) be 2010 // present even if the attribute list was empty. 2011 RequiresArg = true; 2012 } 2013 // Eat any Microsoft extensions. 2014 while ((Tok.is(tok::kw___cdecl) || Tok.is(tok::kw___stdcall) || 2015 (Tok.is(tok::kw___fastcall))) && PP.getLangOptions().Microsoft) 2016 ConsumeToken(); 2017 2018 // If we haven't past the identifier yet (or where the identifier would be 2019 // stored, if this is an abstract declarator), then this is probably just 2020 // grouping parens. However, if this could be an abstract-declarator, then 2021 // this could also be the start of function arguments (consider 'void()'). 2022 bool isGrouping; 2023 2024 if (!D.mayOmitIdentifier()) { 2025 // If this can't be an abstract-declarator, this *must* be a grouping 2026 // paren, because we haven't seen the identifier yet. 2027 isGrouping = true; 2028 } else if (Tok.is(tok::r_paren) || // 'int()' is a function. 2029 (getLang().CPlusPlus && Tok.is(tok::ellipsis)) || // C++ int(...) 2030 isDeclarationSpecifier()) { // 'int(int)' is a function. 2031 // This handles C99 6.7.5.3p11: in "typedef int X; void foo(X)", X is 2032 // considered to be a type, not a K&R identifier-list. 2033 isGrouping = false; 2034 } else { 2035 // Otherwise, this is a grouping paren, e.g. 'int (*X)' or 'int(X)'. 2036 isGrouping = true; 2037 } 2038 2039 // If this is a grouping paren, handle: 2040 // direct-declarator: '(' declarator ')' 2041 // direct-declarator: '(' attributes declarator ')' 2042 if (isGrouping) { 2043 bool hadGroupingParens = D.hasGroupingParens(); 2044 D.setGroupingParens(true); 2045 if (AttrList) 2046 D.AddAttributes(AttrList, SourceLocation()); 2047 2048 ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator); 2049 // Match the ')'. 2050 SourceLocation Loc = MatchRHSPunctuation(tok::r_paren, StartLoc); 2051 2052 D.setGroupingParens(hadGroupingParens); 2053 D.SetRangeEnd(Loc); 2054 return; 2055 } 2056 2057 // Okay, if this wasn't a grouping paren, it must be the start of a function 2058 // argument list. Recognize that this declarator will never have an 2059 // identifier (and remember where it would have been), then call into 2060 // ParseFunctionDeclarator to handle of argument list. 2061 D.SetIdentifier(0, Tok.getLocation()); 2062 2063 ParseFunctionDeclarator(StartLoc, D, AttrList, RequiresArg); 2064} 2065 2066/// ParseFunctionDeclarator - We are after the identifier and have parsed the 2067/// declarator D up to a paren, which indicates that we are parsing function 2068/// arguments. 2069/// 2070/// If AttrList is non-null, then the caller parsed those arguments immediately 2071/// after the open paren - they should be considered to be the first argument of 2072/// a parameter. If RequiresArg is true, then the first argument of the 2073/// function is required to be present and required to not be an identifier 2074/// list. 2075/// 2076/// This method also handles this portion of the grammar: 2077/// parameter-type-list: [C99 6.7.5] 2078/// parameter-list 2079/// parameter-list ',' '...' 2080/// 2081/// parameter-list: [C99 6.7.5] 2082/// parameter-declaration 2083/// parameter-list ',' parameter-declaration 2084/// 2085/// parameter-declaration: [C99 6.7.5] 2086/// declaration-specifiers declarator 2087/// [C++] declaration-specifiers declarator '=' assignment-expression 2088/// [GNU] declaration-specifiers declarator attributes 2089/// declaration-specifiers abstract-declarator[opt] 2090/// [C++] declaration-specifiers abstract-declarator[opt] 2091/// '=' assignment-expression 2092/// [GNU] declaration-specifiers abstract-declarator[opt] attributes 2093/// 2094/// For C++, after the parameter-list, it also parses "cv-qualifier-seq[opt]" 2095/// and "exception-specification[opt]". 2096/// 2097void Parser::ParseFunctionDeclarator(SourceLocation LParenLoc, Declarator &D, 2098 AttributeList *AttrList, 2099 bool RequiresArg) { 2100 // lparen is already consumed! 2101 assert(D.isPastIdentifier() && "Should not call before identifier!"); 2102 2103 // This parameter list may be empty. 2104 if (Tok.is(tok::r_paren)) { 2105 if (RequiresArg) { 2106 Diag(Tok, diag::err_argument_required_after_attribute); 2107 delete AttrList; 2108 } 2109 2110 SourceLocation Loc = ConsumeParen(); // Eat the closing ')'. 2111 2112 // cv-qualifier-seq[opt]. 2113 DeclSpec DS; 2114 if (getLang().CPlusPlus) { 2115 ParseTypeQualifierListOpt(DS, false /*no attributes*/); 2116 if (!DS.getSourceRange().getEnd().isInvalid()) 2117 Loc = DS.getSourceRange().getEnd(); 2118 2119 // Parse exception-specification[opt]. 2120 if (Tok.is(tok::kw_throw)) 2121 ParseExceptionSpecification(Loc); 2122 } 2123 2124 // Remember that we parsed a function type, and remember the attributes. 2125 // int() -> no prototype, no '...'. 2126 D.AddTypeInfo(DeclaratorChunk::getFunction(/*prototype*/getLang().CPlusPlus, 2127 /*variadic*/ false, 2128 SourceLocation(), 2129 /*arglist*/ 0, 0, 2130 DS.getTypeQualifiers(), 2131 LParenLoc, D), 2132 Loc); 2133 return; 2134 } 2135 2136 // Alternatively, this parameter list may be an identifier list form for a 2137 // K&R-style function: void foo(a,b,c) 2138 if (!getLang().CPlusPlus && Tok.is(tok::identifier)) { 2139 if (!TryAnnotateTypeOrScopeToken()) { 2140 // K&R identifier lists can't have typedefs as identifiers, per 2141 // C99 6.7.5.3p11. 2142 if (RequiresArg) { 2143 Diag(Tok, diag::err_argument_required_after_attribute); 2144 delete AttrList; 2145 } 2146 // Identifier list. Note that '(' identifier-list ')' is only allowed for 2147 // normal declarators, not for abstract-declarators. 2148 return ParseFunctionDeclaratorIdentifierList(LParenLoc, D); 2149 } 2150 } 2151 2152 // Finally, a normal, non-empty parameter type list. 2153 2154 // Build up an array of information about the parsed arguments. 2155 llvm::SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo; 2156 2157 // Enter function-declaration scope, limiting any declarators to the 2158 // function prototype scope, including parameter declarators. 2159 ParseScope PrototypeScope(this, 2160 Scope::FunctionPrototypeScope|Scope::DeclScope); 2161 2162 bool IsVariadic = false; 2163 SourceLocation EllipsisLoc; 2164 while (1) { 2165 if (Tok.is(tok::ellipsis)) { 2166 IsVariadic = true; 2167 EllipsisLoc = ConsumeToken(); // Consume the ellipsis. 2168 break; 2169 } 2170 2171 SourceLocation DSStart = Tok.getLocation(); 2172 2173 // Parse the declaration-specifiers. 2174 DeclSpec DS; 2175 2176 // If the caller parsed attributes for the first argument, add them now. 2177 if (AttrList) { 2178 DS.AddAttributes(AttrList); 2179 AttrList = 0; // Only apply the attributes to the first parameter. 2180 } 2181 ParseDeclarationSpecifiers(DS); 2182 2183 // Parse the declarator. This is "PrototypeContext", because we must 2184 // accept either 'declarator' or 'abstract-declarator' here. 2185 Declarator ParmDecl(DS, Declarator::PrototypeContext); 2186 ParseDeclarator(ParmDecl); 2187 2188 // Parse GNU attributes, if present. 2189 if (Tok.is(tok::kw___attribute)) { 2190 SourceLocation Loc; 2191 AttributeList *AttrList = ParseAttributes(&Loc); 2192 ParmDecl.AddAttributes(AttrList, Loc); 2193 } 2194 2195 // Remember this parsed parameter in ParamInfo. 2196 IdentifierInfo *ParmII = ParmDecl.getIdentifier(); 2197 2198 // DefArgToks is used when the parsing of default arguments needs 2199 // to be delayed. 2200 CachedTokens *DefArgToks = 0; 2201 2202 // If no parameter was specified, verify that *something* was specified, 2203 // otherwise we have a missing type and identifier. 2204 if (DS.isEmpty() && ParmDecl.getIdentifier() == 0 && 2205 ParmDecl.getNumTypeObjects() == 0) { 2206 // Completely missing, emit error. 2207 Diag(DSStart, diag::err_missing_param); 2208 } else { 2209 // Otherwise, we have something. Add it and let semantic analysis try 2210 // to grok it and add the result to the ParamInfo we are building. 2211 2212 // Inform the actions module about the parameter declarator, so it gets 2213 // added to the current scope. 2214 DeclPtrTy Param = Actions.ActOnParamDeclarator(CurScope, ParmDecl); 2215 2216 // Parse the default argument, if any. We parse the default 2217 // arguments in all dialects; the semantic analysis in 2218 // ActOnParamDefaultArgument will reject the default argument in 2219 // C. 2220 if (Tok.is(tok::equal)) { 2221 SourceLocation EqualLoc = Tok.getLocation(); 2222 2223 // Parse the default argument 2224 if (D.getContext() == Declarator::MemberContext) { 2225 // If we're inside a class definition, cache the tokens 2226 // corresponding to the default argument. We'll actually parse 2227 // them when we see the end of the class definition. 2228 // FIXME: Templates will require something similar. 2229 // FIXME: Can we use a smart pointer for Toks? 2230 DefArgToks = new CachedTokens; 2231 2232 if (!ConsumeAndStoreUntil(tok::comma, tok::r_paren, *DefArgToks, 2233 tok::semi, false)) { 2234 delete DefArgToks; 2235 DefArgToks = 0; 2236 Actions.ActOnParamDefaultArgumentError(Param); 2237 } else 2238 Actions.ActOnParamUnparsedDefaultArgument(Param, EqualLoc); 2239 } else { 2240 // Consume the '='. 2241 ConsumeToken(); 2242 2243 OwningExprResult DefArgResult(ParseAssignmentExpression()); 2244 if (DefArgResult.isInvalid()) { 2245 Actions.ActOnParamDefaultArgumentError(Param); 2246 SkipUntil(tok::comma, tok::r_paren, true, true); 2247 } else { 2248 // Inform the actions module about the default argument 2249 Actions.ActOnParamDefaultArgument(Param, EqualLoc, 2250 move(DefArgResult)); 2251 } 2252 } 2253 } 2254 2255 ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII, 2256 ParmDecl.getIdentifierLoc(), Param, 2257 DefArgToks)); 2258 } 2259 2260 // If the next token is a comma, consume it and keep reading arguments. 2261 if (Tok.isNot(tok::comma)) break; 2262 2263 // Consume the comma. 2264 ConsumeToken(); 2265 } 2266 2267 // Leave prototype scope. 2268 PrototypeScope.Exit(); 2269 2270 // If we have the closing ')', eat it. 2271 SourceLocation Loc = MatchRHSPunctuation(tok::r_paren, LParenLoc); 2272 2273 DeclSpec DS; 2274 if (getLang().CPlusPlus) { 2275 // Parse cv-qualifier-seq[opt]. 2276 ParseTypeQualifierListOpt(DS, false /*no attributes*/); 2277 if (!DS.getSourceRange().getEnd().isInvalid()) 2278 Loc = DS.getSourceRange().getEnd(); 2279 2280 // Parse exception-specification[opt]. 2281 if (Tok.is(tok::kw_throw)) 2282 ParseExceptionSpecification(Loc); 2283 } 2284 2285 // Remember that we parsed a function type, and remember the attributes. 2286 D.AddTypeInfo(DeclaratorChunk::getFunction(/*proto*/true, IsVariadic, 2287 EllipsisLoc, 2288 &ParamInfo[0], ParamInfo.size(), 2289 DS.getTypeQualifiers(), 2290 LParenLoc, D), 2291 Loc); 2292} 2293 2294/// ParseFunctionDeclaratorIdentifierList - While parsing a function declarator 2295/// we found a K&R-style identifier list instead of a type argument list. The 2296/// current token is known to be the first identifier in the list. 2297/// 2298/// identifier-list: [C99 6.7.5] 2299/// identifier 2300/// identifier-list ',' identifier 2301/// 2302void Parser::ParseFunctionDeclaratorIdentifierList(SourceLocation LParenLoc, 2303 Declarator &D) { 2304 // Build up an array of information about the parsed arguments. 2305 llvm::SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo; 2306 llvm::SmallSet<const IdentifierInfo*, 16> ParamsSoFar; 2307 2308 // If there was no identifier specified for the declarator, either we are in 2309 // an abstract-declarator, or we are in a parameter declarator which was found 2310 // to be abstract. In abstract-declarators, identifier lists are not valid: 2311 // diagnose this. 2312 if (!D.getIdentifier()) 2313 Diag(Tok, diag::ext_ident_list_in_param); 2314 2315 // Tok is known to be the first identifier in the list. Remember this 2316 // identifier in ParamInfo. 2317 ParamsSoFar.insert(Tok.getIdentifierInfo()); 2318 ParamInfo.push_back(DeclaratorChunk::ParamInfo(Tok.getIdentifierInfo(), 2319 Tok.getLocation(), 2320 DeclPtrTy())); 2321 2322 ConsumeToken(); // eat the first identifier. 2323 2324 while (Tok.is(tok::comma)) { 2325 // Eat the comma. 2326 ConsumeToken(); 2327 2328 // If this isn't an identifier, report the error and skip until ')'. 2329 if (Tok.isNot(tok::identifier)) { 2330 Diag(Tok, diag::err_expected_ident); 2331 SkipUntil(tok::r_paren); 2332 return; 2333 } 2334 2335 IdentifierInfo *ParmII = Tok.getIdentifierInfo(); 2336 2337 // Reject 'typedef int y; int test(x, y)', but continue parsing. 2338 if (Actions.getTypeName(*ParmII, Tok.getLocation(), CurScope)) 2339 Diag(Tok, diag::err_unexpected_typedef_ident) << ParmII; 2340 2341 // Verify that the argument identifier has not already been mentioned. 2342 if (!ParamsSoFar.insert(ParmII)) { 2343 Diag(Tok, diag::err_param_redefinition) << ParmII; 2344 } else { 2345 // Remember this identifier in ParamInfo. 2346 ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII, 2347 Tok.getLocation(), 2348 DeclPtrTy())); 2349 } 2350 2351 // Eat the identifier. 2352 ConsumeToken(); 2353 } 2354 2355 // If we have the closing ')', eat it and we're done. 2356 SourceLocation RLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc); 2357 2358 // Remember that we parsed a function type, and remember the attributes. This 2359 // function type is always a K&R style function type, which is not varargs and 2360 // has no prototype. 2361 D.AddTypeInfo(DeclaratorChunk::getFunction(/*proto*/false, /*varargs*/false, 2362 SourceLocation(), 2363 &ParamInfo[0], ParamInfo.size(), 2364 /*TypeQuals*/0, LParenLoc, D), 2365 RLoc); 2366} 2367 2368/// [C90] direct-declarator '[' constant-expression[opt] ']' 2369/// [C99] direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']' 2370/// [C99] direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']' 2371/// [C99] direct-declarator '[' type-qual-list 'static' assignment-expr ']' 2372/// [C99] direct-declarator '[' type-qual-list[opt] '*' ']' 2373void Parser::ParseBracketDeclarator(Declarator &D) { 2374 SourceLocation StartLoc = ConsumeBracket(); 2375 2376 // C array syntax has many features, but by-far the most common is [] and [4]. 2377 // This code does a fast path to handle some of the most obvious cases. 2378 if (Tok.getKind() == tok::r_square) { 2379 SourceLocation EndLoc = MatchRHSPunctuation(tok::r_square, StartLoc); 2380 // Remember that we parsed the empty array type. 2381 OwningExprResult NumElements(Actions); 2382 D.AddTypeInfo(DeclaratorChunk::getArray(0, false, false, 0, StartLoc), 2383 EndLoc); 2384 return; 2385 } else if (Tok.getKind() == tok::numeric_constant && 2386 GetLookAheadToken(1).is(tok::r_square)) { 2387 // [4] is very common. Parse the numeric constant expression. 2388 OwningExprResult ExprRes(Actions.ActOnNumericConstant(Tok)); 2389 ConsumeToken(); 2390 2391 SourceLocation EndLoc = MatchRHSPunctuation(tok::r_square, StartLoc); 2392 2393 // If there was an error parsing the assignment-expression, recover. 2394 if (ExprRes.isInvalid()) 2395 ExprRes.release(); // Deallocate expr, just use []. 2396 2397 // Remember that we parsed a array type, and remember its features. 2398 D.AddTypeInfo(DeclaratorChunk::getArray(0, false, 0, 2399 ExprRes.release(), StartLoc), 2400 EndLoc); 2401 return; 2402 } 2403 2404 // If valid, this location is the position where we read the 'static' keyword. 2405 SourceLocation StaticLoc; 2406 if (Tok.is(tok::kw_static)) 2407 StaticLoc = ConsumeToken(); 2408 2409 // If there is a type-qualifier-list, read it now. 2410 // Type qualifiers in an array subscript are a C99 feature. 2411 DeclSpec DS; 2412 ParseTypeQualifierListOpt(DS, false /*no attributes*/); 2413 2414 // If we haven't already read 'static', check to see if there is one after the 2415 // type-qualifier-list. 2416 if (!StaticLoc.isValid() && Tok.is(tok::kw_static)) 2417 StaticLoc = ConsumeToken(); 2418 2419 // Handle "direct-declarator [ type-qual-list[opt] * ]". 2420 bool isStar = false; 2421 OwningExprResult NumElements(Actions); 2422 2423 // Handle the case where we have '[*]' as the array size. However, a leading 2424 // star could be the start of an expression, for example 'X[*p + 4]'. Verify 2425 // the the token after the star is a ']'. Since stars in arrays are 2426 // infrequent, use of lookahead is not costly here. 2427 if (Tok.is(tok::star) && GetLookAheadToken(1).is(tok::r_square)) { 2428 ConsumeToken(); // Eat the '*'. 2429 2430 if (StaticLoc.isValid()) { 2431 Diag(StaticLoc, diag::err_unspecified_vla_size_with_static); 2432 StaticLoc = SourceLocation(); // Drop the static. 2433 } 2434 isStar = true; 2435 } else if (Tok.isNot(tok::r_square)) { 2436 // Note, in C89, this production uses the constant-expr production instead 2437 // of assignment-expr. The only difference is that assignment-expr allows 2438 // things like '=' and '*='. Sema rejects these in C89 mode because they 2439 // are not i-c-e's, so we don't need to distinguish between the two here. 2440 2441 // Parse the assignment-expression now. 2442 NumElements = ParseAssignmentExpression(); 2443 } 2444 2445 // If there was an error parsing the assignment-expression, recover. 2446 if (NumElements.isInvalid()) { 2447 // If the expression was invalid, skip it. 2448 SkipUntil(tok::r_square); 2449 return; 2450 } 2451 2452 SourceLocation EndLoc = MatchRHSPunctuation(tok::r_square, StartLoc); 2453 2454 // Remember that we parsed a array type, and remember its features. 2455 D.AddTypeInfo(DeclaratorChunk::getArray(DS.getTypeQualifiers(), 2456 StaticLoc.isValid(), isStar, 2457 NumElements.release(), StartLoc), 2458 EndLoc); 2459} 2460 2461/// [GNU] typeof-specifier: 2462/// typeof ( expressions ) 2463/// typeof ( type-name ) 2464/// [GNU/C++] typeof unary-expression 2465/// 2466void Parser::ParseTypeofSpecifier(DeclSpec &DS) { 2467 assert(Tok.is(tok::kw_typeof) && "Not a typeof specifier"); 2468 const IdentifierInfo *BuiltinII = Tok.getIdentifierInfo(); 2469 SourceLocation StartLoc = ConsumeToken(); 2470 2471 if (Tok.isNot(tok::l_paren)) { 2472 if (!getLang().CPlusPlus) { 2473 Diag(Tok, diag::err_expected_lparen_after_id) << BuiltinII; 2474 return; 2475 } 2476 2477 OwningExprResult Result(ParseCastExpression(true/*isUnaryExpression*/)); 2478 if (Result.isInvalid()) { 2479 DS.SetTypeSpecError(); 2480 return; 2481 } 2482 2483 const char *PrevSpec = 0; 2484 // Check for duplicate type specifiers. 2485 if (DS.SetTypeSpecType(DeclSpec::TST_typeofExpr, StartLoc, PrevSpec, 2486 Result.release())) 2487 Diag(StartLoc, diag::err_invalid_decl_spec_combination) << PrevSpec; 2488 2489 // FIXME: Not accurate, the range gets one token more than it should. 2490 DS.SetRangeEnd(Tok.getLocation()); 2491 return; 2492 } 2493 2494 SourceLocation LParenLoc = ConsumeParen(), RParenLoc; 2495 2496 if (isTypeIdInParens()) { 2497 Action::TypeResult Ty = ParseTypeName(); 2498 2499 assert((Ty.isInvalid() || Ty.get()) && 2500 "Parser::ParseTypeofSpecifier(): missing type"); 2501 2502 if (Tok.isNot(tok::r_paren)) { 2503 MatchRHSPunctuation(tok::r_paren, LParenLoc); 2504 return; 2505 } 2506 RParenLoc = ConsumeParen(); 2507 2508 if (Ty.isInvalid()) 2509 DS.SetTypeSpecError(); 2510 else { 2511 const char *PrevSpec = 0; 2512 // Check for duplicate type specifiers (e.g. "int typeof(int)"). 2513 if (DS.SetTypeSpecType(DeclSpec::TST_typeofType, StartLoc, PrevSpec, 2514 Ty.get())) 2515 Diag(StartLoc, diag::err_invalid_decl_spec_combination) << PrevSpec; 2516 } 2517 } else { // we have an expression. 2518 OwningExprResult Result(ParseExpression()); 2519 2520 if (Result.isInvalid() || Tok.isNot(tok::r_paren)) { 2521 MatchRHSPunctuation(tok::r_paren, LParenLoc); 2522 DS.SetTypeSpecError(); 2523 return; 2524 } 2525 RParenLoc = ConsumeParen(); 2526 const char *PrevSpec = 0; 2527 // Check for duplicate type specifiers (e.g. "int typeof(int)"). 2528 if (DS.SetTypeSpecType(DeclSpec::TST_typeofExpr, StartLoc, PrevSpec, 2529 Result.release())) 2530 Diag(StartLoc, diag::err_invalid_decl_spec_combination) << PrevSpec; 2531 } 2532 DS.SetRangeEnd(RParenLoc); 2533} 2534 2535 2536