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