ParseDecl.cpp revision f27f03e215cbd7a7bdfb35a95e524c9eea8ba940
1//===--- ParseDecl.cpp - Declaration Parsing ------------------------------===// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file is distributed under the University of Illinois Open Source 6// License. See LICENSE.TXT for details. 7// 8//===----------------------------------------------------------------------===// 9// 10// This file implements the Declaration portions of the Parser interfaces. 11// 12//===----------------------------------------------------------------------===// 13 14#include "clang/Parse/Parser.h" 15#include "clang/Parse/ParseDiagnostic.h" 16#include "clang/Sema/Scope.h" 17#include "clang/Sema/ParsedTemplate.h" 18#include "clang/Sema/PrettyDeclStackTrace.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++. 32TypeResult 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(getCurScope(), 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 "parameterized" 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 = AttrFactory.Create(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 ExprResult 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 = AttrFactory.Create(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 = AttrFactory.Create(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 CurrAttr = AttrFactory.Create(AttrName, AttrNameLoc, 0, AttrNameLoc, 179 0, SourceLocation(), 0, 0, CurrAttr); 180 if (CurrAttr->getKind() == AttributeList::AT_IBOutletCollection) 181 Diag(Tok, diag::err_iboutletcollection_builtintype); 182 // If it's a builtin type name, eat it and expect a rparen 183 // __attribute__(( vec_type_hint(char) )) 184 ConsumeToken(); 185 if (Tok.is(tok::r_paren)) 186 ConsumeParen(); 187 break; 188 default: 189 // __attribute__(( aligned(16) )) 190 ExprVector ArgExprs(Actions); 191 bool ArgExprsOk = true; 192 193 // now parse the list of expressions 194 while (1) { 195 ExprResult ArgExpr(ParseAssignmentExpression()); 196 if (ArgExpr.isInvalid()) { 197 ArgExprsOk = false; 198 SkipUntil(tok::r_paren); 199 break; 200 } else { 201 ArgExprs.push_back(ArgExpr.release()); 202 } 203 if (Tok.isNot(tok::comma)) 204 break; 205 ConsumeToken(); // Eat the comma, move to the next argument 206 } 207 // Match the ')'. 208 if (ArgExprsOk && Tok.is(tok::r_paren)) { 209 ConsumeParen(); // ignore the right paren loc for now 210 CurrAttr = AttrFactory.Create(AttrName, AttrNameLoc, 0, 211 AttrNameLoc, 0, SourceLocation(), ArgExprs.take(), 212 ArgExprs.size(), 213 CurrAttr); 214 } 215 break; 216 } 217 } 218 } else { 219 CurrAttr = AttrFactory.Create(AttrName, AttrNameLoc, 0, AttrNameLoc, 220 0, SourceLocation(), 0, 0, CurrAttr); 221 } 222 } 223 if (ExpectAndConsume(tok::r_paren, diag::err_expected_rparen)) 224 SkipUntil(tok::r_paren, false); 225 SourceLocation Loc = Tok.getLocation(); 226 if (ExpectAndConsume(tok::r_paren, diag::err_expected_rparen)) { 227 SkipUntil(tok::r_paren, false); 228 } 229 if (EndLoc) 230 *EndLoc = Loc; 231 } 232 return CurrAttr; 233} 234 235/// ParseMicrosoftDeclSpec - Parse an __declspec construct 236/// 237/// [MS] decl-specifier: 238/// __declspec ( extended-decl-modifier-seq ) 239/// 240/// [MS] extended-decl-modifier-seq: 241/// extended-decl-modifier[opt] 242/// extended-decl-modifier extended-decl-modifier-seq 243 244AttributeList* Parser::ParseMicrosoftDeclSpec(AttributeList *CurrAttr) { 245 assert(Tok.is(tok::kw___declspec) && "Not a declspec!"); 246 247 ConsumeToken(); 248 if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after, 249 "declspec")) { 250 SkipUntil(tok::r_paren, true); // skip until ) or ; 251 return CurrAttr; 252 } 253 while (Tok.getIdentifierInfo()) { 254 IdentifierInfo *AttrName = Tok.getIdentifierInfo(); 255 SourceLocation AttrNameLoc = ConsumeToken(); 256 if (Tok.is(tok::l_paren)) { 257 ConsumeParen(); 258 // FIXME: This doesn't parse __declspec(property(get=get_func_name)) 259 // correctly. 260 ExprResult ArgExpr(ParseAssignmentExpression()); 261 if (!ArgExpr.isInvalid()) { 262 Expr *ExprList = ArgExpr.take(); 263 CurrAttr = AttrFactory.Create(AttrName, AttrNameLoc, 0, AttrNameLoc, 0, 264 SourceLocation(), &ExprList, 1, 265 CurrAttr, true); 266 } 267 if (ExpectAndConsume(tok::r_paren, diag::err_expected_rparen)) 268 SkipUntil(tok::r_paren, false); 269 } else { 270 CurrAttr = AttrFactory.Create(AttrName, AttrNameLoc, 0, AttrNameLoc, 271 0, SourceLocation(), 0, 0, CurrAttr, true); 272 } 273 } 274 if (ExpectAndConsume(tok::r_paren, diag::err_expected_rparen)) 275 SkipUntil(tok::r_paren, false); 276 return CurrAttr; 277} 278 279AttributeList* Parser::ParseMicrosoftTypeAttributes(AttributeList *CurrAttr) { 280 // Treat these like attributes 281 // FIXME: Allow Sema to distinguish between these and real attributes! 282 while (Tok.is(tok::kw___fastcall) || Tok.is(tok::kw___stdcall) || 283 Tok.is(tok::kw___thiscall) || Tok.is(tok::kw___cdecl) || 284 Tok.is(tok::kw___ptr64) || Tok.is(tok::kw___w64)) { 285 IdentifierInfo *AttrName = Tok.getIdentifierInfo(); 286 SourceLocation AttrNameLoc = ConsumeToken(); 287 if (Tok.is(tok::kw___ptr64) || Tok.is(tok::kw___w64)) 288 // FIXME: Support these properly! 289 continue; 290 CurrAttr = AttrFactory.Create(AttrName, AttrNameLoc, 0, AttrNameLoc, 0, 291 SourceLocation(), 0, 0, CurrAttr, true); 292 } 293 return CurrAttr; 294} 295 296AttributeList* Parser::ParseBorlandTypeAttributes(AttributeList *CurrAttr) { 297 // Treat these like attributes 298 while (Tok.is(tok::kw___pascal)) { 299 IdentifierInfo *AttrName = Tok.getIdentifierInfo(); 300 SourceLocation AttrNameLoc = ConsumeToken(); 301 CurrAttr = AttrFactory.Create(AttrName, AttrNameLoc, 0, AttrNameLoc, 0, 302 SourceLocation(), 0, 0, CurrAttr, true); 303 } 304 return CurrAttr; 305} 306 307/// ParseDeclaration - Parse a full 'declaration', which consists of 308/// declaration-specifiers, some number of declarators, and a semicolon. 309/// 'Context' should be a Declarator::TheContext value. This returns the 310/// location of the semicolon in DeclEnd. 311/// 312/// declaration: [C99 6.7] 313/// block-declaration -> 314/// simple-declaration 315/// others [FIXME] 316/// [C++] template-declaration 317/// [C++] namespace-definition 318/// [C++] using-directive 319/// [C++] using-declaration 320/// [C++0x] static_assert-declaration 321/// others... [FIXME] 322/// 323Parser::DeclGroupPtrTy Parser::ParseDeclaration(StmtVector &Stmts, 324 unsigned Context, 325 SourceLocation &DeclEnd, 326 CXX0XAttributeList Attr) { 327 ParenBraceBracketBalancer BalancerRAIIObj(*this); 328 329 Decl *SingleDecl = 0; 330 switch (Tok.getKind()) { 331 case tok::kw_template: 332 case tok::kw_export: 333 if (Attr.HasAttr) 334 Diag(Attr.Range.getBegin(), diag::err_attributes_not_allowed) 335 << Attr.Range; 336 SingleDecl = ParseDeclarationStartingWithTemplate(Context, DeclEnd); 337 break; 338 case tok::kw_inline: 339 // Could be the start of an inline namespace. Allowed as an ext in C++03. 340 if (getLang().CPlusPlus && NextToken().is(tok::kw_namespace)) { 341 if (Attr.HasAttr) 342 Diag(Attr.Range.getBegin(), diag::err_attributes_not_allowed) 343 << Attr.Range; 344 SourceLocation InlineLoc = ConsumeToken(); 345 SingleDecl = ParseNamespace(Context, DeclEnd, InlineLoc); 346 break; 347 } 348 return ParseSimpleDeclaration(Stmts, Context, DeclEnd, Attr.AttrList, 349 true); 350 case tok::kw_namespace: 351 if (Attr.HasAttr) 352 Diag(Attr.Range.getBegin(), diag::err_attributes_not_allowed) 353 << Attr.Range; 354 SingleDecl = ParseNamespace(Context, DeclEnd); 355 break; 356 case tok::kw_using: 357 SingleDecl = ParseUsingDirectiveOrDeclaration(Context, ParsedTemplateInfo(), 358 DeclEnd, Attr); 359 break; 360 case tok::kw_static_assert: 361 if (Attr.HasAttr) 362 Diag(Attr.Range.getBegin(), diag::err_attributes_not_allowed) 363 << Attr.Range; 364 SingleDecl = ParseStaticAssertDeclaration(DeclEnd); 365 break; 366 default: 367 return ParseSimpleDeclaration(Stmts, Context, DeclEnd, Attr.AttrList, 368 true); 369 } 370 371 // This routine returns a DeclGroup, if the thing we parsed only contains a 372 // single decl, convert it now. 373 return Actions.ConvertDeclToDeclGroup(SingleDecl); 374} 375 376/// simple-declaration: [C99 6.7: declaration] [C++ 7p1: dcl.dcl] 377/// declaration-specifiers init-declarator-list[opt] ';' 378///[C90/C++]init-declarator-list ';' [TODO] 379/// [OMP] threadprivate-directive [TODO] 380/// 381/// If RequireSemi is false, this does not check for a ';' at the end of the 382/// declaration. If it is true, it checks for and eats it. 383Parser::DeclGroupPtrTy Parser::ParseSimpleDeclaration(StmtVector &Stmts, 384 unsigned Context, 385 SourceLocation &DeclEnd, 386 AttributeList *Attr, 387 bool RequireSemi) { 388 // Parse the common declaration-specifiers piece. 389 ParsingDeclSpec DS(*this); 390 if (Attr) 391 DS.AddAttributes(Attr); 392 ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS_none, 393 getDeclSpecContextFromDeclaratorContext(Context)); 394 StmtResult R = Actions.ActOnVlaStmt(DS); 395 if (R.isUsable()) 396 Stmts.push_back(R.release()); 397 398 // C99 6.7.2.3p6: Handle "struct-or-union identifier;", "enum { X };" 399 // declaration-specifiers init-declarator-list[opt] ';' 400 if (Tok.is(tok::semi)) { 401 if (RequireSemi) ConsumeToken(); 402 Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS_none, 403 DS); 404 DS.complete(TheDecl); 405 return Actions.ConvertDeclToDeclGroup(TheDecl); 406 } 407 408 return ParseDeclGroup(DS, Context, /*FunctionDefs=*/ false, &DeclEnd); 409} 410 411/// ParseDeclGroup - Having concluded that this is either a function 412/// definition or a group of object declarations, actually parse the 413/// result. 414Parser::DeclGroupPtrTy Parser::ParseDeclGroup(ParsingDeclSpec &DS, 415 unsigned Context, 416 bool AllowFunctionDefinitions, 417 SourceLocation *DeclEnd) { 418 // Parse the first declarator. 419 ParsingDeclarator D(*this, DS, static_cast<Declarator::TheContext>(Context)); 420 ParseDeclarator(D); 421 422 // Bail out if the first declarator didn't seem well-formed. 423 if (!D.hasName() && !D.mayOmitIdentifier()) { 424 // Skip until ; or }. 425 SkipUntil(tok::r_brace, true, true); 426 if (Tok.is(tok::semi)) 427 ConsumeToken(); 428 return DeclGroupPtrTy(); 429 } 430 431 // Check to see if we have a function *definition* which must have a body. 432 if (AllowFunctionDefinitions && D.isFunctionDeclarator() && 433 // Look at the next token to make sure that this isn't a function 434 // declaration. We have to check this because __attribute__ might be the 435 // start of a function definition in GCC-extended K&R C. 436 !isDeclarationAfterDeclarator()) { 437 438 if (isStartOfFunctionDefinition(D)) { 439 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) { 440 Diag(Tok, diag::err_function_declared_typedef); 441 442 // Recover by treating the 'typedef' as spurious. 443 DS.ClearStorageClassSpecs(); 444 } 445 446 Decl *TheDecl = ParseFunctionDefinition(D); 447 return Actions.ConvertDeclToDeclGroup(TheDecl); 448 } 449 450 if (isDeclarationSpecifier()) { 451 // If there is an invalid declaration specifier right after the function 452 // prototype, then we must be in a missing semicolon case where this isn't 453 // actually a body. Just fall through into the code that handles it as a 454 // prototype, and let the top-level code handle the erroneous declspec 455 // where it would otherwise expect a comma or semicolon. 456 } else { 457 Diag(Tok, diag::err_expected_fn_body); 458 SkipUntil(tok::semi); 459 return DeclGroupPtrTy(); 460 } 461 } 462 463 llvm::SmallVector<Decl *, 8> DeclsInGroup; 464 Decl *FirstDecl = ParseDeclarationAfterDeclarator(D); 465 D.complete(FirstDecl); 466 if (FirstDecl) 467 DeclsInGroup.push_back(FirstDecl); 468 469 // If we don't have a comma, it is either the end of the list (a ';') or an 470 // error, bail out. 471 while (Tok.is(tok::comma)) { 472 // Consume the comma. 473 ConsumeToken(); 474 475 // Parse the next declarator. 476 D.clear(); 477 478 // Accept attributes in an init-declarator. In the first declarator in a 479 // declaration, these would be part of the declspec. In subsequent 480 // declarators, they become part of the declarator itself, so that they 481 // don't apply to declarators after *this* one. Examples: 482 // short __attribute__((common)) var; -> declspec 483 // short var __attribute__((common)); -> declarator 484 // short x, __attribute__((common)) var; -> declarator 485 if (Tok.is(tok::kw___attribute)) { 486 SourceLocation Loc; 487 AttributeList *AttrList = ParseGNUAttributes(&Loc); 488 D.AddAttributes(AttrList, Loc); 489 } 490 491 ParseDeclarator(D); 492 493 Decl *ThisDecl = ParseDeclarationAfterDeclarator(D); 494 D.complete(ThisDecl); 495 if (ThisDecl) 496 DeclsInGroup.push_back(ThisDecl); 497 } 498 499 if (DeclEnd) 500 *DeclEnd = Tok.getLocation(); 501 502 if (Context != Declarator::ForContext && 503 ExpectAndConsume(tok::semi, 504 Context == Declarator::FileContext 505 ? diag::err_invalid_token_after_toplevel_declarator 506 : diag::err_expected_semi_declaration)) { 507 // Okay, there was no semicolon and one was expected. If we see a 508 // declaration specifier, just assume it was missing and continue parsing. 509 // Otherwise things are very confused and we skip to recover. 510 if (!isDeclarationSpecifier()) { 511 SkipUntil(tok::r_brace, true, true); 512 if (Tok.is(tok::semi)) 513 ConsumeToken(); 514 } 515 } 516 517 return Actions.FinalizeDeclaratorGroup(getCurScope(), DS, 518 DeclsInGroup.data(), 519 DeclsInGroup.size()); 520} 521 522/// \brief Parse 'declaration' after parsing 'declaration-specifiers 523/// declarator'. This method parses the remainder of the declaration 524/// (including any attributes or initializer, among other things) and 525/// finalizes the declaration. 526/// 527/// init-declarator: [C99 6.7] 528/// declarator 529/// declarator '=' initializer 530/// [GNU] declarator simple-asm-expr[opt] attributes[opt] 531/// [GNU] declarator simple-asm-expr[opt] attributes[opt] '=' initializer 532/// [C++] declarator initializer[opt] 533/// 534/// [C++] initializer: 535/// [C++] '=' initializer-clause 536/// [C++] '(' expression-list ')' 537/// [C++0x] '=' 'default' [TODO] 538/// [C++0x] '=' 'delete' 539/// 540/// According to the standard grammar, =default and =delete are function 541/// definitions, but that definitely doesn't fit with the parser here. 542/// 543Decl *Parser::ParseDeclarationAfterDeclarator(Declarator &D, 544 const ParsedTemplateInfo &TemplateInfo) { 545 // If a simple-asm-expr is present, parse it. 546 if (Tok.is(tok::kw_asm)) { 547 SourceLocation Loc; 548 ExprResult AsmLabel(ParseSimpleAsm(&Loc)); 549 if (AsmLabel.isInvalid()) { 550 SkipUntil(tok::semi, true, true); 551 return 0; 552 } 553 554 D.setAsmLabel(AsmLabel.release()); 555 D.SetRangeEnd(Loc); 556 } 557 558 // If attributes are present, parse them. 559 if (Tok.is(tok::kw___attribute)) { 560 SourceLocation Loc; 561 AttributeList *AttrList = ParseGNUAttributes(&Loc); 562 D.AddAttributes(AttrList, Loc); 563 } 564 565 // Inform the current actions module that we just parsed this declarator. 566 Decl *ThisDecl = 0; 567 switch (TemplateInfo.Kind) { 568 case ParsedTemplateInfo::NonTemplate: 569 ThisDecl = Actions.ActOnDeclarator(getCurScope(), D); 570 break; 571 572 case ParsedTemplateInfo::Template: 573 case ParsedTemplateInfo::ExplicitSpecialization: 574 ThisDecl = Actions.ActOnTemplateDeclarator(getCurScope(), 575 MultiTemplateParamsArg(Actions, 576 TemplateInfo.TemplateParams->data(), 577 TemplateInfo.TemplateParams->size()), 578 D); 579 break; 580 581 case ParsedTemplateInfo::ExplicitInstantiation: { 582 DeclResult ThisRes 583 = Actions.ActOnExplicitInstantiation(getCurScope(), 584 TemplateInfo.ExternLoc, 585 TemplateInfo.TemplateLoc, 586 D); 587 if (ThisRes.isInvalid()) { 588 SkipUntil(tok::semi, true, true); 589 return 0; 590 } 591 592 ThisDecl = ThisRes.get(); 593 break; 594 } 595 } 596 597 // Parse declarator '=' initializer. 598 if (isTokenEqualOrMistypedEqualEqual( 599 diag::err_invalid_equalequal_after_declarator)) { 600 ConsumeToken(); 601 if (Tok.is(tok::kw_delete)) { 602 SourceLocation DelLoc = ConsumeToken(); 603 604 if (!getLang().CPlusPlus0x) 605 Diag(DelLoc, diag::warn_deleted_function_accepted_as_extension); 606 607 Actions.SetDeclDeleted(ThisDecl, DelLoc); 608 } else { 609 if (getLang().CPlusPlus && D.getCXXScopeSpec().isSet()) { 610 EnterScope(0); 611 Actions.ActOnCXXEnterDeclInitializer(getCurScope(), ThisDecl); 612 } 613 614 if (Tok.is(tok::code_completion)) { 615 Actions.CodeCompleteInitializer(getCurScope(), ThisDecl); 616 ConsumeCodeCompletionToken(); 617 SkipUntil(tok::comma, true, true); 618 return ThisDecl; 619 } 620 621 ExprResult Init(ParseInitializer()); 622 623 if (getLang().CPlusPlus && D.getCXXScopeSpec().isSet()) { 624 Actions.ActOnCXXExitDeclInitializer(getCurScope(), ThisDecl); 625 ExitScope(); 626 } 627 628 if (Init.isInvalid()) { 629 SkipUntil(tok::comma, true, true); 630 Actions.ActOnInitializerError(ThisDecl); 631 } else 632 Actions.AddInitializerToDecl(ThisDecl, Init.take()); 633 } 634 } else if (Tok.is(tok::l_paren)) { 635 // Parse C++ direct initializer: '(' expression-list ')' 636 SourceLocation LParenLoc = ConsumeParen(); 637 ExprVector Exprs(Actions); 638 CommaLocsTy CommaLocs; 639 640 if (getLang().CPlusPlus && D.getCXXScopeSpec().isSet()) { 641 EnterScope(0); 642 Actions.ActOnCXXEnterDeclInitializer(getCurScope(), ThisDecl); 643 } 644 645 if (ParseExpressionList(Exprs, CommaLocs)) { 646 SkipUntil(tok::r_paren); 647 648 if (getLang().CPlusPlus && D.getCXXScopeSpec().isSet()) { 649 Actions.ActOnCXXExitDeclInitializer(getCurScope(), ThisDecl); 650 ExitScope(); 651 } 652 } else { 653 // Match the ')'. 654 SourceLocation RParenLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc); 655 656 assert(!Exprs.empty() && Exprs.size()-1 == CommaLocs.size() && 657 "Unexpected number of commas!"); 658 659 if (getLang().CPlusPlus && D.getCXXScopeSpec().isSet()) { 660 Actions.ActOnCXXExitDeclInitializer(getCurScope(), ThisDecl); 661 ExitScope(); 662 } 663 664 Actions.AddCXXDirectInitializerToDecl(ThisDecl, LParenLoc, 665 move_arg(Exprs), 666 RParenLoc); 667 } 668 } else { 669 bool TypeContainsUndeducedAuto = 670 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto; 671 Actions.ActOnUninitializedDecl(ThisDecl, TypeContainsUndeducedAuto); 672 } 673 674 return ThisDecl; 675} 676 677/// ParseSpecifierQualifierList 678/// specifier-qualifier-list: 679/// type-specifier specifier-qualifier-list[opt] 680/// type-qualifier specifier-qualifier-list[opt] 681/// [GNU] attributes specifier-qualifier-list[opt] 682/// 683void Parser::ParseSpecifierQualifierList(DeclSpec &DS) { 684 /// specifier-qualifier-list is a subset of declaration-specifiers. Just 685 /// parse declaration-specifiers and complain about extra stuff. 686 ParseDeclarationSpecifiers(DS); 687 688 // Validate declspec for type-name. 689 unsigned Specs = DS.getParsedSpecifiers(); 690 if (Specs == DeclSpec::PQ_None && !DS.getNumProtocolQualifiers() && 691 !DS.getAttributes()) 692 Diag(Tok, diag::err_typename_requires_specqual); 693 694 // Issue diagnostic and remove storage class if present. 695 if (Specs & DeclSpec::PQ_StorageClassSpecifier) { 696 if (DS.getStorageClassSpecLoc().isValid()) 697 Diag(DS.getStorageClassSpecLoc(),diag::err_typename_invalid_storageclass); 698 else 699 Diag(DS.getThreadSpecLoc(), diag::err_typename_invalid_storageclass); 700 DS.ClearStorageClassSpecs(); 701 } 702 703 // Issue diagnostic and remove function specfier if present. 704 if (Specs & DeclSpec::PQ_FunctionSpecifier) { 705 if (DS.isInlineSpecified()) 706 Diag(DS.getInlineSpecLoc(), diag::err_typename_invalid_functionspec); 707 if (DS.isVirtualSpecified()) 708 Diag(DS.getVirtualSpecLoc(), diag::err_typename_invalid_functionspec); 709 if (DS.isExplicitSpecified()) 710 Diag(DS.getExplicitSpecLoc(), diag::err_typename_invalid_functionspec); 711 DS.ClearFunctionSpecs(); 712 } 713} 714 715/// isValidAfterIdentifierInDeclaratorAfterDeclSpec - Return true if the 716/// specified token is valid after the identifier in a declarator which 717/// immediately follows the declspec. For example, these things are valid: 718/// 719/// int x [ 4]; // direct-declarator 720/// int x ( int y); // direct-declarator 721/// int(int x ) // direct-declarator 722/// int x ; // simple-declaration 723/// int x = 17; // init-declarator-list 724/// int x , y; // init-declarator-list 725/// int x __asm__ ("foo"); // init-declarator-list 726/// int x : 4; // struct-declarator 727/// int x { 5}; // C++'0x unified initializers 728/// 729/// This is not, because 'x' does not immediately follow the declspec (though 730/// ')' happens to be valid anyway). 731/// int (x) 732/// 733static bool isValidAfterIdentifierInDeclarator(const Token &T) { 734 return T.is(tok::l_square) || T.is(tok::l_paren) || T.is(tok::r_paren) || 735 T.is(tok::semi) || T.is(tok::comma) || T.is(tok::equal) || 736 T.is(tok::kw_asm) || T.is(tok::l_brace) || T.is(tok::colon); 737} 738 739 740/// ParseImplicitInt - This method is called when we have an non-typename 741/// identifier in a declspec (which normally terminates the decl spec) when 742/// the declspec has no type specifier. In this case, the declspec is either 743/// malformed or is "implicit int" (in K&R and C89). 744/// 745/// This method handles diagnosing this prettily and returns false if the 746/// declspec is done being processed. If it recovers and thinks there may be 747/// other pieces of declspec after it, it returns true. 748/// 749bool Parser::ParseImplicitInt(DeclSpec &DS, CXXScopeSpec *SS, 750 const ParsedTemplateInfo &TemplateInfo, 751 AccessSpecifier AS) { 752 assert(Tok.is(tok::identifier) && "should have identifier"); 753 754 SourceLocation Loc = Tok.getLocation(); 755 // If we see an identifier that is not a type name, we normally would 756 // parse it as the identifer being declared. However, when a typename 757 // is typo'd or the definition is not included, this will incorrectly 758 // parse the typename as the identifier name and fall over misparsing 759 // later parts of the diagnostic. 760 // 761 // As such, we try to do some look-ahead in cases where this would 762 // otherwise be an "implicit-int" case to see if this is invalid. For 763 // example: "static foo_t x = 4;" In this case, if we parsed foo_t as 764 // an identifier with implicit int, we'd get a parse error because the 765 // next token is obviously invalid for a type. Parse these as a case 766 // with an invalid type specifier. 767 assert(!DS.hasTypeSpecifier() && "Type specifier checked above"); 768 769 // Since we know that this either implicit int (which is rare) or an 770 // error, we'd do lookahead to try to do better recovery. 771 if (isValidAfterIdentifierInDeclarator(NextToken())) { 772 // If this token is valid for implicit int, e.g. "static x = 4", then 773 // we just avoid eating the identifier, so it will be parsed as the 774 // identifier in the declarator. 775 return false; 776 } 777 778 // Otherwise, if we don't consume this token, we are going to emit an 779 // error anyway. Try to recover from various common problems. Check 780 // to see if this was a reference to a tag name without a tag specified. 781 // This is a common problem in C (saying 'foo' instead of 'struct foo'). 782 // 783 // C++ doesn't need this, and isTagName doesn't take SS. 784 if (SS == 0) { 785 const char *TagName = 0; 786 tok::TokenKind TagKind = tok::unknown; 787 788 switch (Actions.isTagName(*Tok.getIdentifierInfo(), getCurScope())) { 789 default: break; 790 case DeclSpec::TST_enum: TagName="enum" ;TagKind=tok::kw_enum ;break; 791 case DeclSpec::TST_union: TagName="union" ;TagKind=tok::kw_union ;break; 792 case DeclSpec::TST_struct:TagName="struct";TagKind=tok::kw_struct;break; 793 case DeclSpec::TST_class: TagName="class" ;TagKind=tok::kw_class ;break; 794 } 795 796 if (TagName) { 797 Diag(Loc, diag::err_use_of_tag_name_without_tag) 798 << Tok.getIdentifierInfo() << TagName << getLang().CPlusPlus 799 << FixItHint::CreateInsertion(Tok.getLocation(),TagName); 800 801 // Parse this as a tag as if the missing tag were present. 802 if (TagKind == tok::kw_enum) 803 ParseEnumSpecifier(Loc, DS, TemplateInfo, AS); 804 else 805 ParseClassSpecifier(TagKind, Loc, DS, TemplateInfo, AS); 806 return true; 807 } 808 } 809 810 // This is almost certainly an invalid type name. Let the action emit a 811 // diagnostic and attempt to recover. 812 ParsedType T; 813 if (Actions.DiagnoseUnknownTypeName(*Tok.getIdentifierInfo(), Loc, 814 getCurScope(), SS, T)) { 815 // The action emitted a diagnostic, so we don't have to. 816 if (T) { 817 // The action has suggested that the type T could be used. Set that as 818 // the type in the declaration specifiers, consume the would-be type 819 // name token, and we're done. 820 const char *PrevSpec; 821 unsigned DiagID; 822 DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID, T); 823 DS.SetRangeEnd(Tok.getLocation()); 824 ConsumeToken(); 825 826 // There may be other declaration specifiers after this. 827 return true; 828 } 829 830 // Fall through; the action had no suggestion for us. 831 } else { 832 // The action did not emit a diagnostic, so emit one now. 833 SourceRange R; 834 if (SS) R = SS->getRange(); 835 Diag(Loc, diag::err_unknown_typename) << Tok.getIdentifierInfo() << R; 836 } 837 838 // Mark this as an error. 839 const char *PrevSpec; 840 unsigned DiagID; 841 DS.SetTypeSpecType(DeclSpec::TST_error, Loc, PrevSpec, DiagID); 842 DS.SetRangeEnd(Tok.getLocation()); 843 ConsumeToken(); 844 845 // TODO: Could inject an invalid typedef decl in an enclosing scope to 846 // avoid rippling error messages on subsequent uses of the same type, 847 // could be useful if #include was forgotten. 848 return false; 849} 850 851/// \brief Determine the declaration specifier context from the declarator 852/// context. 853/// 854/// \param Context the declarator context, which is one of the 855/// Declarator::TheContext enumerator values. 856Parser::DeclSpecContext 857Parser::getDeclSpecContextFromDeclaratorContext(unsigned Context) { 858 if (Context == Declarator::MemberContext) 859 return DSC_class; 860 if (Context == Declarator::FileContext) 861 return DSC_top_level; 862 return DSC_normal; 863} 864 865/// ParseDeclarationSpecifiers 866/// declaration-specifiers: [C99 6.7] 867/// storage-class-specifier declaration-specifiers[opt] 868/// type-specifier declaration-specifiers[opt] 869/// [C99] function-specifier declaration-specifiers[opt] 870/// [GNU] attributes declaration-specifiers[opt] 871/// 872/// storage-class-specifier: [C99 6.7.1] 873/// 'typedef' 874/// 'extern' 875/// 'static' 876/// 'auto' 877/// 'register' 878/// [C++] 'mutable' 879/// [GNU] '__thread' 880/// function-specifier: [C99 6.7.4] 881/// [C99] 'inline' 882/// [C++] 'virtual' 883/// [C++] 'explicit' 884/// 'friend': [C++ dcl.friend] 885/// 'constexpr': [C++0x dcl.constexpr] 886 887/// 888void Parser::ParseDeclarationSpecifiers(DeclSpec &DS, 889 const ParsedTemplateInfo &TemplateInfo, 890 AccessSpecifier AS, 891 DeclSpecContext DSContext) { 892 DS.SetRangeStart(Tok.getLocation()); 893 DS.SetRangeEnd(Tok.getLocation()); 894 while (1) { 895 bool isInvalid = false; 896 const char *PrevSpec = 0; 897 unsigned DiagID = 0; 898 899 SourceLocation Loc = Tok.getLocation(); 900 901 switch (Tok.getKind()) { 902 default: 903 DoneWithDeclSpec: 904 // If this is not a declaration specifier token, we're done reading decl 905 // specifiers. First verify that DeclSpec's are consistent. 906 DS.Finish(Diags, PP); 907 return; 908 909 case tok::code_completion: { 910 Sema::ParserCompletionContext CCC = Sema::PCC_Namespace; 911 if (DS.hasTypeSpecifier()) { 912 bool AllowNonIdentifiers 913 = (getCurScope()->getFlags() & (Scope::ControlScope | 914 Scope::BlockScope | 915 Scope::TemplateParamScope | 916 Scope::FunctionPrototypeScope | 917 Scope::AtCatchScope)) == 0; 918 bool AllowNestedNameSpecifiers 919 = DSContext == DSC_top_level || 920 (DSContext == DSC_class && DS.isFriendSpecified()); 921 922 Actions.CodeCompleteDeclSpec(getCurScope(), DS, 923 AllowNonIdentifiers, 924 AllowNestedNameSpecifiers); 925 ConsumeCodeCompletionToken(); 926 return; 927 } 928 929 if (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate) 930 CCC = DSContext == DSC_class? Sema::PCC_MemberTemplate 931 : Sema::PCC_Template; 932 else if (DSContext == DSC_class) 933 CCC = Sema::PCC_Class; 934 else if (ObjCImpDecl) 935 CCC = Sema::PCC_ObjCImplementation; 936 937 Actions.CodeCompleteOrdinaryName(getCurScope(), CCC); 938 ConsumeCodeCompletionToken(); 939 return; 940 } 941 942 case tok::coloncolon: // ::foo::bar 943 // C++ scope specifier. Annotate and loop, or bail out on error. 944 if (TryAnnotateCXXScopeToken(true)) { 945 if (!DS.hasTypeSpecifier()) 946 DS.SetTypeSpecError(); 947 goto DoneWithDeclSpec; 948 } 949 if (Tok.is(tok::coloncolon)) // ::new or ::delete 950 goto DoneWithDeclSpec; 951 continue; 952 953 case tok::annot_cxxscope: { 954 if (DS.hasTypeSpecifier()) 955 goto DoneWithDeclSpec; 956 957 CXXScopeSpec SS; 958 SS.setScopeRep((NestedNameSpecifier*) Tok.getAnnotationValue()); 959 SS.setRange(Tok.getAnnotationRange()); 960 961 // We are looking for a qualified typename. 962 Token Next = NextToken(); 963 if (Next.is(tok::annot_template_id) && 964 static_cast<TemplateIdAnnotation *>(Next.getAnnotationValue()) 965 ->Kind == TNK_Type_template) { 966 // We have a qualified template-id, e.g., N::A<int> 967 968 // C++ [class.qual]p2: 969 // In a lookup in which the constructor is an acceptable lookup 970 // result and the nested-name-specifier nominates a class C: 971 // 972 // - if the name specified after the 973 // nested-name-specifier, when looked up in C, is the 974 // injected-class-name of C (Clause 9), or 975 // 976 // - if the name specified after the nested-name-specifier 977 // is the same as the identifier or the 978 // simple-template-id's template-name in the last 979 // component of the nested-name-specifier, 980 // 981 // the name is instead considered to name the constructor of 982 // class C. 983 // 984 // Thus, if the template-name is actually the constructor 985 // name, then the code is ill-formed; this interpretation is 986 // reinforced by the NAD status of core issue 635. 987 TemplateIdAnnotation *TemplateId 988 = static_cast<TemplateIdAnnotation *>(Next.getAnnotationValue()); 989 if ((DSContext == DSC_top_level || 990 (DSContext == DSC_class && DS.isFriendSpecified())) && 991 TemplateId->Name && 992 Actions.isCurrentClassName(*TemplateId->Name, getCurScope(), &SS)) { 993 if (isConstructorDeclarator()) { 994 // The user meant this to be an out-of-line constructor 995 // definition, but template arguments are not allowed 996 // there. Just allow this as a constructor; we'll 997 // complain about it later. 998 goto DoneWithDeclSpec; 999 } 1000 1001 // The user meant this to name a type, but it actually names 1002 // a constructor with some extraneous template 1003 // arguments. Complain, then parse it as a type as the user 1004 // intended. 1005 Diag(TemplateId->TemplateNameLoc, 1006 diag::err_out_of_line_template_id_names_constructor) 1007 << TemplateId->Name; 1008 } 1009 1010 DS.getTypeSpecScope() = SS; 1011 ConsumeToken(); // The C++ scope. 1012 assert(Tok.is(tok::annot_template_id) && 1013 "ParseOptionalCXXScopeSpecifier not working"); 1014 AnnotateTemplateIdTokenAsType(&SS); 1015 continue; 1016 } 1017 1018 if (Next.is(tok::annot_typename)) { 1019 DS.getTypeSpecScope() = SS; 1020 ConsumeToken(); // The C++ scope. 1021 if (Tok.getAnnotationValue()) { 1022 ParsedType T = getTypeAnnotation(Tok); 1023 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, 1024 Tok.getAnnotationEndLoc(), 1025 PrevSpec, DiagID, T); 1026 } 1027 else 1028 DS.SetTypeSpecError(); 1029 DS.SetRangeEnd(Tok.getAnnotationEndLoc()); 1030 ConsumeToken(); // The typename 1031 } 1032 1033 if (Next.isNot(tok::identifier)) 1034 goto DoneWithDeclSpec; 1035 1036 // If we're in a context where the identifier could be a class name, 1037 // check whether this is a constructor declaration. 1038 if ((DSContext == DSC_top_level || 1039 (DSContext == DSC_class && DS.isFriendSpecified())) && 1040 Actions.isCurrentClassName(*Next.getIdentifierInfo(), getCurScope(), 1041 &SS)) { 1042 if (isConstructorDeclarator()) 1043 goto DoneWithDeclSpec; 1044 1045 // As noted in C++ [class.qual]p2 (cited above), when the name 1046 // of the class is qualified in a context where it could name 1047 // a constructor, its a constructor name. However, we've 1048 // looked at the declarator, and the user probably meant this 1049 // to be a type. Complain that it isn't supposed to be treated 1050 // as a type, then proceed to parse it as a type. 1051 Diag(Next.getLocation(), diag::err_out_of_line_type_names_constructor) 1052 << Next.getIdentifierInfo(); 1053 } 1054 1055 ParsedType TypeRep = Actions.getTypeName(*Next.getIdentifierInfo(), 1056 Next.getLocation(), 1057 getCurScope(), &SS); 1058 1059 // If the referenced identifier is not a type, then this declspec is 1060 // erroneous: We already checked about that it has no type specifier, and 1061 // C++ doesn't have implicit int. Diagnose it as a typo w.r.t. to the 1062 // typename. 1063 if (TypeRep == 0) { 1064 ConsumeToken(); // Eat the scope spec so the identifier is current. 1065 if (ParseImplicitInt(DS, &SS, TemplateInfo, AS)) continue; 1066 goto DoneWithDeclSpec; 1067 } 1068 1069 DS.getTypeSpecScope() = SS; 1070 ConsumeToken(); // The C++ scope. 1071 1072 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, 1073 DiagID, TypeRep); 1074 if (isInvalid) 1075 break; 1076 1077 DS.SetRangeEnd(Tok.getLocation()); 1078 ConsumeToken(); // The typename. 1079 1080 continue; 1081 } 1082 1083 case tok::annot_typename: { 1084 if (Tok.getAnnotationValue()) { 1085 ParsedType T = getTypeAnnotation(Tok); 1086 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, 1087 DiagID, T); 1088 } else 1089 DS.SetTypeSpecError(); 1090 1091 if (isInvalid) 1092 break; 1093 1094 DS.SetRangeEnd(Tok.getAnnotationEndLoc()); 1095 ConsumeToken(); // The typename 1096 1097 // Objective-C supports syntax of the form 'id<proto1,proto2>' where 'id' 1098 // is a specific typedef and 'itf<proto1,proto2>' where 'itf' is an 1099 // Objective-C interface. 1100 if (Tok.is(tok::less) && getLang().ObjC1) 1101 ParseObjCProtocolQualifiers(DS); 1102 1103 continue; 1104 } 1105 1106 // typedef-name 1107 case tok::identifier: { 1108 // In C++, check to see if this is a scope specifier like foo::bar::, if 1109 // so handle it as such. This is important for ctor parsing. 1110 if (getLang().CPlusPlus) { 1111 if (TryAnnotateCXXScopeToken(true)) { 1112 if (!DS.hasTypeSpecifier()) 1113 DS.SetTypeSpecError(); 1114 goto DoneWithDeclSpec; 1115 } 1116 if (!Tok.is(tok::identifier)) 1117 continue; 1118 } 1119 1120 // This identifier can only be a typedef name if we haven't already seen 1121 // a type-specifier. Without this check we misparse: 1122 // typedef int X; struct Y { short X; }; as 'short int'. 1123 if (DS.hasTypeSpecifier()) 1124 goto DoneWithDeclSpec; 1125 1126 // Check for need to substitute AltiVec keyword tokens. 1127 if (TryAltiVecToken(DS, Loc, PrevSpec, DiagID, isInvalid)) 1128 break; 1129 1130 // It has to be available as a typedef too! 1131 ParsedType TypeRep = 1132 Actions.getTypeName(*Tok.getIdentifierInfo(), 1133 Tok.getLocation(), getCurScope()); 1134 1135 // If this is not a typedef name, don't parse it as part of the declspec, 1136 // it must be an implicit int or an error. 1137 if (!TypeRep) { 1138 if (ParseImplicitInt(DS, 0, TemplateInfo, AS)) continue; 1139 goto DoneWithDeclSpec; 1140 } 1141 1142 // If we're in a context where the identifier could be a class name, 1143 // check whether this is a constructor declaration. 1144 if (getLang().CPlusPlus && DSContext == DSC_class && 1145 Actions.isCurrentClassName(*Tok.getIdentifierInfo(), getCurScope()) && 1146 isConstructorDeclarator()) 1147 goto DoneWithDeclSpec; 1148 1149 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, 1150 DiagID, TypeRep); 1151 if (isInvalid) 1152 break; 1153 1154 DS.SetRangeEnd(Tok.getLocation()); 1155 ConsumeToken(); // The identifier 1156 1157 // Objective-C supports syntax of the form 'id<proto1,proto2>' where 'id' 1158 // is a specific typedef and 'itf<proto1,proto2>' where 'itf' is an 1159 // Objective-C interface. 1160 if (Tok.is(tok::less) && getLang().ObjC1) 1161 ParseObjCProtocolQualifiers(DS); 1162 1163 // Need to support trailing type qualifiers (e.g. "id<p> const"). 1164 // If a type specifier follows, it will be diagnosed elsewhere. 1165 continue; 1166 } 1167 1168 // type-name 1169 case tok::annot_template_id: { 1170 TemplateIdAnnotation *TemplateId 1171 = static_cast<TemplateIdAnnotation *>(Tok.getAnnotationValue()); 1172 if (TemplateId->Kind != TNK_Type_template) { 1173 // This template-id does not refer to a type name, so we're 1174 // done with the type-specifiers. 1175 goto DoneWithDeclSpec; 1176 } 1177 1178 // If we're in a context where the template-id could be a 1179 // constructor name or specialization, check whether this is a 1180 // constructor declaration. 1181 if (getLang().CPlusPlus && DSContext == DSC_class && 1182 Actions.isCurrentClassName(*TemplateId->Name, getCurScope()) && 1183 isConstructorDeclarator()) 1184 goto DoneWithDeclSpec; 1185 1186 // Turn the template-id annotation token into a type annotation 1187 // token, then try again to parse it as a type-specifier. 1188 AnnotateTemplateIdTokenAsType(); 1189 continue; 1190 } 1191 1192 // GNU attributes support. 1193 case tok::kw___attribute: 1194 DS.AddAttributes(ParseGNUAttributes()); 1195 continue; 1196 1197 // Microsoft declspec support. 1198 case tok::kw___declspec: 1199 DS.AddAttributes(ParseMicrosoftDeclSpec()); 1200 continue; 1201 1202 // Microsoft single token adornments. 1203 case tok::kw___forceinline: 1204 // FIXME: Add handling here! 1205 break; 1206 1207 case tok::kw___ptr64: 1208 case tok::kw___w64: 1209 case tok::kw___cdecl: 1210 case tok::kw___stdcall: 1211 case tok::kw___fastcall: 1212 case tok::kw___thiscall: 1213 DS.AddAttributes(ParseMicrosoftTypeAttributes()); 1214 continue; 1215 1216 // Borland single token adornments. 1217 case tok::kw___pascal: 1218 DS.AddAttributes(ParseBorlandTypeAttributes()); 1219 continue; 1220 1221 // storage-class-specifier 1222 case tok::kw_typedef: 1223 isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_typedef, Loc, PrevSpec, 1224 DiagID); 1225 break; 1226 case tok::kw_extern: 1227 if (DS.isThreadSpecified()) 1228 Diag(Tok, diag::ext_thread_before) << "extern"; 1229 isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_extern, Loc, PrevSpec, 1230 DiagID); 1231 break; 1232 case tok::kw___private_extern__: 1233 isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_private_extern, Loc, 1234 PrevSpec, DiagID); 1235 break; 1236 case tok::kw_static: 1237 if (DS.isThreadSpecified()) 1238 Diag(Tok, diag::ext_thread_before) << "static"; 1239 isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_static, Loc, PrevSpec, 1240 DiagID); 1241 break; 1242 case tok::kw_auto: 1243 if (getLang().CPlusPlus0x) 1244 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_auto, Loc, PrevSpec, 1245 DiagID); 1246 else 1247 isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_auto, Loc, PrevSpec, 1248 DiagID); 1249 break; 1250 case tok::kw_register: 1251 isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_register, Loc, PrevSpec, 1252 DiagID); 1253 break; 1254 case tok::kw_mutable: 1255 isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_mutable, Loc, PrevSpec, 1256 DiagID); 1257 break; 1258 case tok::kw___thread: 1259 isInvalid = DS.SetStorageClassSpecThread(Loc, PrevSpec, DiagID); 1260 break; 1261 1262 // function-specifier 1263 case tok::kw_inline: 1264 isInvalid = DS.SetFunctionSpecInline(Loc, PrevSpec, DiagID); 1265 break; 1266 case tok::kw_virtual: 1267 isInvalid = DS.SetFunctionSpecVirtual(Loc, PrevSpec, DiagID); 1268 break; 1269 case tok::kw_explicit: 1270 isInvalid = DS.SetFunctionSpecExplicit(Loc, PrevSpec, DiagID); 1271 break; 1272 1273 // friend 1274 case tok::kw_friend: 1275 if (DSContext == DSC_class) 1276 isInvalid = DS.SetFriendSpec(Loc, PrevSpec, DiagID); 1277 else { 1278 PrevSpec = ""; // not actually used by the diagnostic 1279 DiagID = diag::err_friend_invalid_in_context; 1280 isInvalid = true; 1281 } 1282 break; 1283 1284 // constexpr 1285 case tok::kw_constexpr: 1286 isInvalid = DS.SetConstexprSpec(Loc, PrevSpec, DiagID); 1287 break; 1288 1289 // type-specifier 1290 case tok::kw_short: 1291 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_short, Loc, PrevSpec, 1292 DiagID); 1293 break; 1294 case tok::kw_long: 1295 if (DS.getTypeSpecWidth() != DeclSpec::TSW_long) 1296 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_long, Loc, PrevSpec, 1297 DiagID); 1298 else 1299 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec, 1300 DiagID); 1301 break; 1302 case tok::kw_signed: 1303 isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_signed, Loc, PrevSpec, 1304 DiagID); 1305 break; 1306 case tok::kw_unsigned: 1307 isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_unsigned, Loc, PrevSpec, 1308 DiagID); 1309 break; 1310 case tok::kw__Complex: 1311 isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_complex, Loc, PrevSpec, 1312 DiagID); 1313 break; 1314 case tok::kw__Imaginary: 1315 isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_imaginary, Loc, PrevSpec, 1316 DiagID); 1317 break; 1318 case tok::kw_void: 1319 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec, 1320 DiagID); 1321 break; 1322 case tok::kw_char: 1323 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec, 1324 DiagID); 1325 break; 1326 case tok::kw_int: 1327 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec, 1328 DiagID); 1329 break; 1330 case tok::kw_float: 1331 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec, 1332 DiagID); 1333 break; 1334 case tok::kw_double: 1335 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec, 1336 DiagID); 1337 break; 1338 case tok::kw_wchar_t: 1339 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec, 1340 DiagID); 1341 break; 1342 case tok::kw_char16_t: 1343 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char16, Loc, PrevSpec, 1344 DiagID); 1345 break; 1346 case tok::kw_char32_t: 1347 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char32, Loc, PrevSpec, 1348 DiagID); 1349 break; 1350 case tok::kw_bool: 1351 case tok::kw__Bool: 1352 if (Tok.is(tok::kw_bool) && 1353 DS.getTypeSpecType() != DeclSpec::TST_unspecified && 1354 DS.getStorageClassSpec() == DeclSpec::SCS_typedef) { 1355 PrevSpec = ""; // Not used by the diagnostic. 1356 DiagID = diag::err_bool_redeclaration; 1357 isInvalid = true; 1358 } else { 1359 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec, 1360 DiagID); 1361 } 1362 break; 1363 case tok::kw__Decimal32: 1364 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal32, Loc, PrevSpec, 1365 DiagID); 1366 break; 1367 case tok::kw__Decimal64: 1368 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal64, Loc, PrevSpec, 1369 DiagID); 1370 break; 1371 case tok::kw__Decimal128: 1372 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal128, Loc, PrevSpec, 1373 DiagID); 1374 break; 1375 case tok::kw___vector: 1376 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID); 1377 break; 1378 case tok::kw___pixel: 1379 isInvalid = DS.SetTypeAltiVecPixel(true, Loc, PrevSpec, DiagID); 1380 break; 1381 1382 // class-specifier: 1383 case tok::kw_class: 1384 case tok::kw_struct: 1385 case tok::kw_union: { 1386 tok::TokenKind Kind = Tok.getKind(); 1387 ConsumeToken(); 1388 ParseClassSpecifier(Kind, Loc, DS, TemplateInfo, AS); 1389 continue; 1390 } 1391 1392 // enum-specifier: 1393 case tok::kw_enum: 1394 ConsumeToken(); 1395 ParseEnumSpecifier(Loc, DS, TemplateInfo, AS); 1396 continue; 1397 1398 // cv-qualifier: 1399 case tok::kw_const: 1400 isInvalid = DS.SetTypeQual(DeclSpec::TQ_const, Loc, PrevSpec, DiagID, 1401 getLang()); 1402 break; 1403 case tok::kw_volatile: 1404 isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, DiagID, 1405 getLang()); 1406 break; 1407 case tok::kw_restrict: 1408 isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, DiagID, 1409 getLang()); 1410 break; 1411 1412 // C++ typename-specifier: 1413 case tok::kw_typename: 1414 if (TryAnnotateTypeOrScopeToken()) { 1415 DS.SetTypeSpecError(); 1416 goto DoneWithDeclSpec; 1417 } 1418 if (!Tok.is(tok::kw_typename)) 1419 continue; 1420 break; 1421 1422 // GNU typeof support. 1423 case tok::kw_typeof: 1424 ParseTypeofSpecifier(DS); 1425 continue; 1426 1427 case tok::kw_decltype: 1428 ParseDecltypeSpecifier(DS); 1429 continue; 1430 1431 case tok::less: 1432 // GCC ObjC supports types like "<SomeProtocol>" as a synonym for 1433 // "id<SomeProtocol>". This is hopelessly old fashioned and dangerous, 1434 // but we support it. 1435 if (DS.hasTypeSpecifier() || !getLang().ObjC1) 1436 goto DoneWithDeclSpec; 1437 1438 if (!ParseObjCProtocolQualifiers(DS)) 1439 Diag(Loc, diag::warn_objc_protocol_qualifier_missing_id) 1440 << FixItHint::CreateInsertion(Loc, "id") 1441 << SourceRange(Loc, DS.getSourceRange().getEnd()); 1442 1443 // Need to support trailing type qualifiers (e.g. "id<p> const"). 1444 // If a type specifier follows, it will be diagnosed elsewhere. 1445 continue; 1446 } 1447 // If the specifier wasn't legal, issue a diagnostic. 1448 if (isInvalid) { 1449 assert(PrevSpec && "Method did not return previous specifier!"); 1450 assert(DiagID); 1451 1452 if (DiagID == diag::ext_duplicate_declspec) 1453 Diag(Tok, DiagID) 1454 << PrevSpec << FixItHint::CreateRemoval(Tok.getLocation()); 1455 else 1456 Diag(Tok, DiagID) << PrevSpec; 1457 } 1458 DS.SetRangeEnd(Tok.getLocation()); 1459 ConsumeToken(); 1460 } 1461} 1462 1463/// ParseOptionalTypeSpecifier - Try to parse a single type-specifier. We 1464/// primarily follow the C++ grammar with additions for C99 and GNU, 1465/// which together subsume the C grammar. Note that the C++ 1466/// type-specifier also includes the C type-qualifier (for const, 1467/// volatile, and C99 restrict). Returns true if a type-specifier was 1468/// found (and parsed), false otherwise. 1469/// 1470/// type-specifier: [C++ 7.1.5] 1471/// simple-type-specifier 1472/// class-specifier 1473/// enum-specifier 1474/// elaborated-type-specifier [TODO] 1475/// cv-qualifier 1476/// 1477/// cv-qualifier: [C++ 7.1.5.1] 1478/// 'const' 1479/// 'volatile' 1480/// [C99] 'restrict' 1481/// 1482/// simple-type-specifier: [ C++ 7.1.5.2] 1483/// '::'[opt] nested-name-specifier[opt] type-name [TODO] 1484/// '::'[opt] nested-name-specifier 'template' template-id [TODO] 1485/// 'char' 1486/// 'wchar_t' 1487/// 'bool' 1488/// 'short' 1489/// 'int' 1490/// 'long' 1491/// 'signed' 1492/// 'unsigned' 1493/// 'float' 1494/// 'double' 1495/// 'void' 1496/// [C99] '_Bool' 1497/// [C99] '_Complex' 1498/// [C99] '_Imaginary' // Removed in TC2? 1499/// [GNU] '_Decimal32' 1500/// [GNU] '_Decimal64' 1501/// [GNU] '_Decimal128' 1502/// [GNU] typeof-specifier 1503/// [OBJC] class-name objc-protocol-refs[opt] [TODO] 1504/// [OBJC] typedef-name objc-protocol-refs[opt] [TODO] 1505/// [C++0x] 'decltype' ( expression ) 1506/// [AltiVec] '__vector' 1507bool Parser::ParseOptionalTypeSpecifier(DeclSpec &DS, bool& isInvalid, 1508 const char *&PrevSpec, 1509 unsigned &DiagID, 1510 const ParsedTemplateInfo &TemplateInfo, 1511 bool SuppressDeclarations) { 1512 SourceLocation Loc = Tok.getLocation(); 1513 1514 switch (Tok.getKind()) { 1515 case tok::identifier: // foo::bar 1516 // If we already have a type specifier, this identifier is not a type. 1517 if (DS.getTypeSpecType() != DeclSpec::TST_unspecified || 1518 DS.getTypeSpecWidth() != DeclSpec::TSW_unspecified || 1519 DS.getTypeSpecSign() != DeclSpec::TSS_unspecified) 1520 return false; 1521 // Check for need to substitute AltiVec keyword tokens. 1522 if (TryAltiVecToken(DS, Loc, PrevSpec, DiagID, isInvalid)) 1523 break; 1524 // Fall through. 1525 case tok::kw_typename: // typename foo::bar 1526 // Annotate typenames and C++ scope specifiers. If we get one, just 1527 // recurse to handle whatever we get. 1528 if (TryAnnotateTypeOrScopeToken()) 1529 return true; 1530 if (Tok.is(tok::identifier)) 1531 return false; 1532 return ParseOptionalTypeSpecifier(DS, isInvalid, PrevSpec, DiagID, 1533 TemplateInfo, SuppressDeclarations); 1534 case tok::coloncolon: // ::foo::bar 1535 if (NextToken().is(tok::kw_new) || // ::new 1536 NextToken().is(tok::kw_delete)) // ::delete 1537 return false; 1538 1539 // Annotate typenames and C++ scope specifiers. If we get one, just 1540 // recurse to handle whatever we get. 1541 if (TryAnnotateTypeOrScopeToken()) 1542 return true; 1543 return ParseOptionalTypeSpecifier(DS, isInvalid, PrevSpec, DiagID, 1544 TemplateInfo, SuppressDeclarations); 1545 1546 // simple-type-specifier: 1547 case tok::annot_typename: { 1548 if (ParsedType T = getTypeAnnotation(Tok)) { 1549 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, 1550 Tok.getAnnotationEndLoc(), PrevSpec, 1551 DiagID, T); 1552 } else 1553 DS.SetTypeSpecError(); 1554 DS.SetRangeEnd(Tok.getAnnotationEndLoc()); 1555 ConsumeToken(); // The typename 1556 1557 // Objective-C supports syntax of the form 'id<proto1,proto2>' where 'id' 1558 // is a specific typedef and 'itf<proto1,proto2>' where 'itf' is an 1559 // Objective-C interface. If we don't have Objective-C or a '<', this is 1560 // just a normal reference to a typedef name. 1561 if (Tok.is(tok::less) && getLang().ObjC1) 1562 ParseObjCProtocolQualifiers(DS); 1563 1564 return true; 1565 } 1566 1567 case tok::kw_short: 1568 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_short, Loc, PrevSpec, DiagID); 1569 break; 1570 case tok::kw_long: 1571 if (DS.getTypeSpecWidth() != DeclSpec::TSW_long) 1572 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_long, Loc, PrevSpec, 1573 DiagID); 1574 else 1575 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec, 1576 DiagID); 1577 break; 1578 case tok::kw_signed: 1579 isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_signed, Loc, PrevSpec, DiagID); 1580 break; 1581 case tok::kw_unsigned: 1582 isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_unsigned, Loc, PrevSpec, 1583 DiagID); 1584 break; 1585 case tok::kw__Complex: 1586 isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_complex, Loc, PrevSpec, 1587 DiagID); 1588 break; 1589 case tok::kw__Imaginary: 1590 isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_imaginary, Loc, PrevSpec, 1591 DiagID); 1592 break; 1593 case tok::kw_void: 1594 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec, DiagID); 1595 break; 1596 case tok::kw_char: 1597 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec, DiagID); 1598 break; 1599 case tok::kw_int: 1600 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec, DiagID); 1601 break; 1602 case tok::kw_float: 1603 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec, DiagID); 1604 break; 1605 case tok::kw_double: 1606 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec, DiagID); 1607 break; 1608 case tok::kw_wchar_t: 1609 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec, DiagID); 1610 break; 1611 case tok::kw_char16_t: 1612 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char16, Loc, PrevSpec, DiagID); 1613 break; 1614 case tok::kw_char32_t: 1615 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char32, Loc, PrevSpec, DiagID); 1616 break; 1617 case tok::kw_bool: 1618 case tok::kw__Bool: 1619 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec, DiagID); 1620 break; 1621 case tok::kw__Decimal32: 1622 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal32, Loc, PrevSpec, 1623 DiagID); 1624 break; 1625 case tok::kw__Decimal64: 1626 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal64, Loc, PrevSpec, 1627 DiagID); 1628 break; 1629 case tok::kw__Decimal128: 1630 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal128, Loc, PrevSpec, 1631 DiagID); 1632 break; 1633 case tok::kw___vector: 1634 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID); 1635 break; 1636 case tok::kw___pixel: 1637 isInvalid = DS.SetTypeAltiVecPixel(true, Loc, PrevSpec, DiagID); 1638 break; 1639 1640 // class-specifier: 1641 case tok::kw_class: 1642 case tok::kw_struct: 1643 case tok::kw_union: { 1644 tok::TokenKind Kind = Tok.getKind(); 1645 ConsumeToken(); 1646 ParseClassSpecifier(Kind, Loc, DS, TemplateInfo, AS_none, 1647 SuppressDeclarations); 1648 return true; 1649 } 1650 1651 // enum-specifier: 1652 case tok::kw_enum: 1653 ConsumeToken(); 1654 ParseEnumSpecifier(Loc, DS, TemplateInfo, AS_none); 1655 return true; 1656 1657 // cv-qualifier: 1658 case tok::kw_const: 1659 isInvalid = DS.SetTypeQual(DeclSpec::TQ_const , Loc, PrevSpec, 1660 DiagID, getLang()); 1661 break; 1662 case tok::kw_volatile: 1663 isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, 1664 DiagID, getLang()); 1665 break; 1666 case tok::kw_restrict: 1667 isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, 1668 DiagID, getLang()); 1669 break; 1670 1671 // GNU typeof support. 1672 case tok::kw_typeof: 1673 ParseTypeofSpecifier(DS); 1674 return true; 1675 1676 // C++0x decltype support. 1677 case tok::kw_decltype: 1678 ParseDecltypeSpecifier(DS); 1679 return true; 1680 1681 // C++0x auto support. 1682 case tok::kw_auto: 1683 if (!getLang().CPlusPlus0x) 1684 return false; 1685 1686 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_auto, Loc, PrevSpec, DiagID); 1687 break; 1688 1689 case tok::kw___ptr64: 1690 case tok::kw___w64: 1691 case tok::kw___cdecl: 1692 case tok::kw___stdcall: 1693 case tok::kw___fastcall: 1694 case tok::kw___thiscall: 1695 DS.AddAttributes(ParseMicrosoftTypeAttributes()); 1696 return true; 1697 1698 case tok::kw___pascal: 1699 DS.AddAttributes(ParseBorlandTypeAttributes()); 1700 return true; 1701 1702 default: 1703 // Not a type-specifier; do nothing. 1704 return false; 1705 } 1706 1707 // If the specifier combination wasn't legal, issue a diagnostic. 1708 if (isInvalid) { 1709 assert(PrevSpec && "Method did not return previous specifier!"); 1710 // Pick between error or extwarn. 1711 Diag(Tok, DiagID) << PrevSpec; 1712 } 1713 DS.SetRangeEnd(Tok.getLocation()); 1714 ConsumeToken(); // whatever we parsed above. 1715 return true; 1716} 1717 1718/// ParseStructDeclaration - Parse a struct declaration without the terminating 1719/// semicolon. 1720/// 1721/// struct-declaration: 1722/// specifier-qualifier-list struct-declarator-list 1723/// [GNU] __extension__ struct-declaration 1724/// [GNU] specifier-qualifier-list 1725/// struct-declarator-list: 1726/// struct-declarator 1727/// struct-declarator-list ',' struct-declarator 1728/// [GNU] struct-declarator-list ',' attributes[opt] struct-declarator 1729/// struct-declarator: 1730/// declarator 1731/// [GNU] declarator attributes[opt] 1732/// declarator[opt] ':' constant-expression 1733/// [GNU] declarator[opt] ':' constant-expression attributes[opt] 1734/// 1735void Parser:: 1736ParseStructDeclaration(DeclSpec &DS, FieldCallback &Fields) { 1737 if (Tok.is(tok::kw___extension__)) { 1738 // __extension__ silences extension warnings in the subexpression. 1739 ExtensionRAIIObject O(Diags); // Use RAII to do this. 1740 ConsumeToken(); 1741 return ParseStructDeclaration(DS, Fields); 1742 } 1743 1744 // Parse the common specifier-qualifiers-list piece. 1745 SourceLocation DSStart = Tok.getLocation(); 1746 ParseSpecifierQualifierList(DS); 1747 1748 // If there are no declarators, this is a free-standing declaration 1749 // specifier. Let the actions module cope with it. 1750 if (Tok.is(tok::semi)) { 1751 Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS_none, DS); 1752 return; 1753 } 1754 1755 // Read struct-declarators until we find the semicolon. 1756 bool FirstDeclarator = true; 1757 while (1) { 1758 ParsingDeclRAIIObject PD(*this); 1759 FieldDeclarator DeclaratorInfo(DS); 1760 1761 // Attributes are only allowed here on successive declarators. 1762 if (!FirstDeclarator && Tok.is(tok::kw___attribute)) { 1763 SourceLocation Loc; 1764 AttributeList *AttrList = ParseGNUAttributes(&Loc); 1765 DeclaratorInfo.D.AddAttributes(AttrList, Loc); 1766 } 1767 1768 /// struct-declarator: declarator 1769 /// struct-declarator: declarator[opt] ':' constant-expression 1770 if (Tok.isNot(tok::colon)) { 1771 // Don't parse FOO:BAR as if it were a typo for FOO::BAR. 1772 ColonProtectionRAIIObject X(*this); 1773 ParseDeclarator(DeclaratorInfo.D); 1774 } 1775 1776 if (Tok.is(tok::colon)) { 1777 ConsumeToken(); 1778 ExprResult Res(ParseConstantExpression()); 1779 if (Res.isInvalid()) 1780 SkipUntil(tok::semi, true, true); 1781 else 1782 DeclaratorInfo.BitfieldSize = Res.release(); 1783 } 1784 1785 // If attributes exist after the declarator, parse them. 1786 if (Tok.is(tok::kw___attribute)) { 1787 SourceLocation Loc; 1788 AttributeList *AttrList = ParseGNUAttributes(&Loc); 1789 DeclaratorInfo.D.AddAttributes(AttrList, Loc); 1790 } 1791 1792 // We're done with this declarator; invoke the callback. 1793 Decl *D = Fields.invoke(DeclaratorInfo); 1794 PD.complete(D); 1795 1796 // If we don't have a comma, it is either the end of the list (a ';') 1797 // or an error, bail out. 1798 if (Tok.isNot(tok::comma)) 1799 return; 1800 1801 // Consume the comma. 1802 ConsumeToken(); 1803 1804 FirstDeclarator = false; 1805 } 1806} 1807 1808/// ParseStructUnionBody 1809/// struct-contents: 1810/// struct-declaration-list 1811/// [EXT] empty 1812/// [GNU] "struct-declaration-list" without terminatoring ';' 1813/// struct-declaration-list: 1814/// struct-declaration 1815/// struct-declaration-list struct-declaration 1816/// [OBC] '@' 'defs' '(' class-name ')' 1817/// 1818void Parser::ParseStructUnionBody(SourceLocation RecordLoc, 1819 unsigned TagType, Decl *TagDecl) { 1820 PrettyDeclStackTraceEntry CrashInfo(Actions, TagDecl, RecordLoc, 1821 "parsing struct/union body"); 1822 1823 SourceLocation LBraceLoc = ConsumeBrace(); 1824 1825 ParseScope StructScope(this, Scope::ClassScope|Scope::DeclScope); 1826 Actions.ActOnTagStartDefinition(getCurScope(), TagDecl); 1827 1828 // Empty structs are an extension in C (C99 6.7.2.1p7), but are allowed in 1829 // C++. 1830 if (Tok.is(tok::r_brace) && !getLang().CPlusPlus) 1831 Diag(Tok, diag::ext_empty_struct_union) 1832 << (TagType == TST_union); 1833 1834 llvm::SmallVector<Decl *, 32> FieldDecls; 1835 1836 // While we still have something to read, read the declarations in the struct. 1837 while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) { 1838 // Each iteration of this loop reads one struct-declaration. 1839 1840 // Check for extraneous top-level semicolon. 1841 if (Tok.is(tok::semi)) { 1842 Diag(Tok, diag::ext_extra_struct_semi) 1843 << DeclSpec::getSpecifierName((DeclSpec::TST)TagType) 1844 << FixItHint::CreateRemoval(Tok.getLocation()); 1845 ConsumeToken(); 1846 continue; 1847 } 1848 1849 // Parse all the comma separated declarators. 1850 DeclSpec DS; 1851 1852 if (!Tok.is(tok::at)) { 1853 struct CFieldCallback : FieldCallback { 1854 Parser &P; 1855 Decl *TagDecl; 1856 llvm::SmallVectorImpl<Decl *> &FieldDecls; 1857 1858 CFieldCallback(Parser &P, Decl *TagDecl, 1859 llvm::SmallVectorImpl<Decl *> &FieldDecls) : 1860 P(P), TagDecl(TagDecl), FieldDecls(FieldDecls) {} 1861 1862 virtual Decl *invoke(FieldDeclarator &FD) { 1863 // Install the declarator into the current TagDecl. 1864 Decl *Field = P.Actions.ActOnField(P.getCurScope(), TagDecl, 1865 FD.D.getDeclSpec().getSourceRange().getBegin(), 1866 FD.D, FD.BitfieldSize); 1867 FieldDecls.push_back(Field); 1868 return Field; 1869 } 1870 } Callback(*this, TagDecl, FieldDecls); 1871 1872 ParseStructDeclaration(DS, Callback); 1873 } else { // Handle @defs 1874 ConsumeToken(); 1875 if (!Tok.isObjCAtKeyword(tok::objc_defs)) { 1876 Diag(Tok, diag::err_unexpected_at); 1877 SkipUntil(tok::semi, true); 1878 continue; 1879 } 1880 ConsumeToken(); 1881 ExpectAndConsume(tok::l_paren, diag::err_expected_lparen); 1882 if (!Tok.is(tok::identifier)) { 1883 Diag(Tok, diag::err_expected_ident); 1884 SkipUntil(tok::semi, true); 1885 continue; 1886 } 1887 llvm::SmallVector<Decl *, 16> Fields; 1888 Actions.ActOnDefs(getCurScope(), TagDecl, Tok.getLocation(), 1889 Tok.getIdentifierInfo(), Fields); 1890 FieldDecls.insert(FieldDecls.end(), Fields.begin(), Fields.end()); 1891 ConsumeToken(); 1892 ExpectAndConsume(tok::r_paren, diag::err_expected_rparen); 1893 } 1894 1895 if (Tok.is(tok::semi)) { 1896 ConsumeToken(); 1897 } else if (Tok.is(tok::r_brace)) { 1898 ExpectAndConsume(tok::semi, diag::ext_expected_semi_decl_list); 1899 break; 1900 } else { 1901 ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list); 1902 // Skip to end of block or statement to avoid ext-warning on extra ';'. 1903 SkipUntil(tok::r_brace, true, true); 1904 // If we stopped at a ';', eat it. 1905 if (Tok.is(tok::semi)) ConsumeToken(); 1906 } 1907 } 1908 1909 SourceLocation RBraceLoc = MatchRHSPunctuation(tok::r_brace, LBraceLoc); 1910 1911 AttributeList *AttrList = 0; 1912 // If attributes exist after struct contents, parse them. 1913 if (Tok.is(tok::kw___attribute)) 1914 AttrList = ParseGNUAttributes(); 1915 1916 Actions.ActOnFields(getCurScope(), 1917 RecordLoc, TagDecl, FieldDecls.data(), FieldDecls.size(), 1918 LBraceLoc, RBraceLoc, 1919 AttrList); 1920 StructScope.Exit(); 1921 Actions.ActOnTagFinishDefinition(getCurScope(), TagDecl, RBraceLoc); 1922} 1923 1924 1925/// ParseEnumSpecifier 1926/// enum-specifier: [C99 6.7.2.2] 1927/// 'enum' identifier[opt] '{' enumerator-list '}' 1928///[C99/C++]'enum' identifier[opt] '{' enumerator-list ',' '}' 1929/// [GNU] 'enum' attributes[opt] identifier[opt] '{' enumerator-list ',' [opt] 1930/// '}' attributes[opt] 1931/// 'enum' identifier 1932/// [GNU] 'enum' attributes[opt] identifier 1933/// 1934/// [C++0x] enum-head '{' enumerator-list[opt] '}' 1935/// [C++0x] enum-head '{' enumerator-list ',' '}' 1936/// 1937/// enum-head: [C++0x] 1938/// enum-key attributes[opt] identifier[opt] enum-base[opt] 1939/// enum-key attributes[opt] nested-name-specifier identifier enum-base[opt] 1940/// 1941/// enum-key: [C++0x] 1942/// 'enum' 1943/// 'enum' 'class' 1944/// 'enum' 'struct' 1945/// 1946/// enum-base: [C++0x] 1947/// ':' type-specifier-seq 1948/// 1949/// [C++] elaborated-type-specifier: 1950/// [C++] 'enum' '::'[opt] nested-name-specifier[opt] identifier 1951/// 1952void Parser::ParseEnumSpecifier(SourceLocation StartLoc, DeclSpec &DS, 1953 const ParsedTemplateInfo &TemplateInfo, 1954 AccessSpecifier AS) { 1955 // Parse the tag portion of this. 1956 if (Tok.is(tok::code_completion)) { 1957 // Code completion for an enum name. 1958 Actions.CodeCompleteTag(getCurScope(), DeclSpec::TST_enum); 1959 ConsumeCodeCompletionToken(); 1960 } 1961 1962 AttributeList *Attr = 0; 1963 // If attributes exist after tag, parse them. 1964 if (Tok.is(tok::kw___attribute)) 1965 Attr = ParseGNUAttributes(); 1966 1967 CXXScopeSpec &SS = DS.getTypeSpecScope(); 1968 if (getLang().CPlusPlus) { 1969 if (ParseOptionalCXXScopeSpecifier(SS, ParsedType(), false)) 1970 return; 1971 1972 if (SS.isSet() && Tok.isNot(tok::identifier)) { 1973 Diag(Tok, diag::err_expected_ident); 1974 if (Tok.isNot(tok::l_brace)) { 1975 // Has no name and is not a definition. 1976 // Skip the rest of this declarator, up until the comma or semicolon. 1977 SkipUntil(tok::comma, true); 1978 return; 1979 } 1980 } 1981 } 1982 1983 bool IsScopedEnum = false; 1984 1985 if (getLang().CPlusPlus0x && (Tok.is(tok::kw_class) 1986 || Tok.is(tok::kw_struct))) { 1987 ConsumeToken(); 1988 IsScopedEnum = true; 1989 } 1990 1991 // Must have either 'enum name' or 'enum {...}'. 1992 if (Tok.isNot(tok::identifier) && Tok.isNot(tok::l_brace)) { 1993 Diag(Tok, diag::err_expected_ident_lbrace); 1994 1995 // Skip the rest of this declarator, up until the comma or semicolon. 1996 SkipUntil(tok::comma, true); 1997 return; 1998 } 1999 2000 // If an identifier is present, consume and remember it. 2001 IdentifierInfo *Name = 0; 2002 SourceLocation NameLoc; 2003 if (Tok.is(tok::identifier)) { 2004 Name = Tok.getIdentifierInfo(); 2005 NameLoc = ConsumeToken(); 2006 } 2007 2008 if (!Name && IsScopedEnum) { 2009 // C++0x 7.2p2: The optional identifier shall not be omitted in the 2010 // declaration of a scoped enumeration. 2011 Diag(Tok, diag::err_scoped_enum_missing_identifier); 2012 IsScopedEnum = false; 2013 } 2014 2015 TypeResult BaseType; 2016 2017 if (getLang().CPlusPlus0x && Tok.is(tok::colon)) { 2018 ConsumeToken(); 2019 SourceRange Range; 2020 BaseType = ParseTypeName(&Range); 2021 } 2022 2023 // There are three options here. If we have 'enum foo;', then this is a 2024 // forward declaration. If we have 'enum foo {...' then this is a 2025 // definition. Otherwise we have something like 'enum foo xyz', a reference. 2026 // 2027 // This is needed to handle stuff like this right (C99 6.7.2.3p11): 2028 // enum foo {..}; void bar() { enum foo; } <- new foo in bar. 2029 // enum foo {..}; void bar() { enum foo x; } <- use of old foo. 2030 // 2031 Sema::TagUseKind TUK; 2032 if (Tok.is(tok::l_brace)) 2033 TUK = Sema::TUK_Definition; 2034 else if (Tok.is(tok::semi)) 2035 TUK = Sema::TUK_Declaration; 2036 else 2037 TUK = Sema::TUK_Reference; 2038 2039 // enums cannot be templates, although they can be referenced from a 2040 // template. 2041 if (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate && 2042 TUK != Sema::TUK_Reference) { 2043 Diag(Tok, diag::err_enum_template); 2044 2045 // Skip the rest of this declarator, up until the comma or semicolon. 2046 SkipUntil(tok::comma, true); 2047 return; 2048 } 2049 2050 bool Owned = false; 2051 bool IsDependent = false; 2052 SourceLocation TSTLoc = NameLoc.isValid()? NameLoc : StartLoc; 2053 const char *PrevSpec = 0; 2054 unsigned DiagID; 2055 Decl *TagDecl = Actions.ActOnTag(getCurScope(), DeclSpec::TST_enum, TUK, 2056 StartLoc, SS, Name, NameLoc, Attr, 2057 AS, 2058 MultiTemplateParamsArg(Actions), 2059 Owned, IsDependent, IsScopedEnum, 2060 BaseType); 2061 2062 if (IsDependent) { 2063 // This enum has a dependent nested-name-specifier. Handle it as a 2064 // dependent tag. 2065 if (!Name) { 2066 DS.SetTypeSpecError(); 2067 Diag(Tok, diag::err_expected_type_name_after_typename); 2068 return; 2069 } 2070 2071 TypeResult Type = Actions.ActOnDependentTag(getCurScope(), DeclSpec::TST_enum, 2072 TUK, SS, Name, StartLoc, 2073 NameLoc); 2074 if (Type.isInvalid()) { 2075 DS.SetTypeSpecError(); 2076 return; 2077 } 2078 2079 if (DS.SetTypeSpecType(DeclSpec::TST_typename, TSTLoc, PrevSpec, DiagID, 2080 Type.get())) 2081 Diag(StartLoc, DiagID) << PrevSpec; 2082 2083 return; 2084 } 2085 2086 if (!TagDecl) { 2087 // The action failed to produce an enumeration tag. If this is a 2088 // definition, consume the entire definition. 2089 if (Tok.is(tok::l_brace)) { 2090 ConsumeBrace(); 2091 SkipUntil(tok::r_brace); 2092 } 2093 2094 DS.SetTypeSpecError(); 2095 return; 2096 } 2097 2098 if (Tok.is(tok::l_brace)) 2099 ParseEnumBody(StartLoc, TagDecl); 2100 2101 // FIXME: The DeclSpec should keep the locations of both the keyword 2102 // and the name (if there is one). 2103 if (DS.SetTypeSpecType(DeclSpec::TST_enum, TSTLoc, PrevSpec, DiagID, 2104 TagDecl, Owned)) 2105 Diag(StartLoc, DiagID) << PrevSpec; 2106} 2107 2108/// ParseEnumBody - Parse a {} enclosed enumerator-list. 2109/// enumerator-list: 2110/// enumerator 2111/// enumerator-list ',' enumerator 2112/// enumerator: 2113/// enumeration-constant 2114/// enumeration-constant '=' constant-expression 2115/// enumeration-constant: 2116/// identifier 2117/// 2118void Parser::ParseEnumBody(SourceLocation StartLoc, Decl *EnumDecl) { 2119 // Enter the scope of the enum body and start the definition. 2120 ParseScope EnumScope(this, Scope::DeclScope); 2121 Actions.ActOnTagStartDefinition(getCurScope(), EnumDecl); 2122 2123 SourceLocation LBraceLoc = ConsumeBrace(); 2124 2125 // C does not allow an empty enumerator-list, C++ does [dcl.enum]. 2126 if (Tok.is(tok::r_brace) && !getLang().CPlusPlus) 2127 Diag(Tok, diag::error_empty_enum); 2128 2129 llvm::SmallVector<Decl *, 32> EnumConstantDecls; 2130 2131 Decl *LastEnumConstDecl = 0; 2132 2133 // Parse the enumerator-list. 2134 while (Tok.is(tok::identifier)) { 2135 IdentifierInfo *Ident = Tok.getIdentifierInfo(); 2136 SourceLocation IdentLoc = ConsumeToken(); 2137 2138 // If attributes exist after the enumerator, parse them. 2139 AttributeList *Attr = 0; 2140 if (Tok.is(tok::kw___attribute)) 2141 Attr = ParseGNUAttributes(); 2142 2143 SourceLocation EqualLoc; 2144 ExprResult AssignedVal; 2145 if (Tok.is(tok::equal)) { 2146 EqualLoc = ConsumeToken(); 2147 AssignedVal = ParseConstantExpression(); 2148 if (AssignedVal.isInvalid()) 2149 SkipUntil(tok::comma, tok::r_brace, true, true); 2150 } 2151 2152 // Install the enumerator constant into EnumDecl. 2153 Decl *EnumConstDecl = Actions.ActOnEnumConstant(getCurScope(), EnumDecl, 2154 LastEnumConstDecl, 2155 IdentLoc, Ident, 2156 Attr, EqualLoc, 2157 AssignedVal.release()); 2158 EnumConstantDecls.push_back(EnumConstDecl); 2159 LastEnumConstDecl = EnumConstDecl; 2160 2161 if (Tok.is(tok::identifier)) { 2162 // We're missing a comma between enumerators. 2163 SourceLocation Loc = PP.getLocForEndOfToken(PrevTokLocation); 2164 Diag(Loc, diag::err_enumerator_list_missing_comma) 2165 << FixItHint::CreateInsertion(Loc, ", "); 2166 continue; 2167 } 2168 2169 if (Tok.isNot(tok::comma)) 2170 break; 2171 SourceLocation CommaLoc = ConsumeToken(); 2172 2173 if (Tok.isNot(tok::identifier) && 2174 !(getLang().C99 || getLang().CPlusPlus0x)) 2175 Diag(CommaLoc, diag::ext_enumerator_list_comma) 2176 << getLang().CPlusPlus 2177 << FixItHint::CreateRemoval(CommaLoc); 2178 } 2179 2180 // Eat the }. 2181 SourceLocation RBraceLoc = MatchRHSPunctuation(tok::r_brace, LBraceLoc); 2182 2183 AttributeList *Attr = 0; 2184 // If attributes exist after the identifier list, parse them. 2185 if (Tok.is(tok::kw___attribute)) 2186 Attr = ParseGNUAttributes(); // FIXME: where do they do? 2187 2188 Actions.ActOnEnumBody(StartLoc, LBraceLoc, RBraceLoc, EnumDecl, 2189 EnumConstantDecls.data(), EnumConstantDecls.size(), 2190 getCurScope(), Attr); 2191 2192 EnumScope.Exit(); 2193 Actions.ActOnTagFinishDefinition(getCurScope(), EnumDecl, RBraceLoc); 2194} 2195 2196/// isTypeSpecifierQualifier - Return true if the current token could be the 2197/// start of a type-qualifier-list. 2198bool Parser::isTypeQualifier() const { 2199 switch (Tok.getKind()) { 2200 default: return false; 2201 // type-qualifier 2202 case tok::kw_const: 2203 case tok::kw_volatile: 2204 case tok::kw_restrict: 2205 return true; 2206 } 2207} 2208 2209/// isKnownToBeTypeSpecifier - Return true if we know that the specified token 2210/// is definitely a type-specifier. Return false if it isn't part of a type 2211/// specifier or if we're not sure. 2212bool Parser::isKnownToBeTypeSpecifier(const Token &Tok) const { 2213 switch (Tok.getKind()) { 2214 default: return false; 2215 // type-specifiers 2216 case tok::kw_short: 2217 case tok::kw_long: 2218 case tok::kw_signed: 2219 case tok::kw_unsigned: 2220 case tok::kw__Complex: 2221 case tok::kw__Imaginary: 2222 case tok::kw_void: 2223 case tok::kw_char: 2224 case tok::kw_wchar_t: 2225 case tok::kw_char16_t: 2226 case tok::kw_char32_t: 2227 case tok::kw_int: 2228 case tok::kw_float: 2229 case tok::kw_double: 2230 case tok::kw_bool: 2231 case tok::kw__Bool: 2232 case tok::kw__Decimal32: 2233 case tok::kw__Decimal64: 2234 case tok::kw__Decimal128: 2235 case tok::kw___vector: 2236 2237 // struct-or-union-specifier (C99) or class-specifier (C++) 2238 case tok::kw_class: 2239 case tok::kw_struct: 2240 case tok::kw_union: 2241 // enum-specifier 2242 case tok::kw_enum: 2243 2244 // typedef-name 2245 case tok::annot_typename: 2246 return true; 2247 } 2248} 2249 2250/// isTypeSpecifierQualifier - Return true if the current token could be the 2251/// start of a specifier-qualifier-list. 2252bool Parser::isTypeSpecifierQualifier() { 2253 switch (Tok.getKind()) { 2254 default: return false; 2255 2256 case tok::identifier: // foo::bar 2257 if (TryAltiVecVectorToken()) 2258 return true; 2259 // Fall through. 2260 case tok::kw_typename: // typename T::type 2261 // Annotate typenames and C++ scope specifiers. If we get one, just 2262 // recurse to handle whatever we get. 2263 if (TryAnnotateTypeOrScopeToken()) 2264 return true; 2265 if (Tok.is(tok::identifier)) 2266 return false; 2267 return isTypeSpecifierQualifier(); 2268 2269 case tok::coloncolon: // ::foo::bar 2270 if (NextToken().is(tok::kw_new) || // ::new 2271 NextToken().is(tok::kw_delete)) // ::delete 2272 return false; 2273 2274 if (TryAnnotateTypeOrScopeToken()) 2275 return true; 2276 return isTypeSpecifierQualifier(); 2277 2278 // GNU attributes support. 2279 case tok::kw___attribute: 2280 // GNU typeof support. 2281 case tok::kw_typeof: 2282 2283 // type-specifiers 2284 case tok::kw_short: 2285 case tok::kw_long: 2286 case tok::kw_signed: 2287 case tok::kw_unsigned: 2288 case tok::kw__Complex: 2289 case tok::kw__Imaginary: 2290 case tok::kw_void: 2291 case tok::kw_char: 2292 case tok::kw_wchar_t: 2293 case tok::kw_char16_t: 2294 case tok::kw_char32_t: 2295 case tok::kw_int: 2296 case tok::kw_float: 2297 case tok::kw_double: 2298 case tok::kw_bool: 2299 case tok::kw__Bool: 2300 case tok::kw__Decimal32: 2301 case tok::kw__Decimal64: 2302 case tok::kw__Decimal128: 2303 case tok::kw___vector: 2304 2305 // struct-or-union-specifier (C99) or class-specifier (C++) 2306 case tok::kw_class: 2307 case tok::kw_struct: 2308 case tok::kw_union: 2309 // enum-specifier 2310 case tok::kw_enum: 2311 2312 // type-qualifier 2313 case tok::kw_const: 2314 case tok::kw_volatile: 2315 case tok::kw_restrict: 2316 2317 // typedef-name 2318 case tok::annot_typename: 2319 return true; 2320 2321 // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'. 2322 case tok::less: 2323 return getLang().ObjC1; 2324 2325 case tok::kw___cdecl: 2326 case tok::kw___stdcall: 2327 case tok::kw___fastcall: 2328 case tok::kw___thiscall: 2329 case tok::kw___w64: 2330 case tok::kw___ptr64: 2331 case tok::kw___pascal: 2332 return true; 2333 } 2334} 2335 2336/// isDeclarationSpecifier() - Return true if the current token is part of a 2337/// declaration specifier. 2338/// 2339/// \param DisambiguatingWithExpression True to indicate that the purpose of 2340/// this check is to disambiguate between an expression and a declaration. 2341bool Parser::isDeclarationSpecifier(bool DisambiguatingWithExpression) { 2342 switch (Tok.getKind()) { 2343 default: return false; 2344 2345 case tok::identifier: // foo::bar 2346 // Unfortunate hack to support "Class.factoryMethod" notation. 2347 if (getLang().ObjC1 && NextToken().is(tok::period)) 2348 return false; 2349 if (TryAltiVecVectorToken()) 2350 return true; 2351 // Fall through. 2352 case tok::kw_typename: // typename T::type 2353 // Annotate typenames and C++ scope specifiers. If we get one, just 2354 // recurse to handle whatever we get. 2355 if (TryAnnotateTypeOrScopeToken()) 2356 return true; 2357 if (Tok.is(tok::identifier)) 2358 return false; 2359 2360 // If we're in Objective-C and we have an Objective-C class type followed 2361 // by an identifier and then either ':' or ']', in a place where an 2362 // expression is permitted, then this is probably a class message send 2363 // missing the initial '['. In this case, we won't consider this to be 2364 // the start of a declaration. 2365 if (DisambiguatingWithExpression && 2366 isStartOfObjCClassMessageMissingOpenBracket()) 2367 return false; 2368 2369 return isDeclarationSpecifier(); 2370 2371 case tok::coloncolon: // ::foo::bar 2372 if (NextToken().is(tok::kw_new) || // ::new 2373 NextToken().is(tok::kw_delete)) // ::delete 2374 return false; 2375 2376 // Annotate typenames and C++ scope specifiers. If we get one, just 2377 // recurse to handle whatever we get. 2378 if (TryAnnotateTypeOrScopeToken()) 2379 return true; 2380 return isDeclarationSpecifier(); 2381 2382 // storage-class-specifier 2383 case tok::kw_typedef: 2384 case tok::kw_extern: 2385 case tok::kw___private_extern__: 2386 case tok::kw_static: 2387 case tok::kw_auto: 2388 case tok::kw_register: 2389 case tok::kw___thread: 2390 2391 // type-specifiers 2392 case tok::kw_short: 2393 case tok::kw_long: 2394 case tok::kw_signed: 2395 case tok::kw_unsigned: 2396 case tok::kw__Complex: 2397 case tok::kw__Imaginary: 2398 case tok::kw_void: 2399 case tok::kw_char: 2400 case tok::kw_wchar_t: 2401 case tok::kw_char16_t: 2402 case tok::kw_char32_t: 2403 2404 case tok::kw_int: 2405 case tok::kw_float: 2406 case tok::kw_double: 2407 case tok::kw_bool: 2408 case tok::kw__Bool: 2409 case tok::kw__Decimal32: 2410 case tok::kw__Decimal64: 2411 case tok::kw__Decimal128: 2412 case tok::kw___vector: 2413 2414 // struct-or-union-specifier (C99) or class-specifier (C++) 2415 case tok::kw_class: 2416 case tok::kw_struct: 2417 case tok::kw_union: 2418 // enum-specifier 2419 case tok::kw_enum: 2420 2421 // type-qualifier 2422 case tok::kw_const: 2423 case tok::kw_volatile: 2424 case tok::kw_restrict: 2425 2426 // function-specifier 2427 case tok::kw_inline: 2428 case tok::kw_virtual: 2429 case tok::kw_explicit: 2430 2431 // typedef-name 2432 case tok::annot_typename: 2433 2434 // GNU typeof support. 2435 case tok::kw_typeof: 2436 2437 // GNU attributes. 2438 case tok::kw___attribute: 2439 return true; 2440 2441 // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'. 2442 case tok::less: 2443 return getLang().ObjC1; 2444 2445 case tok::kw___declspec: 2446 case tok::kw___cdecl: 2447 case tok::kw___stdcall: 2448 case tok::kw___fastcall: 2449 case tok::kw___thiscall: 2450 case tok::kw___w64: 2451 case tok::kw___ptr64: 2452 case tok::kw___forceinline: 2453 case tok::kw___pascal: 2454 return true; 2455 } 2456} 2457 2458bool Parser::isConstructorDeclarator() { 2459 TentativeParsingAction TPA(*this); 2460 2461 // Parse the C++ scope specifier. 2462 CXXScopeSpec SS; 2463 if (ParseOptionalCXXScopeSpecifier(SS, ParsedType(), true)) { 2464 TPA.Revert(); 2465 return false; 2466 } 2467 2468 // Parse the constructor name. 2469 if (Tok.is(tok::identifier) || Tok.is(tok::annot_template_id)) { 2470 // We already know that we have a constructor name; just consume 2471 // the token. 2472 ConsumeToken(); 2473 } else { 2474 TPA.Revert(); 2475 return false; 2476 } 2477 2478 // Current class name must be followed by a left parentheses. 2479 if (Tok.isNot(tok::l_paren)) { 2480 TPA.Revert(); 2481 return false; 2482 } 2483 ConsumeParen(); 2484 2485 // A right parentheses or ellipsis signals that we have a constructor. 2486 if (Tok.is(tok::r_paren) || Tok.is(tok::ellipsis)) { 2487 TPA.Revert(); 2488 return true; 2489 } 2490 2491 // If we need to, enter the specified scope. 2492 DeclaratorScopeObj DeclScopeObj(*this, SS); 2493 if (SS.isSet() && Actions.ShouldEnterDeclaratorScope(getCurScope(), SS)) 2494 DeclScopeObj.EnterDeclaratorScope(); 2495 2496 // Check whether the next token(s) are part of a declaration 2497 // specifier, in which case we have the start of a parameter and, 2498 // therefore, we know that this is a constructor. 2499 bool IsConstructor = isDeclarationSpecifier(); 2500 TPA.Revert(); 2501 return IsConstructor; 2502} 2503 2504/// ParseTypeQualifierListOpt 2505/// type-qualifier-list: [C99 6.7.5] 2506/// type-qualifier 2507/// [vendor] attributes 2508/// [ only if VendorAttributesAllowed=true ] 2509/// type-qualifier-list type-qualifier 2510/// [vendor] type-qualifier-list attributes 2511/// [ only if VendorAttributesAllowed=true ] 2512/// [C++0x] attribute-specifier[opt] is allowed before cv-qualifier-seq 2513/// [ only if CXX0XAttributesAllowed=true ] 2514/// Note: vendor can be GNU, MS, etc. 2515/// 2516void Parser::ParseTypeQualifierListOpt(DeclSpec &DS, 2517 bool VendorAttributesAllowed, 2518 bool CXX0XAttributesAllowed) { 2519 if (getLang().CPlusPlus0x && isCXX0XAttributeSpecifier()) { 2520 SourceLocation Loc = Tok.getLocation(); 2521 CXX0XAttributeList Attr = ParseCXX0XAttributes(); 2522 if (CXX0XAttributesAllowed) 2523 DS.AddAttributes(Attr.AttrList); 2524 else 2525 Diag(Loc, diag::err_attributes_not_allowed); 2526 } 2527 2528 while (1) { 2529 bool isInvalid = false; 2530 const char *PrevSpec = 0; 2531 unsigned DiagID = 0; 2532 SourceLocation Loc = Tok.getLocation(); 2533 2534 switch (Tok.getKind()) { 2535 case tok::code_completion: 2536 Actions.CodeCompleteTypeQualifiers(DS); 2537 ConsumeCodeCompletionToken(); 2538 break; 2539 2540 case tok::kw_const: 2541 isInvalid = DS.SetTypeQual(DeclSpec::TQ_const , Loc, PrevSpec, DiagID, 2542 getLang()); 2543 break; 2544 case tok::kw_volatile: 2545 isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, DiagID, 2546 getLang()); 2547 break; 2548 case tok::kw_restrict: 2549 isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, DiagID, 2550 getLang()); 2551 break; 2552 case tok::kw___w64: 2553 case tok::kw___ptr64: 2554 case tok::kw___cdecl: 2555 case tok::kw___stdcall: 2556 case tok::kw___fastcall: 2557 case tok::kw___thiscall: 2558 if (VendorAttributesAllowed) { 2559 DS.AddAttributes(ParseMicrosoftTypeAttributes()); 2560 continue; 2561 } 2562 goto DoneWithTypeQuals; 2563 case tok::kw___pascal: 2564 if (VendorAttributesAllowed) { 2565 DS.AddAttributes(ParseBorlandTypeAttributes()); 2566 continue; 2567 } 2568 goto DoneWithTypeQuals; 2569 case tok::kw___attribute: 2570 if (VendorAttributesAllowed) { 2571 DS.AddAttributes(ParseGNUAttributes()); 2572 continue; // do *not* consume the next token! 2573 } 2574 // otherwise, FALL THROUGH! 2575 default: 2576 DoneWithTypeQuals: 2577 // If this is not a type-qualifier token, we're done reading type 2578 // qualifiers. First verify that DeclSpec's are consistent. 2579 DS.Finish(Diags, PP); 2580 return; 2581 } 2582 2583 // If the specifier combination wasn't legal, issue a diagnostic. 2584 if (isInvalid) { 2585 assert(PrevSpec && "Method did not return previous specifier!"); 2586 Diag(Tok, DiagID) << PrevSpec; 2587 } 2588 ConsumeToken(); 2589 } 2590} 2591 2592 2593/// ParseDeclarator - Parse and verify a newly-initialized declarator. 2594/// 2595void Parser::ParseDeclarator(Declarator &D) { 2596 /// This implements the 'declarator' production in the C grammar, then checks 2597 /// for well-formedness and issues diagnostics. 2598 ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator); 2599} 2600 2601/// ParseDeclaratorInternal - Parse a C or C++ declarator. The direct-declarator 2602/// is parsed by the function passed to it. Pass null, and the direct-declarator 2603/// isn't parsed at all, making this function effectively parse the C++ 2604/// ptr-operator production. 2605/// 2606/// declarator: [C99 6.7.5] [C++ 8p4, dcl.decl] 2607/// [C] pointer[opt] direct-declarator 2608/// [C++] direct-declarator 2609/// [C++] ptr-operator declarator 2610/// 2611/// pointer: [C99 6.7.5] 2612/// '*' type-qualifier-list[opt] 2613/// '*' type-qualifier-list[opt] pointer 2614/// 2615/// ptr-operator: 2616/// '*' cv-qualifier-seq[opt] 2617/// '&' 2618/// [C++0x] '&&' 2619/// [GNU] '&' restrict[opt] attributes[opt] 2620/// [GNU?] '&&' restrict[opt] attributes[opt] 2621/// '::'[opt] nested-name-specifier '*' cv-qualifier-seq[opt] 2622void Parser::ParseDeclaratorInternal(Declarator &D, 2623 DirectDeclParseFunction DirectDeclParser) { 2624 if (Diags.hasAllExtensionsSilenced()) 2625 D.setExtension(); 2626 2627 // C++ member pointers start with a '::' or a nested-name. 2628 // Member pointers get special handling, since there's no place for the 2629 // scope spec in the generic path below. 2630 if (getLang().CPlusPlus && 2631 (Tok.is(tok::coloncolon) || Tok.is(tok::identifier) || 2632 Tok.is(tok::annot_cxxscope))) { 2633 CXXScopeSpec SS; 2634 ParseOptionalCXXScopeSpecifier(SS, ParsedType(), true); // ignore fail 2635 2636 if (SS.isNotEmpty()) { 2637 if (Tok.isNot(tok::star)) { 2638 // The scope spec really belongs to the direct-declarator. 2639 D.getCXXScopeSpec() = SS; 2640 if (DirectDeclParser) 2641 (this->*DirectDeclParser)(D); 2642 return; 2643 } 2644 2645 SourceLocation Loc = ConsumeToken(); 2646 D.SetRangeEnd(Loc); 2647 DeclSpec DS; 2648 ParseTypeQualifierListOpt(DS); 2649 D.ExtendWithDeclSpec(DS); 2650 2651 // Recurse to parse whatever is left. 2652 ParseDeclaratorInternal(D, DirectDeclParser); 2653 2654 // Sema will have to catch (syntactically invalid) pointers into global 2655 // scope. It has to catch pointers into namespace scope anyway. 2656 D.AddTypeInfo(DeclaratorChunk::getMemberPointer(SS,DS.getTypeQualifiers(), 2657 Loc, DS.TakeAttributes()), 2658 /* Don't replace range end. */SourceLocation()); 2659 return; 2660 } 2661 } 2662 2663 tok::TokenKind Kind = Tok.getKind(); 2664 // Not a pointer, C++ reference, or block. 2665 if (Kind != tok::star && Kind != tok::caret && 2666 (Kind != tok::amp || !getLang().CPlusPlus) && 2667 // We parse rvalue refs in C++03, because otherwise the errors are scary. 2668 (Kind != tok::ampamp || !getLang().CPlusPlus)) { 2669 if (DirectDeclParser) 2670 (this->*DirectDeclParser)(D); 2671 return; 2672 } 2673 2674 // Otherwise, '*' -> pointer, '^' -> block, '&' -> lvalue reference, 2675 // '&&' -> rvalue reference 2676 SourceLocation Loc = ConsumeToken(); // Eat the *, ^, & or &&. 2677 D.SetRangeEnd(Loc); 2678 2679 if (Kind == tok::star || Kind == tok::caret) { 2680 // Is a pointer. 2681 DeclSpec DS; 2682 2683 ParseTypeQualifierListOpt(DS); 2684 D.ExtendWithDeclSpec(DS); 2685 2686 // Recursively parse the declarator. 2687 ParseDeclaratorInternal(D, DirectDeclParser); 2688 if (Kind == tok::star) 2689 // Remember that we parsed a pointer type, and remember the type-quals. 2690 D.AddTypeInfo(DeclaratorChunk::getPointer(DS.getTypeQualifiers(), Loc, 2691 DS.TakeAttributes()), 2692 SourceLocation()); 2693 else 2694 // Remember that we parsed a Block type, and remember the type-quals. 2695 D.AddTypeInfo(DeclaratorChunk::getBlockPointer(DS.getTypeQualifiers(), 2696 Loc, DS.TakeAttributes()), 2697 SourceLocation()); 2698 } else { 2699 // Is a reference 2700 DeclSpec DS; 2701 2702 // Complain about rvalue references in C++03, but then go on and build 2703 // the declarator. 2704 if (Kind == tok::ampamp && !getLang().CPlusPlus0x) 2705 Diag(Loc, diag::err_rvalue_reference); 2706 2707 // C++ 8.3.2p1: cv-qualified references are ill-formed except when the 2708 // cv-qualifiers are introduced through the use of a typedef or of a 2709 // template type argument, in which case the cv-qualifiers are ignored. 2710 // 2711 // [GNU] Retricted references are allowed. 2712 // [GNU] Attributes on references are allowed. 2713 // [C++0x] Attributes on references are not allowed. 2714 ParseTypeQualifierListOpt(DS, true, false); 2715 D.ExtendWithDeclSpec(DS); 2716 2717 if (DS.getTypeQualifiers() != DeclSpec::TQ_unspecified) { 2718 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 2719 Diag(DS.getConstSpecLoc(), 2720 diag::err_invalid_reference_qualifier_application) << "const"; 2721 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 2722 Diag(DS.getVolatileSpecLoc(), 2723 diag::err_invalid_reference_qualifier_application) << "volatile"; 2724 } 2725 2726 // Recursively parse the declarator. 2727 ParseDeclaratorInternal(D, DirectDeclParser); 2728 2729 if (D.getNumTypeObjects() > 0) { 2730 // C++ [dcl.ref]p4: There shall be no references to references. 2731 DeclaratorChunk& InnerChunk = D.getTypeObject(D.getNumTypeObjects() - 1); 2732 if (InnerChunk.Kind == DeclaratorChunk::Reference) { 2733 if (const IdentifierInfo *II = D.getIdentifier()) 2734 Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference) 2735 << II; 2736 else 2737 Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference) 2738 << "type name"; 2739 2740 // Once we've complained about the reference-to-reference, we 2741 // can go ahead and build the (technically ill-formed) 2742 // declarator: reference collapsing will take care of it. 2743 } 2744 } 2745 2746 // Remember that we parsed a reference type. It doesn't have type-quals. 2747 D.AddTypeInfo(DeclaratorChunk::getReference(DS.getTypeQualifiers(), Loc, 2748 DS.TakeAttributes(), 2749 Kind == tok::amp), 2750 SourceLocation()); 2751 } 2752} 2753 2754/// ParseDirectDeclarator 2755/// direct-declarator: [C99 6.7.5] 2756/// [C99] identifier 2757/// '(' declarator ')' 2758/// [GNU] '(' attributes declarator ')' 2759/// [C90] direct-declarator '[' constant-expression[opt] ']' 2760/// [C99] direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']' 2761/// [C99] direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']' 2762/// [C99] direct-declarator '[' type-qual-list 'static' assignment-expr ']' 2763/// [C99] direct-declarator '[' type-qual-list[opt] '*' ']' 2764/// direct-declarator '(' parameter-type-list ')' 2765/// direct-declarator '(' identifier-list[opt] ')' 2766/// [GNU] direct-declarator '(' parameter-forward-declarations 2767/// parameter-type-list[opt] ')' 2768/// [C++] direct-declarator '(' parameter-declaration-clause ')' 2769/// cv-qualifier-seq[opt] exception-specification[opt] 2770/// [C++] declarator-id 2771/// 2772/// declarator-id: [C++ 8] 2773/// id-expression 2774/// '::'[opt] nested-name-specifier[opt] type-name 2775/// 2776/// id-expression: [C++ 5.1] 2777/// unqualified-id 2778/// qualified-id 2779/// 2780/// unqualified-id: [C++ 5.1] 2781/// identifier 2782/// operator-function-id 2783/// conversion-function-id 2784/// '~' class-name 2785/// template-id 2786/// 2787void Parser::ParseDirectDeclarator(Declarator &D) { 2788 DeclaratorScopeObj DeclScopeObj(*this, D.getCXXScopeSpec()); 2789 2790 if (getLang().CPlusPlus && D.mayHaveIdentifier()) { 2791 // ParseDeclaratorInternal might already have parsed the scope. 2792 if (D.getCXXScopeSpec().isEmpty()) { 2793 ParseOptionalCXXScopeSpecifier(D.getCXXScopeSpec(), ParsedType(), true); 2794 } 2795 2796 if (D.getCXXScopeSpec().isValid()) { 2797 if (Actions.ShouldEnterDeclaratorScope(getCurScope(), D.getCXXScopeSpec())) 2798 // Change the declaration context for name lookup, until this function 2799 // is exited (and the declarator has been parsed). 2800 DeclScopeObj.EnterDeclaratorScope(); 2801 } 2802 2803 if (Tok.is(tok::identifier) || Tok.is(tok::kw_operator) || 2804 Tok.is(tok::annot_template_id) || Tok.is(tok::tilde)) { 2805 // We found something that indicates the start of an unqualified-id. 2806 // Parse that unqualified-id. 2807 bool AllowConstructorName; 2808 if (D.getDeclSpec().hasTypeSpecifier()) 2809 AllowConstructorName = false; 2810 else if (D.getCXXScopeSpec().isSet()) 2811 AllowConstructorName = 2812 (D.getContext() == Declarator::FileContext || 2813 (D.getContext() == Declarator::MemberContext && 2814 D.getDeclSpec().isFriendSpecified())); 2815 else 2816 AllowConstructorName = (D.getContext() == Declarator::MemberContext); 2817 2818 if (ParseUnqualifiedId(D.getCXXScopeSpec(), 2819 /*EnteringContext=*/true, 2820 /*AllowDestructorName=*/true, 2821 AllowConstructorName, 2822 ParsedType(), 2823 D.getName()) || 2824 // Once we're past the identifier, if the scope was bad, mark the 2825 // whole declarator bad. 2826 D.getCXXScopeSpec().isInvalid()) { 2827 D.SetIdentifier(0, Tok.getLocation()); 2828 D.setInvalidType(true); 2829 } else { 2830 // Parsed the unqualified-id; update range information and move along. 2831 if (D.getSourceRange().getBegin().isInvalid()) 2832 D.SetRangeBegin(D.getName().getSourceRange().getBegin()); 2833 D.SetRangeEnd(D.getName().getSourceRange().getEnd()); 2834 } 2835 goto PastIdentifier; 2836 } 2837 } else if (Tok.is(tok::identifier) && D.mayHaveIdentifier()) { 2838 assert(!getLang().CPlusPlus && 2839 "There's a C++-specific check for tok::identifier above"); 2840 assert(Tok.getIdentifierInfo() && "Not an identifier?"); 2841 D.SetIdentifier(Tok.getIdentifierInfo(), Tok.getLocation()); 2842 ConsumeToken(); 2843 goto PastIdentifier; 2844 } 2845 2846 if (Tok.is(tok::l_paren)) { 2847 // direct-declarator: '(' declarator ')' 2848 // direct-declarator: '(' attributes declarator ')' 2849 // Example: 'char (*X)' or 'int (*XX)(void)' 2850 ParseParenDeclarator(D); 2851 2852 // If the declarator was parenthesized, we entered the declarator 2853 // scope when parsing the parenthesized declarator, then exited 2854 // the scope already. Re-enter the scope, if we need to. 2855 if (D.getCXXScopeSpec().isSet()) { 2856 // If there was an error parsing parenthesized declarator, declarator 2857 // scope may have been enterred before. Don't do it again. 2858 if (!D.isInvalidType() && 2859 Actions.ShouldEnterDeclaratorScope(getCurScope(), D.getCXXScopeSpec())) 2860 // Change the declaration context for name lookup, until this function 2861 // is exited (and the declarator has been parsed). 2862 DeclScopeObj.EnterDeclaratorScope(); 2863 } 2864 } else if (D.mayOmitIdentifier()) { 2865 // This could be something simple like "int" (in which case the declarator 2866 // portion is empty), if an abstract-declarator is allowed. 2867 D.SetIdentifier(0, Tok.getLocation()); 2868 } else { 2869 if (D.getContext() == Declarator::MemberContext) 2870 Diag(Tok, diag::err_expected_member_name_or_semi) 2871 << D.getDeclSpec().getSourceRange(); 2872 else if (getLang().CPlusPlus) 2873 Diag(Tok, diag::err_expected_unqualified_id) << getLang().CPlusPlus; 2874 else 2875 Diag(Tok, diag::err_expected_ident_lparen); 2876 D.SetIdentifier(0, Tok.getLocation()); 2877 D.setInvalidType(true); 2878 } 2879 2880 PastIdentifier: 2881 assert(D.isPastIdentifier() && 2882 "Haven't past the location of the identifier yet?"); 2883 2884 // Don't parse attributes unless we have an identifier. 2885 if (D.getIdentifier() && getLang().CPlusPlus0x 2886 && isCXX0XAttributeSpecifier(true)) { 2887 SourceLocation AttrEndLoc; 2888 CXX0XAttributeList Attr = ParseCXX0XAttributes(); 2889 D.AddAttributes(Attr.AttrList, AttrEndLoc); 2890 } 2891 2892 while (1) { 2893 if (Tok.is(tok::l_paren)) { 2894 // The paren may be part of a C++ direct initializer, eg. "int x(1);". 2895 // In such a case, check if we actually have a function declarator; if it 2896 // is not, the declarator has been fully parsed. 2897 if (getLang().CPlusPlus && D.mayBeFollowedByCXXDirectInit()) { 2898 // When not in file scope, warn for ambiguous function declarators, just 2899 // in case the author intended it as a variable definition. 2900 bool warnIfAmbiguous = D.getContext() != Declarator::FileContext; 2901 if (!isCXXFunctionDeclarator(warnIfAmbiguous)) 2902 break; 2903 } 2904 ParseFunctionDeclarator(ConsumeParen(), D); 2905 } else if (Tok.is(tok::l_square)) { 2906 ParseBracketDeclarator(D); 2907 } else { 2908 break; 2909 } 2910 } 2911} 2912 2913/// ParseParenDeclarator - We parsed the declarator D up to a paren. This is 2914/// only called before the identifier, so these are most likely just grouping 2915/// parens for precedence. If we find that these are actually function 2916/// parameter parens in an abstract-declarator, we call ParseFunctionDeclarator. 2917/// 2918/// direct-declarator: 2919/// '(' declarator ')' 2920/// [GNU] '(' attributes declarator ')' 2921/// direct-declarator '(' parameter-type-list ')' 2922/// direct-declarator '(' identifier-list[opt] ')' 2923/// [GNU] direct-declarator '(' parameter-forward-declarations 2924/// parameter-type-list[opt] ')' 2925/// 2926void Parser::ParseParenDeclarator(Declarator &D) { 2927 SourceLocation StartLoc = ConsumeParen(); 2928 assert(!D.isPastIdentifier() && "Should be called before passing identifier"); 2929 2930 // Eat any attributes before we look at whether this is a grouping or function 2931 // declarator paren. If this is a grouping paren, the attribute applies to 2932 // the type being built up, for example: 2933 // int (__attribute__(()) *x)(long y) 2934 // If this ends up not being a grouping paren, the attribute applies to the 2935 // first argument, for example: 2936 // int (__attribute__(()) int x) 2937 // In either case, we need to eat any attributes to be able to determine what 2938 // sort of paren this is. 2939 // 2940 AttributeList *AttrList = 0; 2941 bool RequiresArg = false; 2942 if (Tok.is(tok::kw___attribute)) { 2943 AttrList = ParseGNUAttributes(); 2944 2945 // We require that the argument list (if this is a non-grouping paren) be 2946 // present even if the attribute list was empty. 2947 RequiresArg = true; 2948 } 2949 // Eat any Microsoft extensions. 2950 if (Tok.is(tok::kw___cdecl) || Tok.is(tok::kw___stdcall) || 2951 Tok.is(tok::kw___thiscall) || Tok.is(tok::kw___fastcall) || 2952 Tok.is(tok::kw___w64) || Tok.is(tok::kw___ptr64)) { 2953 AttrList = ParseMicrosoftTypeAttributes(AttrList); 2954 } 2955 // Eat any Borland extensions. 2956 if (Tok.is(tok::kw___pascal)) 2957 AttrList = ParseBorlandTypeAttributes(AttrList); 2958 2959 // If we haven't past the identifier yet (or where the identifier would be 2960 // stored, if this is an abstract declarator), then this is probably just 2961 // grouping parens. However, if this could be an abstract-declarator, then 2962 // this could also be the start of function arguments (consider 'void()'). 2963 bool isGrouping; 2964 2965 if (!D.mayOmitIdentifier()) { 2966 // If this can't be an abstract-declarator, this *must* be a grouping 2967 // paren, because we haven't seen the identifier yet. 2968 isGrouping = true; 2969 } else if (Tok.is(tok::r_paren) || // 'int()' is a function. 2970 (getLang().CPlusPlus && Tok.is(tok::ellipsis)) || // C++ int(...) 2971 isDeclarationSpecifier()) { // 'int(int)' is a function. 2972 // This handles C99 6.7.5.3p11: in "typedef int X; void foo(X)", X is 2973 // considered to be a type, not a K&R identifier-list. 2974 isGrouping = false; 2975 } else { 2976 // Otherwise, this is a grouping paren, e.g. 'int (*X)' or 'int(X)'. 2977 isGrouping = true; 2978 } 2979 2980 // If this is a grouping paren, handle: 2981 // direct-declarator: '(' declarator ')' 2982 // direct-declarator: '(' attributes declarator ')' 2983 if (isGrouping) { 2984 bool hadGroupingParens = D.hasGroupingParens(); 2985 D.setGroupingParens(true); 2986 if (AttrList) 2987 D.AddAttributes(AttrList, SourceLocation()); 2988 2989 ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator); 2990 // Match the ')'. 2991 SourceLocation Loc = MatchRHSPunctuation(tok::r_paren, StartLoc); 2992 2993 D.setGroupingParens(hadGroupingParens); 2994 D.SetRangeEnd(Loc); 2995 return; 2996 } 2997 2998 // Okay, if this wasn't a grouping paren, it must be the start of a function 2999 // argument list. Recognize that this declarator will never have an 3000 // identifier (and remember where it would have been), then call into 3001 // ParseFunctionDeclarator to handle of argument list. 3002 D.SetIdentifier(0, Tok.getLocation()); 3003 3004 ParseFunctionDeclarator(StartLoc, D, AttrList, RequiresArg); 3005} 3006 3007/// ParseFunctionDeclarator - We are after the identifier and have parsed the 3008/// declarator D up to a paren, which indicates that we are parsing function 3009/// arguments. 3010/// 3011/// If AttrList is non-null, then the caller parsed those arguments immediately 3012/// after the open paren - they should be considered to be the first argument of 3013/// a parameter. If RequiresArg is true, then the first argument of the 3014/// function is required to be present and required to not be an identifier 3015/// list. 3016/// 3017/// This method also handles this portion of the grammar: 3018/// parameter-type-list: [C99 6.7.5] 3019/// parameter-list 3020/// parameter-list ',' '...' 3021/// [C++] parameter-list '...' 3022/// 3023/// parameter-list: [C99 6.7.5] 3024/// parameter-declaration 3025/// parameter-list ',' parameter-declaration 3026/// 3027/// parameter-declaration: [C99 6.7.5] 3028/// declaration-specifiers declarator 3029/// [C++] declaration-specifiers declarator '=' assignment-expression 3030/// [GNU] declaration-specifiers declarator attributes 3031/// declaration-specifiers abstract-declarator[opt] 3032/// [C++] declaration-specifiers abstract-declarator[opt] 3033/// '=' assignment-expression 3034/// [GNU] declaration-specifiers abstract-declarator[opt] attributes 3035/// 3036/// For C++, after the parameter-list, it also parses "cv-qualifier-seq[opt]" 3037/// and "exception-specification[opt]". 3038/// 3039void Parser::ParseFunctionDeclarator(SourceLocation LParenLoc, Declarator &D, 3040 AttributeList *AttrList, 3041 bool RequiresArg) { 3042 // lparen is already consumed! 3043 assert(D.isPastIdentifier() && "Should not call before identifier!"); 3044 3045 ParsedType TrailingReturnType; 3046 3047 // This parameter list may be empty. 3048 if (Tok.is(tok::r_paren)) { 3049 if (RequiresArg) 3050 Diag(Tok, diag::err_argument_required_after_attribute); 3051 3052 SourceLocation RParenLoc = ConsumeParen(); // Eat the closing ')'. 3053 SourceLocation EndLoc = RParenLoc; 3054 3055 // cv-qualifier-seq[opt]. 3056 DeclSpec DS; 3057 bool hasExceptionSpec = false; 3058 SourceLocation ThrowLoc; 3059 bool hasAnyExceptionSpec = false; 3060 llvm::SmallVector<ParsedType, 2> Exceptions; 3061 llvm::SmallVector<SourceRange, 2> ExceptionRanges; 3062 if (getLang().CPlusPlus) { 3063 ParseTypeQualifierListOpt(DS, false /*no attributes*/); 3064 if (!DS.getSourceRange().getEnd().isInvalid()) 3065 EndLoc = DS.getSourceRange().getEnd(); 3066 3067 // Parse exception-specification[opt]. 3068 if (Tok.is(tok::kw_throw)) { 3069 hasExceptionSpec = true; 3070 ThrowLoc = Tok.getLocation(); 3071 ParseExceptionSpecification(EndLoc, Exceptions, ExceptionRanges, 3072 hasAnyExceptionSpec); 3073 assert(Exceptions.size() == ExceptionRanges.size() && 3074 "Produced different number of exception types and ranges."); 3075 } 3076 3077 // Parse trailing-return-type. 3078 if (getLang().CPlusPlus0x && Tok.is(tok::arrow)) { 3079 TrailingReturnType = ParseTrailingReturnType().get(); 3080 } 3081 } 3082 3083 // Remember that we parsed a function type, and remember the attributes. 3084 // int() -> no prototype, no '...'. 3085 D.AddTypeInfo(DeclaratorChunk::getFunction(/*prototype*/getLang().CPlusPlus, 3086 /*variadic*/ false, 3087 SourceLocation(), 3088 /*arglist*/ 0, 0, 3089 DS.getTypeQualifiers(), 3090 hasExceptionSpec, ThrowLoc, 3091 hasAnyExceptionSpec, 3092 Exceptions.data(), 3093 ExceptionRanges.data(), 3094 Exceptions.size(), 3095 LParenLoc, RParenLoc, D, 3096 TrailingReturnType), 3097 EndLoc); 3098 return; 3099 } 3100 3101 // Alternatively, this parameter list may be an identifier list form for a 3102 // K&R-style function: void foo(a,b,c) 3103 if (!getLang().CPlusPlus && Tok.is(tok::identifier) 3104 && !TryAltiVecVectorToken()) { 3105 if (TryAnnotateTypeOrScopeToken() || !Tok.is(tok::annot_typename)) { 3106 // K&R identifier lists can't have typedefs as identifiers, per 3107 // C99 6.7.5.3p11. 3108 if (RequiresArg) 3109 Diag(Tok, diag::err_argument_required_after_attribute); 3110 3111 // Identifier list. Note that '(' identifier-list ')' is only allowed for 3112 // normal declarators, not for abstract-declarators. Get the first 3113 // identifier. 3114 Token FirstTok = Tok; 3115 ConsumeToken(); // eat the first identifier. 3116 3117 // Identifier lists follow a really simple grammar: the identifiers can 3118 // be followed *only* by a ", moreidentifiers" or ")". However, K&R 3119 // identifier lists are really rare in the brave new modern world, and it 3120 // is very common for someone to typo a type in a non-k&r style list. If 3121 // we are presented with something like: "void foo(intptr x, float y)", 3122 // we don't want to start parsing the function declarator as though it is 3123 // a K&R style declarator just because intptr is an invalid type. 3124 // 3125 // To handle this, we check to see if the token after the first identifier 3126 // is a "," or ")". Only if so, do we parse it as an identifier list. 3127 if (Tok.is(tok::comma) || Tok.is(tok::r_paren)) 3128 return ParseFunctionDeclaratorIdentifierList(LParenLoc, 3129 FirstTok.getIdentifierInfo(), 3130 FirstTok.getLocation(), D); 3131 3132 // If we get here, the code is invalid. Push the first identifier back 3133 // into the token stream and parse the first argument as an (invalid) 3134 // normal argument declarator. 3135 PP.EnterToken(Tok); 3136 Tok = FirstTok; 3137 } 3138 } 3139 3140 // Finally, a normal, non-empty parameter type list. 3141 3142 // Build up an array of information about the parsed arguments. 3143 llvm::SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo; 3144 3145 // Enter function-declaration scope, limiting any declarators to the 3146 // function prototype scope, including parameter declarators. 3147 ParseScope PrototypeScope(this, 3148 Scope::FunctionPrototypeScope|Scope::DeclScope); 3149 3150 bool IsVariadic = false; 3151 SourceLocation EllipsisLoc; 3152 while (1) { 3153 if (Tok.is(tok::ellipsis)) { 3154 IsVariadic = true; 3155 EllipsisLoc = ConsumeToken(); // Consume the ellipsis. 3156 break; 3157 } 3158 3159 // Skip any Microsoft attributes before a param. 3160 if (getLang().Microsoft && Tok.is(tok::l_square)) 3161 ParseMicrosoftAttributes(); 3162 3163 SourceLocation DSStart = Tok.getLocation(); 3164 3165 // Parse the declaration-specifiers. 3166 // Just use the ParsingDeclaration "scope" of the declarator. 3167 DeclSpec DS; 3168 3169 // If the caller parsed attributes for the first argument, add them now. 3170 if (AttrList) { 3171 DS.AddAttributes(AttrList); 3172 AttrList = 0; // Only apply the attributes to the first parameter. 3173 } 3174 ParseDeclarationSpecifiers(DS); 3175 3176 // Parse the declarator. This is "PrototypeContext", because we must 3177 // accept either 'declarator' or 'abstract-declarator' here. 3178 Declarator ParmDecl(DS, Declarator::PrototypeContext); 3179 ParseDeclarator(ParmDecl); 3180 3181 // Parse GNU attributes, if present. 3182 if (Tok.is(tok::kw___attribute)) { 3183 SourceLocation Loc; 3184 AttributeList *AttrList = ParseGNUAttributes(&Loc); 3185 ParmDecl.AddAttributes(AttrList, Loc); 3186 } 3187 3188 // Remember this parsed parameter in ParamInfo. 3189 IdentifierInfo *ParmII = ParmDecl.getIdentifier(); 3190 3191 // DefArgToks is used when the parsing of default arguments needs 3192 // to be delayed. 3193 CachedTokens *DefArgToks = 0; 3194 3195 // If no parameter was specified, verify that *something* was specified, 3196 // otherwise we have a missing type and identifier. 3197 if (DS.isEmpty() && ParmDecl.getIdentifier() == 0 && 3198 ParmDecl.getNumTypeObjects() == 0) { 3199 // Completely missing, emit error. 3200 Diag(DSStart, diag::err_missing_param); 3201 } else { 3202 // Otherwise, we have something. Add it and let semantic analysis try 3203 // to grok it and add the result to the ParamInfo we are building. 3204 3205 // Inform the actions module about the parameter declarator, so it gets 3206 // added to the current scope. 3207 Decl *Param = Actions.ActOnParamDeclarator(getCurScope(), ParmDecl); 3208 3209 // Parse the default argument, if any. We parse the default 3210 // arguments in all dialects; the semantic analysis in 3211 // ActOnParamDefaultArgument will reject the default argument in 3212 // C. 3213 if (Tok.is(tok::equal)) { 3214 SourceLocation EqualLoc = Tok.getLocation(); 3215 3216 // Parse the default argument 3217 if (D.getContext() == Declarator::MemberContext) { 3218 // If we're inside a class definition, cache the tokens 3219 // corresponding to the default argument. We'll actually parse 3220 // them when we see the end of the class definition. 3221 // FIXME: Templates will require something similar. 3222 // FIXME: Can we use a smart pointer for Toks? 3223 DefArgToks = new CachedTokens; 3224 3225 if (!ConsumeAndStoreUntil(tok::comma, tok::r_paren, *DefArgToks, 3226 /*StopAtSemi=*/true, 3227 /*ConsumeFinalToken=*/false)) { 3228 delete DefArgToks; 3229 DefArgToks = 0; 3230 Actions.ActOnParamDefaultArgumentError(Param); 3231 } else { 3232 // Mark the end of the default argument so that we know when to 3233 // stop when we parse it later on. 3234 Token DefArgEnd; 3235 DefArgEnd.startToken(); 3236 DefArgEnd.setKind(tok::cxx_defaultarg_end); 3237 DefArgEnd.setLocation(Tok.getLocation()); 3238 DefArgToks->push_back(DefArgEnd); 3239 Actions.ActOnParamUnparsedDefaultArgument(Param, EqualLoc, 3240 (*DefArgToks)[1].getLocation()); 3241 } 3242 } else { 3243 // Consume the '='. 3244 ConsumeToken(); 3245 3246 // The argument isn't actually potentially evaluated unless it is 3247 // used. 3248 EnterExpressionEvaluationContext Eval(Actions, 3249 Sema::PotentiallyEvaluatedIfUsed); 3250 3251 ExprResult DefArgResult(ParseAssignmentExpression()); 3252 if (DefArgResult.isInvalid()) { 3253 Actions.ActOnParamDefaultArgumentError(Param); 3254 SkipUntil(tok::comma, tok::r_paren, true, true); 3255 } else { 3256 // Inform the actions module about the default argument 3257 Actions.ActOnParamDefaultArgument(Param, EqualLoc, 3258 DefArgResult.take()); 3259 } 3260 } 3261 } 3262 3263 ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII, 3264 ParmDecl.getIdentifierLoc(), Param, 3265 DefArgToks)); 3266 } 3267 3268 // If the next token is a comma, consume it and keep reading arguments. 3269 if (Tok.isNot(tok::comma)) { 3270 if (Tok.is(tok::ellipsis)) { 3271 IsVariadic = true; 3272 EllipsisLoc = ConsumeToken(); // Consume the ellipsis. 3273 3274 if (!getLang().CPlusPlus) { 3275 // We have ellipsis without a preceding ',', which is ill-formed 3276 // in C. Complain and provide the fix. 3277 Diag(EllipsisLoc, diag::err_missing_comma_before_ellipsis) 3278 << FixItHint::CreateInsertion(EllipsisLoc, ", "); 3279 } 3280 } 3281 3282 break; 3283 } 3284 3285 // Consume the comma. 3286 ConsumeToken(); 3287 } 3288 3289 // If we have the closing ')', eat it. 3290 SourceLocation RParenLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc); 3291 SourceLocation EndLoc = RParenLoc; 3292 3293 DeclSpec DS; 3294 bool hasExceptionSpec = false; 3295 SourceLocation ThrowLoc; 3296 bool hasAnyExceptionSpec = false; 3297 llvm::SmallVector<ParsedType, 2> Exceptions; 3298 llvm::SmallVector<SourceRange, 2> ExceptionRanges; 3299 3300 if (getLang().CPlusPlus) { 3301 // Parse cv-qualifier-seq[opt]. 3302 ParseTypeQualifierListOpt(DS, false /*no attributes*/); 3303 if (!DS.getSourceRange().getEnd().isInvalid()) 3304 EndLoc = DS.getSourceRange().getEnd(); 3305 3306 // Parse exception-specification[opt]. 3307 if (Tok.is(tok::kw_throw)) { 3308 hasExceptionSpec = true; 3309 ThrowLoc = Tok.getLocation(); 3310 ParseExceptionSpecification(EndLoc, Exceptions, ExceptionRanges, 3311 hasAnyExceptionSpec); 3312 assert(Exceptions.size() == ExceptionRanges.size() && 3313 "Produced different number of exception types and ranges."); 3314 } 3315 3316 // Parse trailing-return-type. 3317 if (getLang().CPlusPlus0x && Tok.is(tok::arrow)) { 3318 TrailingReturnType = ParseTrailingReturnType().get(); 3319 } 3320 } 3321 3322 // FIXME: We should leave the prototype scope before parsing the exception 3323 // specification, and then reenter it when parsing the trailing return type. 3324 3325 // Leave prototype scope. 3326 PrototypeScope.Exit(); 3327 3328 // Remember that we parsed a function type, and remember the attributes. 3329 D.AddTypeInfo(DeclaratorChunk::getFunction(/*proto*/true, IsVariadic, 3330 EllipsisLoc, 3331 ParamInfo.data(), ParamInfo.size(), 3332 DS.getTypeQualifiers(), 3333 hasExceptionSpec, ThrowLoc, 3334 hasAnyExceptionSpec, 3335 Exceptions.data(), 3336 ExceptionRanges.data(), 3337 Exceptions.size(), 3338 LParenLoc, RParenLoc, D, 3339 TrailingReturnType), 3340 EndLoc); 3341} 3342 3343/// ParseFunctionDeclaratorIdentifierList - While parsing a function declarator 3344/// we found a K&R-style identifier list instead of a type argument list. The 3345/// first identifier has already been consumed, and the current token is the 3346/// token right after it. 3347/// 3348/// identifier-list: [C99 6.7.5] 3349/// identifier 3350/// identifier-list ',' identifier 3351/// 3352void Parser::ParseFunctionDeclaratorIdentifierList(SourceLocation LParenLoc, 3353 IdentifierInfo *FirstIdent, 3354 SourceLocation FirstIdentLoc, 3355 Declarator &D) { 3356 // Build up an array of information about the parsed arguments. 3357 llvm::SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo; 3358 llvm::SmallSet<const IdentifierInfo*, 16> ParamsSoFar; 3359 3360 // If there was no identifier specified for the declarator, either we are in 3361 // an abstract-declarator, or we are in a parameter declarator which was found 3362 // to be abstract. In abstract-declarators, identifier lists are not valid: 3363 // diagnose this. 3364 if (!D.getIdentifier()) 3365 Diag(FirstIdentLoc, diag::ext_ident_list_in_param); 3366 3367 // The first identifier was already read, and is known to be the first 3368 // identifier in the list. Remember this identifier in ParamInfo. 3369 ParamsSoFar.insert(FirstIdent); 3370 ParamInfo.push_back(DeclaratorChunk::ParamInfo(FirstIdent, FirstIdentLoc, 0)); 3371 3372 while (Tok.is(tok::comma)) { 3373 // Eat the comma. 3374 ConsumeToken(); 3375 3376 // If this isn't an identifier, report the error and skip until ')'. 3377 if (Tok.isNot(tok::identifier)) { 3378 Diag(Tok, diag::err_expected_ident); 3379 SkipUntil(tok::r_paren); 3380 return; 3381 } 3382 3383 IdentifierInfo *ParmII = Tok.getIdentifierInfo(); 3384 3385 // Reject 'typedef int y; int test(x, y)', but continue parsing. 3386 if (Actions.getTypeName(*ParmII, Tok.getLocation(), getCurScope())) 3387 Diag(Tok, diag::err_unexpected_typedef_ident) << ParmII; 3388 3389 // Verify that the argument identifier has not already been mentioned. 3390 if (!ParamsSoFar.insert(ParmII)) { 3391 Diag(Tok, diag::err_param_redefinition) << ParmII; 3392 } else { 3393 // Remember this identifier in ParamInfo. 3394 ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII, 3395 Tok.getLocation(), 3396 0)); 3397 } 3398 3399 // Eat the identifier. 3400 ConsumeToken(); 3401 } 3402 3403 // If we have the closing ')', eat it and we're done. 3404 SourceLocation RLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc); 3405 3406 // Remember that we parsed a function type, and remember the attributes. This 3407 // function type is always a K&R style function type, which is not varargs and 3408 // has no prototype. 3409 D.AddTypeInfo(DeclaratorChunk::getFunction(/*proto*/false, /*varargs*/false, 3410 SourceLocation(), 3411 &ParamInfo[0], ParamInfo.size(), 3412 /*TypeQuals*/0, 3413 /*exception*/false, 3414 SourceLocation(), false, 0, 0, 0, 3415 LParenLoc, RLoc, D), 3416 RLoc); 3417} 3418 3419/// [C90] direct-declarator '[' constant-expression[opt] ']' 3420/// [C99] direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']' 3421/// [C99] direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']' 3422/// [C99] direct-declarator '[' type-qual-list 'static' assignment-expr ']' 3423/// [C99] direct-declarator '[' type-qual-list[opt] '*' ']' 3424void Parser::ParseBracketDeclarator(Declarator &D) { 3425 SourceLocation StartLoc = ConsumeBracket(); 3426 3427 // C array syntax has many features, but by-far the most common is [] and [4]. 3428 // This code does a fast path to handle some of the most obvious cases. 3429 if (Tok.getKind() == tok::r_square) { 3430 SourceLocation EndLoc = MatchRHSPunctuation(tok::r_square, StartLoc); 3431 //FIXME: Use these 3432 CXX0XAttributeList Attr; 3433 if (getLang().CPlusPlus0x && isCXX0XAttributeSpecifier(true)) { 3434 Attr = ParseCXX0XAttributes(); 3435 } 3436 3437 // Remember that we parsed the empty array type. 3438 ExprResult NumElements; 3439 D.AddTypeInfo(DeclaratorChunk::getArray(0, false, false, 0, 3440 StartLoc, EndLoc), 3441 EndLoc); 3442 return; 3443 } else if (Tok.getKind() == tok::numeric_constant && 3444 GetLookAheadToken(1).is(tok::r_square)) { 3445 // [4] is very common. Parse the numeric constant expression. 3446 ExprResult ExprRes(Actions.ActOnNumericConstant(Tok)); 3447 ConsumeToken(); 3448 3449 SourceLocation EndLoc = MatchRHSPunctuation(tok::r_square, StartLoc); 3450 //FIXME: Use these 3451 CXX0XAttributeList Attr; 3452 if (getLang().CPlusPlus0x && isCXX0XAttributeSpecifier()) { 3453 Attr = ParseCXX0XAttributes(); 3454 } 3455 3456 // If there was an error parsing the assignment-expression, recover. 3457 if (ExprRes.isInvalid()) 3458 ExprRes.release(); // Deallocate expr, just use []. 3459 3460 // Remember that we parsed a array type, and remember its features. 3461 D.AddTypeInfo(DeclaratorChunk::getArray(0, false, 0, ExprRes.release(), 3462 StartLoc, EndLoc), 3463 EndLoc); 3464 return; 3465 } 3466 3467 // If valid, this location is the position where we read the 'static' keyword. 3468 SourceLocation StaticLoc; 3469 if (Tok.is(tok::kw_static)) 3470 StaticLoc = ConsumeToken(); 3471 3472 // If there is a type-qualifier-list, read it now. 3473 // Type qualifiers in an array subscript are a C99 feature. 3474 DeclSpec DS; 3475 ParseTypeQualifierListOpt(DS, false /*no attributes*/); 3476 3477 // If we haven't already read 'static', check to see if there is one after the 3478 // type-qualifier-list. 3479 if (!StaticLoc.isValid() && Tok.is(tok::kw_static)) 3480 StaticLoc = ConsumeToken(); 3481 3482 // Handle "direct-declarator [ type-qual-list[opt] * ]". 3483 bool isStar = false; 3484 ExprResult NumElements; 3485 3486 // Handle the case where we have '[*]' as the array size. However, a leading 3487 // star could be the start of an expression, for example 'X[*p + 4]'. Verify 3488 // the the token after the star is a ']'. Since stars in arrays are 3489 // infrequent, use of lookahead is not costly here. 3490 if (Tok.is(tok::star) && GetLookAheadToken(1).is(tok::r_square)) { 3491 ConsumeToken(); // Eat the '*'. 3492 3493 if (StaticLoc.isValid()) { 3494 Diag(StaticLoc, diag::err_unspecified_vla_size_with_static); 3495 StaticLoc = SourceLocation(); // Drop the static. 3496 } 3497 isStar = true; 3498 } else if (Tok.isNot(tok::r_square)) { 3499 // Note, in C89, this production uses the constant-expr production instead 3500 // of assignment-expr. The only difference is that assignment-expr allows 3501 // things like '=' and '*='. Sema rejects these in C89 mode because they 3502 // are not i-c-e's, so we don't need to distinguish between the two here. 3503 3504 // Parse the constant-expression or assignment-expression now (depending 3505 // on dialect). 3506 if (getLang().CPlusPlus) 3507 NumElements = ParseConstantExpression(); 3508 else 3509 NumElements = ParseAssignmentExpression(); 3510 } 3511 3512 // If there was an error parsing the assignment-expression, recover. 3513 if (NumElements.isInvalid()) { 3514 D.setInvalidType(true); 3515 // If the expression was invalid, skip it. 3516 SkipUntil(tok::r_square); 3517 return; 3518 } 3519 3520 SourceLocation EndLoc = MatchRHSPunctuation(tok::r_square, StartLoc); 3521 3522 //FIXME: Use these 3523 CXX0XAttributeList Attr; 3524 if (getLang().CPlusPlus0x && isCXX0XAttributeSpecifier()) { 3525 Attr = ParseCXX0XAttributes(); 3526 } 3527 3528 // Remember that we parsed a array type, and remember its features. 3529 D.AddTypeInfo(DeclaratorChunk::getArray(DS.getTypeQualifiers(), 3530 StaticLoc.isValid(), isStar, 3531 NumElements.release(), 3532 StartLoc, EndLoc), 3533 EndLoc); 3534} 3535 3536/// [GNU] typeof-specifier: 3537/// typeof ( expressions ) 3538/// typeof ( type-name ) 3539/// [GNU/C++] typeof unary-expression 3540/// 3541void Parser::ParseTypeofSpecifier(DeclSpec &DS) { 3542 assert(Tok.is(tok::kw_typeof) && "Not a typeof specifier"); 3543 Token OpTok = Tok; 3544 SourceLocation StartLoc = ConsumeToken(); 3545 3546 const bool hasParens = Tok.is(tok::l_paren); 3547 3548 bool isCastExpr; 3549 ParsedType CastTy; 3550 SourceRange CastRange; 3551 ExprResult Operand = ParseExprAfterTypeofSizeofAlignof(OpTok, 3552 isCastExpr, 3553 CastTy, 3554 CastRange); 3555 if (hasParens) 3556 DS.setTypeofParensRange(CastRange); 3557 3558 if (CastRange.getEnd().isInvalid()) 3559 // FIXME: Not accurate, the range gets one token more than it should. 3560 DS.SetRangeEnd(Tok.getLocation()); 3561 else 3562 DS.SetRangeEnd(CastRange.getEnd()); 3563 3564 if (isCastExpr) { 3565 if (!CastTy) { 3566 DS.SetTypeSpecError(); 3567 return; 3568 } 3569 3570 const char *PrevSpec = 0; 3571 unsigned DiagID; 3572 // Check for duplicate type specifiers (e.g. "int typeof(int)"). 3573 if (DS.SetTypeSpecType(DeclSpec::TST_typeofType, StartLoc, PrevSpec, 3574 DiagID, CastTy)) 3575 Diag(StartLoc, DiagID) << PrevSpec; 3576 return; 3577 } 3578 3579 // If we get here, the operand to the typeof was an expresion. 3580 if (Operand.isInvalid()) { 3581 DS.SetTypeSpecError(); 3582 return; 3583 } 3584 3585 const char *PrevSpec = 0; 3586 unsigned DiagID; 3587 // Check for duplicate type specifiers (e.g. "int typeof(int)"). 3588 if (DS.SetTypeSpecType(DeclSpec::TST_typeofExpr, StartLoc, PrevSpec, 3589 DiagID, Operand.get())) 3590 Diag(StartLoc, DiagID) << PrevSpec; 3591} 3592 3593 3594/// TryAltiVecVectorTokenOutOfLine - Out of line body that should only be called 3595/// from TryAltiVecVectorToken. 3596bool Parser::TryAltiVecVectorTokenOutOfLine() { 3597 Token Next = NextToken(); 3598 switch (Next.getKind()) { 3599 default: return false; 3600 case tok::kw_short: 3601 case tok::kw_long: 3602 case tok::kw_signed: 3603 case tok::kw_unsigned: 3604 case tok::kw_void: 3605 case tok::kw_char: 3606 case tok::kw_int: 3607 case tok::kw_float: 3608 case tok::kw_double: 3609 case tok::kw_bool: 3610 case tok::kw___pixel: 3611 Tok.setKind(tok::kw___vector); 3612 return true; 3613 case tok::identifier: 3614 if (Next.getIdentifierInfo() == Ident_pixel) { 3615 Tok.setKind(tok::kw___vector); 3616 return true; 3617 } 3618 return false; 3619 } 3620} 3621 3622bool Parser::TryAltiVecTokenOutOfLine(DeclSpec &DS, SourceLocation Loc, 3623 const char *&PrevSpec, unsigned &DiagID, 3624 bool &isInvalid) { 3625 if (Tok.getIdentifierInfo() == Ident_vector) { 3626 Token Next = NextToken(); 3627 switch (Next.getKind()) { 3628 case tok::kw_short: 3629 case tok::kw_long: 3630 case tok::kw_signed: 3631 case tok::kw_unsigned: 3632 case tok::kw_void: 3633 case tok::kw_char: 3634 case tok::kw_int: 3635 case tok::kw_float: 3636 case tok::kw_double: 3637 case tok::kw_bool: 3638 case tok::kw___pixel: 3639 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID); 3640 return true; 3641 case tok::identifier: 3642 if (Next.getIdentifierInfo() == Ident_pixel) { 3643 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID); 3644 return true; 3645 } 3646 break; 3647 default: 3648 break; 3649 } 3650 } else if ((Tok.getIdentifierInfo() == Ident_pixel) && 3651 DS.isTypeAltiVecVector()) { 3652 isInvalid = DS.SetTypeAltiVecPixel(true, Loc, PrevSpec, DiagID); 3653 return true; 3654 } 3655 return false; 3656} 3657 3658