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