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