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