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