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