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