ParseDecl.cpp revision bdd563ec391b0a83fc6d04b8a8ea3022aa702f74
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 // This is almost certainly an invalid type name. Let the action emit a 692 // diagnostic and attempt to recover. 693 Action::TypeTy *T = 0; 694 if (Actions.DiagnoseUnknownTypeName(*Tok.getIdentifierInfo(), Loc, 695 CurScope, SS, T)) { 696 // The action emitted a diagnostic, so we don't have to. 697 if (T) { 698 // The action has suggested that the type T could be used. Set that as 699 // the type in the declaration specifiers, consume the would-be type 700 // name token, and we're done. 701 const char *PrevSpec; 702 unsigned DiagID; 703 DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID, T, 704 false); 705 DS.SetRangeEnd(Tok.getLocation()); 706 ConsumeToken(); 707 708 // There may be other declaration specifiers after this. 709 return true; 710 } 711 712 // Fall through; the action had no suggestion for us. 713 } else { 714 // The action did not emit a diagnostic, so emit one now. 715 SourceRange R; 716 if (SS) R = SS->getRange(); 717 Diag(Loc, diag::err_unknown_typename) << Tok.getIdentifierInfo() << R; 718 } 719 720 // Mark this as an error. 721 const char *PrevSpec; 722 unsigned DiagID; 723 DS.SetTypeSpecType(DeclSpec::TST_error, Loc, PrevSpec, DiagID); 724 DS.SetRangeEnd(Tok.getLocation()); 725 ConsumeToken(); 726 727 // TODO: Could inject an invalid typedef decl in an enclosing scope to 728 // avoid rippling error messages on subsequent uses of the same type, 729 // could be useful if #include was forgotten. 730 return false; 731} 732 733/// ParseDeclarationSpecifiers 734/// declaration-specifiers: [C99 6.7] 735/// storage-class-specifier declaration-specifiers[opt] 736/// type-specifier declaration-specifiers[opt] 737/// [C99] function-specifier declaration-specifiers[opt] 738/// [GNU] attributes declaration-specifiers[opt] 739/// 740/// storage-class-specifier: [C99 6.7.1] 741/// 'typedef' 742/// 'extern' 743/// 'static' 744/// 'auto' 745/// 'register' 746/// [C++] 'mutable' 747/// [GNU] '__thread' 748/// function-specifier: [C99 6.7.4] 749/// [C99] 'inline' 750/// [C++] 'virtual' 751/// [C++] 'explicit' 752/// 'friend': [C++ dcl.friend] 753 754/// 755void Parser::ParseDeclarationSpecifiers(DeclSpec &DS, 756 const ParsedTemplateInfo &TemplateInfo, 757 AccessSpecifier AS, 758 DeclSpecContext DSContext) { 759 if (Tok.is(tok::code_completion)) { 760 Actions.CodeCompleteOrdinaryName(CurScope); 761 ConsumeToken(); 762 } 763 764 DS.SetRangeStart(Tok.getLocation()); 765 while (1) { 766 bool isInvalid = false; 767 const char *PrevSpec = 0; 768 unsigned DiagID = 0; 769 770 SourceLocation Loc = Tok.getLocation(); 771 772 switch (Tok.getKind()) { 773 default: 774 DoneWithDeclSpec: 775 // If this is not a declaration specifier token, we're done reading decl 776 // specifiers. First verify that DeclSpec's are consistent. 777 DS.Finish(Diags, PP); 778 return; 779 780 case tok::coloncolon: // ::foo::bar 781 // Annotate C++ scope specifiers. If we get one, loop. 782 if (TryAnnotateCXXScopeToken(true)) 783 continue; 784 goto DoneWithDeclSpec; 785 786 case tok::annot_cxxscope: { 787 if (DS.hasTypeSpecifier()) 788 goto DoneWithDeclSpec; 789 790 // We are looking for a qualified typename. 791 Token Next = NextToken(); 792 if (Next.is(tok::annot_template_id) && 793 static_cast<TemplateIdAnnotation *>(Next.getAnnotationValue()) 794 ->Kind == TNK_Type_template) { 795 // We have a qualified template-id, e.g., N::A<int> 796 CXXScopeSpec SS; 797 ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/0, true); 798 assert(Tok.is(tok::annot_template_id) && 799 "ParseOptionalCXXScopeSpecifier not working"); 800 AnnotateTemplateIdTokenAsType(&SS); 801 continue; 802 } 803 804 if (Next.is(tok::annot_typename)) { 805 // FIXME: is this scope-specifier getting dropped? 806 ConsumeToken(); // the scope-specifier 807 if (Tok.getAnnotationValue()) 808 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, 809 PrevSpec, DiagID, 810 Tok.getAnnotationValue()); 811 else 812 DS.SetTypeSpecError(); 813 DS.SetRangeEnd(Tok.getAnnotationEndLoc()); 814 ConsumeToken(); // The typename 815 } 816 817 if (Next.isNot(tok::identifier)) 818 goto DoneWithDeclSpec; 819 820 CXXScopeSpec SS; 821 SS.setScopeRep(Tok.getAnnotationValue()); 822 SS.setRange(Tok.getAnnotationRange()); 823 824 // If the next token is the name of the class type that the C++ scope 825 // denotes, followed by a '(', then this is a constructor declaration. 826 // We're done with the decl-specifiers. 827 if (Actions.isCurrentClassName(*Next.getIdentifierInfo(), 828 CurScope, &SS) && 829 GetLookAheadToken(2).is(tok::l_paren)) 830 goto DoneWithDeclSpec; 831 832 TypeTy *TypeRep = Actions.getTypeName(*Next.getIdentifierInfo(), 833 Next.getLocation(), CurScope, &SS); 834 835 // If the referenced identifier is not a type, then this declspec is 836 // erroneous: We already checked about that it has no type specifier, and 837 // C++ doesn't have implicit int. Diagnose it as a typo w.r.t. to the 838 // typename. 839 if (TypeRep == 0) { 840 ConsumeToken(); // Eat the scope spec so the identifier is current. 841 if (ParseImplicitInt(DS, &SS, TemplateInfo, AS)) continue; 842 goto DoneWithDeclSpec; 843 } 844 845 ConsumeToken(); // The C++ scope. 846 847 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, 848 DiagID, TypeRep); 849 if (isInvalid) 850 break; 851 852 DS.SetRangeEnd(Tok.getLocation()); 853 ConsumeToken(); // The typename. 854 855 continue; 856 } 857 858 case tok::annot_typename: { 859 if (Tok.getAnnotationValue()) 860 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, 861 DiagID, Tok.getAnnotationValue()); 862 else 863 DS.SetTypeSpecError(); 864 DS.SetRangeEnd(Tok.getAnnotationEndLoc()); 865 ConsumeToken(); // The typename 866 867 // Objective-C supports syntax of the form 'id<proto1,proto2>' where 'id' 868 // is a specific typedef and 'itf<proto1,proto2>' where 'itf' is an 869 // Objective-C interface. If we don't have Objective-C or a '<', this is 870 // just a normal reference to a typedef name. 871 if (!Tok.is(tok::less) || !getLang().ObjC1) 872 continue; 873 874 SourceLocation LAngleLoc, EndProtoLoc; 875 llvm::SmallVector<DeclPtrTy, 8> ProtocolDecl; 876 llvm::SmallVector<SourceLocation, 8> ProtocolLocs; 877 ParseObjCProtocolReferences(ProtocolDecl, ProtocolLocs, false, 878 LAngleLoc, EndProtoLoc); 879 DS.setProtocolQualifiers(ProtocolDecl.data(), ProtocolDecl.size(), 880 ProtocolLocs.data(), LAngleLoc); 881 882 DS.SetRangeEnd(EndProtoLoc); 883 continue; 884 } 885 886 // typedef-name 887 case tok::identifier: { 888 // In C++, check to see if this is a scope specifier like foo::bar::, if 889 // so handle it as such. This is important for ctor parsing. 890 if (getLang().CPlusPlus && TryAnnotateCXXScopeToken(true)) 891 continue; 892 893 // This identifier can only be a typedef name if we haven't already seen 894 // a type-specifier. Without this check we misparse: 895 // typedef int X; struct Y { short X; }; as 'short int'. 896 if (DS.hasTypeSpecifier()) 897 goto DoneWithDeclSpec; 898 899 // It has to be available as a typedef too! 900 TypeTy *TypeRep = Actions.getTypeName(*Tok.getIdentifierInfo(), 901 Tok.getLocation(), CurScope); 902 903 // If this is not a typedef name, don't parse it as part of the declspec, 904 // it must be an implicit int or an error. 905 if (TypeRep == 0) { 906 if (ParseImplicitInt(DS, 0, TemplateInfo, AS)) continue; 907 goto DoneWithDeclSpec; 908 } 909 910 // C++: If the identifier is actually the name of the class type 911 // being defined and the next token is a '(', then this is a 912 // constructor declaration. We're done with the decl-specifiers 913 // and will treat this token as an identifier. 914 if (getLang().CPlusPlus && 915 (CurScope->isClassScope() || 916 (CurScope->isTemplateParamScope() && 917 CurScope->getParent()->isClassScope())) && 918 Actions.isCurrentClassName(*Tok.getIdentifierInfo(), CurScope) && 919 NextToken().getKind() == tok::l_paren) 920 goto DoneWithDeclSpec; 921 922 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, 923 DiagID, TypeRep); 924 if (isInvalid) 925 break; 926 927 DS.SetRangeEnd(Tok.getLocation()); 928 ConsumeToken(); // The identifier 929 930 // Objective-C supports syntax of the form 'id<proto1,proto2>' where 'id' 931 // is a specific typedef and 'itf<proto1,proto2>' where 'itf' is an 932 // Objective-C interface. If we don't have Objective-C or a '<', this is 933 // just a normal reference to a typedef name. 934 if (!Tok.is(tok::less) || !getLang().ObjC1) 935 continue; 936 937 SourceLocation LAngleLoc, EndProtoLoc; 938 llvm::SmallVector<DeclPtrTy, 8> ProtocolDecl; 939 llvm::SmallVector<SourceLocation, 8> ProtocolLocs; 940 ParseObjCProtocolReferences(ProtocolDecl, ProtocolLocs, false, 941 LAngleLoc, EndProtoLoc); 942 DS.setProtocolQualifiers(ProtocolDecl.data(), ProtocolDecl.size(), 943 ProtocolLocs.data(), LAngleLoc); 944 945 DS.SetRangeEnd(EndProtoLoc); 946 947 // Need to support trailing type qualifiers (e.g. "id<p> const"). 948 // If a type specifier follows, it will be diagnosed elsewhere. 949 continue; 950 } 951 952 // type-name 953 case tok::annot_template_id: { 954 TemplateIdAnnotation *TemplateId 955 = static_cast<TemplateIdAnnotation *>(Tok.getAnnotationValue()); 956 if (TemplateId->Kind != TNK_Type_template) { 957 // This template-id does not refer to a type name, so we're 958 // done with the type-specifiers. 959 goto DoneWithDeclSpec; 960 } 961 962 // Turn the template-id annotation token into a type annotation 963 // token, then try again to parse it as a type-specifier. 964 AnnotateTemplateIdTokenAsType(); 965 continue; 966 } 967 968 // GNU attributes support. 969 case tok::kw___attribute: 970 DS.AddAttributes(ParseAttributes()); 971 continue; 972 973 // Microsoft declspec support. 974 case tok::kw___declspec: 975 DS.AddAttributes(ParseMicrosoftDeclSpec()); 976 continue; 977 978 // Microsoft single token adornments. 979 case tok::kw___forceinline: 980 // FIXME: Add handling here! 981 break; 982 983 case tok::kw___ptr64: 984 case tok::kw___w64: 985 case tok::kw___cdecl: 986 case tok::kw___stdcall: 987 case tok::kw___fastcall: 988 DS.AddAttributes(ParseMicrosoftTypeAttributes()); 989 continue; 990 991 // storage-class-specifier 992 case tok::kw_typedef: 993 isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_typedef, Loc, PrevSpec, 994 DiagID); 995 break; 996 case tok::kw_extern: 997 if (DS.isThreadSpecified()) 998 Diag(Tok, diag::ext_thread_before) << "extern"; 999 isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_extern, Loc, PrevSpec, 1000 DiagID); 1001 break; 1002 case tok::kw___private_extern__: 1003 isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_private_extern, Loc, 1004 PrevSpec, DiagID); 1005 break; 1006 case tok::kw_static: 1007 if (DS.isThreadSpecified()) 1008 Diag(Tok, diag::ext_thread_before) << "static"; 1009 isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_static, Loc, PrevSpec, 1010 DiagID); 1011 break; 1012 case tok::kw_auto: 1013 if (getLang().CPlusPlus0x) 1014 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_auto, Loc, PrevSpec, 1015 DiagID); 1016 else 1017 isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_auto, Loc, PrevSpec, 1018 DiagID); 1019 break; 1020 case tok::kw_register: 1021 isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_register, Loc, PrevSpec, 1022 DiagID); 1023 break; 1024 case tok::kw_mutable: 1025 isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_mutable, Loc, PrevSpec, 1026 DiagID); 1027 break; 1028 case tok::kw___thread: 1029 isInvalid = DS.SetStorageClassSpecThread(Loc, PrevSpec, DiagID); 1030 break; 1031 1032 // function-specifier 1033 case tok::kw_inline: 1034 isInvalid = DS.SetFunctionSpecInline(Loc, PrevSpec, DiagID); 1035 break; 1036 case tok::kw_virtual: 1037 isInvalid = DS.SetFunctionSpecVirtual(Loc, PrevSpec, DiagID); 1038 break; 1039 case tok::kw_explicit: 1040 isInvalid = DS.SetFunctionSpecExplicit(Loc, PrevSpec, DiagID); 1041 break; 1042 1043 // friend 1044 case tok::kw_friend: 1045 if (DSContext == DSC_class) 1046 isInvalid = DS.SetFriendSpec(Loc, PrevSpec, DiagID); 1047 else { 1048 PrevSpec = ""; // not actually used by the diagnostic 1049 DiagID = diag::err_friend_invalid_in_context; 1050 isInvalid = true; 1051 } 1052 break; 1053 1054 // type-specifier 1055 case tok::kw_short: 1056 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_short, Loc, PrevSpec, 1057 DiagID); 1058 break; 1059 case tok::kw_long: 1060 if (DS.getTypeSpecWidth() != DeclSpec::TSW_long) 1061 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_long, Loc, PrevSpec, 1062 DiagID); 1063 else 1064 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec, 1065 DiagID); 1066 break; 1067 case tok::kw_signed: 1068 isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_signed, Loc, PrevSpec, 1069 DiagID); 1070 break; 1071 case tok::kw_unsigned: 1072 isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_unsigned, Loc, PrevSpec, 1073 DiagID); 1074 break; 1075 case tok::kw__Complex: 1076 isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_complex, Loc, PrevSpec, 1077 DiagID); 1078 break; 1079 case tok::kw__Imaginary: 1080 isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_imaginary, Loc, PrevSpec, 1081 DiagID); 1082 break; 1083 case tok::kw_void: 1084 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec, 1085 DiagID); 1086 break; 1087 case tok::kw_char: 1088 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec, 1089 DiagID); 1090 break; 1091 case tok::kw_int: 1092 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec, 1093 DiagID); 1094 break; 1095 case tok::kw_float: 1096 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec, 1097 DiagID); 1098 break; 1099 case tok::kw_double: 1100 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec, 1101 DiagID); 1102 break; 1103 case tok::kw_wchar_t: 1104 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec, 1105 DiagID); 1106 break; 1107 case tok::kw_char16_t: 1108 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char16, Loc, PrevSpec, 1109 DiagID); 1110 break; 1111 case tok::kw_char32_t: 1112 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char32, Loc, PrevSpec, 1113 DiagID); 1114 break; 1115 case tok::kw_bool: 1116 case tok::kw__Bool: 1117 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec, 1118 DiagID); 1119 break; 1120 case tok::kw__Decimal32: 1121 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal32, Loc, PrevSpec, 1122 DiagID); 1123 break; 1124 case tok::kw__Decimal64: 1125 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal64, Loc, PrevSpec, 1126 DiagID); 1127 break; 1128 case tok::kw__Decimal128: 1129 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal128, Loc, PrevSpec, 1130 DiagID); 1131 break; 1132 1133 // class-specifier: 1134 case tok::kw_class: 1135 case tok::kw_struct: 1136 case tok::kw_union: { 1137 tok::TokenKind Kind = Tok.getKind(); 1138 ConsumeToken(); 1139 ParseClassSpecifier(Kind, Loc, DS, TemplateInfo, AS); 1140 continue; 1141 } 1142 1143 // enum-specifier: 1144 case tok::kw_enum: 1145 ConsumeToken(); 1146 ParseEnumSpecifier(Loc, DS, AS); 1147 continue; 1148 1149 // cv-qualifier: 1150 case tok::kw_const: 1151 isInvalid = DS.SetTypeQual(DeclSpec::TQ_const, Loc, PrevSpec, DiagID, 1152 getLang()); 1153 break; 1154 case tok::kw_volatile: 1155 isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, DiagID, 1156 getLang()); 1157 break; 1158 case tok::kw_restrict: 1159 isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, DiagID, 1160 getLang()); 1161 break; 1162 1163 // C++ typename-specifier: 1164 case tok::kw_typename: 1165 if (TryAnnotateTypeOrScopeToken()) 1166 continue; 1167 break; 1168 1169 // GNU typeof support. 1170 case tok::kw_typeof: 1171 ParseTypeofSpecifier(DS); 1172 continue; 1173 1174 case tok::kw_decltype: 1175 ParseDecltypeSpecifier(DS); 1176 continue; 1177 1178 case tok::less: 1179 // GCC ObjC supports types like "<SomeProtocol>" as a synonym for 1180 // "id<SomeProtocol>". This is hopelessly old fashioned and dangerous, 1181 // but we support it. 1182 if (DS.hasTypeSpecifier() || !getLang().ObjC1) 1183 goto DoneWithDeclSpec; 1184 1185 { 1186 SourceLocation LAngleLoc, EndProtoLoc; 1187 llvm::SmallVector<DeclPtrTy, 8> ProtocolDecl; 1188 llvm::SmallVector<SourceLocation, 8> ProtocolLocs; 1189 ParseObjCProtocolReferences(ProtocolDecl, ProtocolLocs, false, 1190 LAngleLoc, EndProtoLoc); 1191 DS.setProtocolQualifiers(ProtocolDecl.data(), ProtocolDecl.size(), 1192 ProtocolLocs.data(), LAngleLoc); 1193 DS.SetRangeEnd(EndProtoLoc); 1194 1195 Diag(Loc, diag::warn_objc_protocol_qualifier_missing_id) 1196 << CodeModificationHint::CreateInsertion(Loc, "id") 1197 << SourceRange(Loc, EndProtoLoc); 1198 // Need to support trailing type qualifiers (e.g. "id<p> const"). 1199 // If a type specifier follows, it will be diagnosed elsewhere. 1200 continue; 1201 } 1202 } 1203 // If the specifier wasn't legal, issue a diagnostic. 1204 if (isInvalid) { 1205 assert(PrevSpec && "Method did not return previous specifier!"); 1206 assert(DiagID); 1207 Diag(Tok, DiagID) << PrevSpec; 1208 } 1209 DS.SetRangeEnd(Tok.getLocation()); 1210 ConsumeToken(); 1211 } 1212} 1213 1214/// ParseOptionalTypeSpecifier - Try to parse a single type-specifier. We 1215/// primarily follow the C++ grammar with additions for C99 and GNU, 1216/// which together subsume the C grammar. Note that the C++ 1217/// type-specifier also includes the C type-qualifier (for const, 1218/// volatile, and C99 restrict). Returns true if a type-specifier was 1219/// found (and parsed), false otherwise. 1220/// 1221/// type-specifier: [C++ 7.1.5] 1222/// simple-type-specifier 1223/// class-specifier 1224/// enum-specifier 1225/// elaborated-type-specifier [TODO] 1226/// cv-qualifier 1227/// 1228/// cv-qualifier: [C++ 7.1.5.1] 1229/// 'const' 1230/// 'volatile' 1231/// [C99] 'restrict' 1232/// 1233/// simple-type-specifier: [ C++ 7.1.5.2] 1234/// '::'[opt] nested-name-specifier[opt] type-name [TODO] 1235/// '::'[opt] nested-name-specifier 'template' template-id [TODO] 1236/// 'char' 1237/// 'wchar_t' 1238/// 'bool' 1239/// 'short' 1240/// 'int' 1241/// 'long' 1242/// 'signed' 1243/// 'unsigned' 1244/// 'float' 1245/// 'double' 1246/// 'void' 1247/// [C99] '_Bool' 1248/// [C99] '_Complex' 1249/// [C99] '_Imaginary' // Removed in TC2? 1250/// [GNU] '_Decimal32' 1251/// [GNU] '_Decimal64' 1252/// [GNU] '_Decimal128' 1253/// [GNU] typeof-specifier 1254/// [OBJC] class-name objc-protocol-refs[opt] [TODO] 1255/// [OBJC] typedef-name objc-protocol-refs[opt] [TODO] 1256/// [C++0x] 'decltype' ( expression ) 1257bool Parser::ParseOptionalTypeSpecifier(DeclSpec &DS, bool& isInvalid, 1258 const char *&PrevSpec, 1259 unsigned &DiagID, 1260 const ParsedTemplateInfo &TemplateInfo) { 1261 SourceLocation Loc = Tok.getLocation(); 1262 1263 switch (Tok.getKind()) { 1264 case tok::identifier: // foo::bar 1265 case tok::kw_typename: // typename foo::bar 1266 // Annotate typenames and C++ scope specifiers. If we get one, just 1267 // recurse to handle whatever we get. 1268 if (TryAnnotateTypeOrScopeToken()) 1269 return ParseOptionalTypeSpecifier(DS, isInvalid, PrevSpec, DiagID, 1270 TemplateInfo); 1271 // Otherwise, not a type specifier. 1272 return false; 1273 case tok::coloncolon: // ::foo::bar 1274 if (NextToken().is(tok::kw_new) || // ::new 1275 NextToken().is(tok::kw_delete)) // ::delete 1276 return false; 1277 1278 // Annotate typenames and C++ scope specifiers. If we get one, just 1279 // recurse to handle whatever we get. 1280 if (TryAnnotateTypeOrScopeToken()) 1281 return ParseOptionalTypeSpecifier(DS, isInvalid, PrevSpec, DiagID, 1282 TemplateInfo); 1283 // Otherwise, not a type specifier. 1284 return false; 1285 1286 // simple-type-specifier: 1287 case tok::annot_typename: { 1288 if (Tok.getAnnotationValue()) 1289 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, 1290 DiagID, Tok.getAnnotationValue()); 1291 else 1292 DS.SetTypeSpecError(); 1293 DS.SetRangeEnd(Tok.getAnnotationEndLoc()); 1294 ConsumeToken(); // The typename 1295 1296 // Objective-C supports syntax of the form 'id<proto1,proto2>' where 'id' 1297 // is a specific typedef and 'itf<proto1,proto2>' where 'itf' is an 1298 // Objective-C interface. If we don't have Objective-C or a '<', this is 1299 // just a normal reference to a typedef name. 1300 if (!Tok.is(tok::less) || !getLang().ObjC1) 1301 return true; 1302 1303 SourceLocation LAngleLoc, EndProtoLoc; 1304 llvm::SmallVector<DeclPtrTy, 8> ProtocolDecl; 1305 llvm::SmallVector<SourceLocation, 8> ProtocolLocs; 1306 ParseObjCProtocolReferences(ProtocolDecl, ProtocolLocs, false, 1307 LAngleLoc, EndProtoLoc); 1308 DS.setProtocolQualifiers(ProtocolDecl.data(), ProtocolDecl.size(), 1309 ProtocolLocs.data(), LAngleLoc); 1310 1311 DS.SetRangeEnd(EndProtoLoc); 1312 return true; 1313 } 1314 1315 case tok::kw_short: 1316 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_short, Loc, PrevSpec, DiagID); 1317 break; 1318 case tok::kw_long: 1319 if (DS.getTypeSpecWidth() != DeclSpec::TSW_long) 1320 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_long, Loc, PrevSpec, 1321 DiagID); 1322 else 1323 isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec, 1324 DiagID); 1325 break; 1326 case tok::kw_signed: 1327 isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_signed, Loc, PrevSpec, DiagID); 1328 break; 1329 case tok::kw_unsigned: 1330 isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_unsigned, Loc, PrevSpec, 1331 DiagID); 1332 break; 1333 case tok::kw__Complex: 1334 isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_complex, Loc, PrevSpec, 1335 DiagID); 1336 break; 1337 case tok::kw__Imaginary: 1338 isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_imaginary, Loc, PrevSpec, 1339 DiagID); 1340 break; 1341 case tok::kw_void: 1342 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec, DiagID); 1343 break; 1344 case tok::kw_char: 1345 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec, DiagID); 1346 break; 1347 case tok::kw_int: 1348 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec, DiagID); 1349 break; 1350 case tok::kw_float: 1351 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec, DiagID); 1352 break; 1353 case tok::kw_double: 1354 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec, DiagID); 1355 break; 1356 case tok::kw_wchar_t: 1357 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec, DiagID); 1358 break; 1359 case tok::kw_char16_t: 1360 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char16, Loc, PrevSpec, DiagID); 1361 break; 1362 case tok::kw_char32_t: 1363 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char32, Loc, PrevSpec, DiagID); 1364 break; 1365 case tok::kw_bool: 1366 case tok::kw__Bool: 1367 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec, DiagID); 1368 break; 1369 case tok::kw__Decimal32: 1370 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal32, Loc, PrevSpec, 1371 DiagID); 1372 break; 1373 case tok::kw__Decimal64: 1374 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal64, Loc, PrevSpec, 1375 DiagID); 1376 break; 1377 case tok::kw__Decimal128: 1378 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal128, Loc, PrevSpec, 1379 DiagID); 1380 break; 1381 1382 // class-specifier: 1383 case tok::kw_class: 1384 case tok::kw_struct: 1385 case tok::kw_union: { 1386 tok::TokenKind Kind = Tok.getKind(); 1387 ConsumeToken(); 1388 ParseClassSpecifier(Kind, Loc, DS, TemplateInfo); 1389 return true; 1390 } 1391 1392 // enum-specifier: 1393 case tok::kw_enum: 1394 ConsumeToken(); 1395 ParseEnumSpecifier(Loc, DS); 1396 return true; 1397 1398 // cv-qualifier: 1399 case tok::kw_const: 1400 isInvalid = DS.SetTypeQual(DeclSpec::TQ_const , Loc, PrevSpec, 1401 DiagID, getLang()); 1402 break; 1403 case tok::kw_volatile: 1404 isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, 1405 DiagID, getLang()); 1406 break; 1407 case tok::kw_restrict: 1408 isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, 1409 DiagID, getLang()); 1410 break; 1411 1412 // GNU typeof support. 1413 case tok::kw_typeof: 1414 ParseTypeofSpecifier(DS); 1415 return true; 1416 1417 // C++0x decltype support. 1418 case tok::kw_decltype: 1419 ParseDecltypeSpecifier(DS); 1420 return true; 1421 1422 // C++0x auto support. 1423 case tok::kw_auto: 1424 if (!getLang().CPlusPlus0x) 1425 return false; 1426 1427 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_auto, Loc, PrevSpec, DiagID); 1428 break; 1429 case tok::kw___ptr64: 1430 case tok::kw___w64: 1431 case tok::kw___cdecl: 1432 case tok::kw___stdcall: 1433 case tok::kw___fastcall: 1434 DS.AddAttributes(ParseMicrosoftTypeAttributes()); 1435 return true; 1436 1437 default: 1438 // Not a type-specifier; do nothing. 1439 return false; 1440 } 1441 1442 // If the specifier combination wasn't legal, issue a diagnostic. 1443 if (isInvalid) { 1444 assert(PrevSpec && "Method did not return previous specifier!"); 1445 // Pick between error or extwarn. 1446 Diag(Tok, DiagID) << PrevSpec; 1447 } 1448 DS.SetRangeEnd(Tok.getLocation()); 1449 ConsumeToken(); // whatever we parsed above. 1450 return true; 1451} 1452 1453/// ParseStructDeclaration - Parse a struct declaration without the terminating 1454/// semicolon. 1455/// 1456/// struct-declaration: 1457/// specifier-qualifier-list struct-declarator-list 1458/// [GNU] __extension__ struct-declaration 1459/// [GNU] specifier-qualifier-list 1460/// struct-declarator-list: 1461/// struct-declarator 1462/// struct-declarator-list ',' struct-declarator 1463/// [GNU] struct-declarator-list ',' attributes[opt] struct-declarator 1464/// struct-declarator: 1465/// declarator 1466/// [GNU] declarator attributes[opt] 1467/// declarator[opt] ':' constant-expression 1468/// [GNU] declarator[opt] ':' constant-expression attributes[opt] 1469/// 1470void Parser:: 1471ParseStructDeclaration(DeclSpec &DS, FieldCallback &Fields) { 1472 if (Tok.is(tok::kw___extension__)) { 1473 // __extension__ silences extension warnings in the subexpression. 1474 ExtensionRAIIObject O(Diags); // Use RAII to do this. 1475 ConsumeToken(); 1476 return ParseStructDeclaration(DS, Fields); 1477 } 1478 1479 // Parse the common specifier-qualifiers-list piece. 1480 SourceLocation DSStart = Tok.getLocation(); 1481 ParseSpecifierQualifierList(DS); 1482 1483 // If there are no declarators, this is a free-standing declaration 1484 // specifier. Let the actions module cope with it. 1485 if (Tok.is(tok::semi)) { 1486 Actions.ParsedFreeStandingDeclSpec(CurScope, DS); 1487 return; 1488 } 1489 1490 // Read struct-declarators until we find the semicolon. 1491 bool FirstDeclarator = true; 1492 while (1) { 1493 FieldDeclarator DeclaratorInfo(DS); 1494 1495 // Attributes are only allowed here on successive declarators. 1496 if (!FirstDeclarator && Tok.is(tok::kw___attribute)) { 1497 SourceLocation Loc; 1498 AttributeList *AttrList = ParseAttributes(&Loc); 1499 DeclaratorInfo.D.AddAttributes(AttrList, Loc); 1500 } 1501 1502 /// struct-declarator: declarator 1503 /// struct-declarator: declarator[opt] ':' constant-expression 1504 if (Tok.isNot(tok::colon)) 1505 ParseDeclarator(DeclaratorInfo.D); 1506 1507 if (Tok.is(tok::colon)) { 1508 ConsumeToken(); 1509 OwningExprResult Res(ParseConstantExpression()); 1510 if (Res.isInvalid()) 1511 SkipUntil(tok::semi, true, true); 1512 else 1513 DeclaratorInfo.BitfieldSize = Res.release(); 1514 } 1515 1516 // If attributes exist after the declarator, parse them. 1517 if (Tok.is(tok::kw___attribute)) { 1518 SourceLocation Loc; 1519 AttributeList *AttrList = ParseAttributes(&Loc); 1520 DeclaratorInfo.D.AddAttributes(AttrList, Loc); 1521 } 1522 1523 // We're done with this declarator; invoke the callback. 1524 (void) Fields.invoke(DeclaratorInfo); 1525 1526 // If we don't have a comma, it is either the end of the list (a ';') 1527 // or an error, bail out. 1528 if (Tok.isNot(tok::comma)) 1529 return; 1530 1531 // Consume the comma. 1532 ConsumeToken(); 1533 1534 FirstDeclarator = false; 1535 } 1536} 1537 1538/// ParseStructUnionBody 1539/// struct-contents: 1540/// struct-declaration-list 1541/// [EXT] empty 1542/// [GNU] "struct-declaration-list" without terminatoring ';' 1543/// struct-declaration-list: 1544/// struct-declaration 1545/// struct-declaration-list struct-declaration 1546/// [OBC] '@' 'defs' '(' class-name ')' 1547/// 1548void Parser::ParseStructUnionBody(SourceLocation RecordLoc, 1549 unsigned TagType, DeclPtrTy TagDecl) { 1550 PrettyStackTraceActionsDecl CrashInfo(TagDecl, RecordLoc, Actions, 1551 PP.getSourceManager(), 1552 "parsing struct/union body"); 1553 1554 SourceLocation LBraceLoc = ConsumeBrace(); 1555 1556 ParseScope StructScope(this, Scope::ClassScope|Scope::DeclScope); 1557 Actions.ActOnTagStartDefinition(CurScope, TagDecl); 1558 1559 // Empty structs are an extension in C (C99 6.7.2.1p7), but are allowed in 1560 // C++. 1561 if (Tok.is(tok::r_brace) && !getLang().CPlusPlus) 1562 Diag(Tok, diag::ext_empty_struct_union_enum) 1563 << DeclSpec::getSpecifierName((DeclSpec::TST)TagType); 1564 1565 llvm::SmallVector<DeclPtrTy, 32> FieldDecls; 1566 1567 // While we still have something to read, read the declarations in the struct. 1568 while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) { 1569 // Each iteration of this loop reads one struct-declaration. 1570 1571 // Check for extraneous top-level semicolon. 1572 if (Tok.is(tok::semi)) { 1573 Diag(Tok, diag::ext_extra_struct_semi) 1574 << CodeModificationHint::CreateRemoval(SourceRange(Tok.getLocation())); 1575 ConsumeToken(); 1576 continue; 1577 } 1578 1579 // Parse all the comma separated declarators. 1580 DeclSpec DS; 1581 1582 if (!Tok.is(tok::at)) { 1583 struct CFieldCallback : FieldCallback { 1584 Parser &P; 1585 DeclPtrTy TagDecl; 1586 llvm::SmallVectorImpl<DeclPtrTy> &FieldDecls; 1587 1588 CFieldCallback(Parser &P, DeclPtrTy TagDecl, 1589 llvm::SmallVectorImpl<DeclPtrTy> &FieldDecls) : 1590 P(P), TagDecl(TagDecl), FieldDecls(FieldDecls) {} 1591 1592 virtual DeclPtrTy invoke(FieldDeclarator &FD) { 1593 const DeclSpec &DS = FD.D.getDeclSpec(); 1594 DeclPtrTy Field; 1595 1596 // Install the declarator into the current TagDecl. 1597 if (FD.D.getExtension()) { 1598 // Silences extension warnings 1599 ExtensionRAIIObject O(P.Diags); 1600 Field = P.Actions.ActOnField(P.CurScope, TagDecl, 1601 DS.getSourceRange().getBegin(), 1602 FD.D, FD.BitfieldSize); 1603 } else { 1604 Field = P.Actions.ActOnField(P.CurScope, TagDecl, 1605 DS.getSourceRange().getBegin(), 1606 FD.D, FD.BitfieldSize); 1607 } 1608 FieldDecls.push_back(Field); 1609 return Field; 1610 } 1611 } Callback(*this, TagDecl, FieldDecls); 1612 1613 ParseStructDeclaration(DS, Callback); 1614 } else { // Handle @defs 1615 ConsumeToken(); 1616 if (!Tok.isObjCAtKeyword(tok::objc_defs)) { 1617 Diag(Tok, diag::err_unexpected_at); 1618 SkipUntil(tok::semi, true, true); 1619 continue; 1620 } 1621 ConsumeToken(); 1622 ExpectAndConsume(tok::l_paren, diag::err_expected_lparen); 1623 if (!Tok.is(tok::identifier)) { 1624 Diag(Tok, diag::err_expected_ident); 1625 SkipUntil(tok::semi, true, true); 1626 continue; 1627 } 1628 llvm::SmallVector<DeclPtrTy, 16> Fields; 1629 Actions.ActOnDefs(CurScope, TagDecl, Tok.getLocation(), 1630 Tok.getIdentifierInfo(), Fields); 1631 FieldDecls.insert(FieldDecls.end(), Fields.begin(), Fields.end()); 1632 ConsumeToken(); 1633 ExpectAndConsume(tok::r_paren, diag::err_expected_rparen); 1634 } 1635 1636 if (Tok.is(tok::semi)) { 1637 ConsumeToken(); 1638 } else if (Tok.is(tok::r_brace)) { 1639 Diag(Tok, diag::ext_expected_semi_decl_list); 1640 break; 1641 } else { 1642 Diag(Tok, diag::err_expected_semi_decl_list); 1643 // Skip to end of block or statement 1644 SkipUntil(tok::r_brace, true, true); 1645 } 1646 } 1647 1648 SourceLocation RBraceLoc = MatchRHSPunctuation(tok::r_brace, LBraceLoc); 1649 1650 AttributeList *AttrList = 0; 1651 // If attributes exist after struct contents, parse them. 1652 if (Tok.is(tok::kw___attribute)) 1653 AttrList = ParseAttributes(); 1654 1655 Actions.ActOnFields(CurScope, 1656 RecordLoc, TagDecl, FieldDecls.data(), FieldDecls.size(), 1657 LBraceLoc, RBraceLoc, 1658 AttrList); 1659 StructScope.Exit(); 1660 Actions.ActOnTagFinishDefinition(CurScope, TagDecl, RBraceLoc); 1661} 1662 1663 1664/// ParseEnumSpecifier 1665/// enum-specifier: [C99 6.7.2.2] 1666/// 'enum' identifier[opt] '{' enumerator-list '}' 1667///[C99/C++]'enum' identifier[opt] '{' enumerator-list ',' '}' 1668/// [GNU] 'enum' attributes[opt] identifier[opt] '{' enumerator-list ',' [opt] 1669/// '}' attributes[opt] 1670/// 'enum' identifier 1671/// [GNU] 'enum' attributes[opt] identifier 1672/// 1673/// [C++] elaborated-type-specifier: 1674/// [C++] 'enum' '::'[opt] nested-name-specifier[opt] identifier 1675/// 1676void Parser::ParseEnumSpecifier(SourceLocation StartLoc, DeclSpec &DS, 1677 AccessSpecifier AS) { 1678 // Parse the tag portion of this. 1679 if (Tok.is(tok::code_completion)) { 1680 // Code completion for an enum name. 1681 Actions.CodeCompleteTag(CurScope, DeclSpec::TST_enum); 1682 ConsumeToken(); 1683 } 1684 1685 AttributeList *Attr = 0; 1686 // If attributes exist after tag, parse them. 1687 if (Tok.is(tok::kw___attribute)) 1688 Attr = ParseAttributes(); 1689 1690 CXXScopeSpec SS; 1691 if (getLang().CPlusPlus && ParseOptionalCXXScopeSpecifier(SS, 0, false)) { 1692 if (Tok.isNot(tok::identifier)) { 1693 Diag(Tok, diag::err_expected_ident); 1694 if (Tok.isNot(tok::l_brace)) { 1695 // Has no name and is not a definition. 1696 // Skip the rest of this declarator, up until the comma or semicolon. 1697 SkipUntil(tok::comma, true); 1698 return; 1699 } 1700 } 1701 } 1702 1703 // Must have either 'enum name' or 'enum {...}'. 1704 if (Tok.isNot(tok::identifier) && Tok.isNot(tok::l_brace)) { 1705 Diag(Tok, diag::err_expected_ident_lbrace); 1706 1707 // Skip the rest of this declarator, up until the comma or semicolon. 1708 SkipUntil(tok::comma, true); 1709 return; 1710 } 1711 1712 // If an identifier is present, consume and remember it. 1713 IdentifierInfo *Name = 0; 1714 SourceLocation NameLoc; 1715 if (Tok.is(tok::identifier)) { 1716 Name = Tok.getIdentifierInfo(); 1717 NameLoc = ConsumeToken(); 1718 } 1719 1720 // There are three options here. If we have 'enum foo;', then this is a 1721 // forward declaration. If we have 'enum foo {...' then this is a 1722 // definition. Otherwise we have something like 'enum foo xyz', a reference. 1723 // 1724 // This is needed to handle stuff like this right (C99 6.7.2.3p11): 1725 // enum foo {..}; void bar() { enum foo; } <- new foo in bar. 1726 // enum foo {..}; void bar() { enum foo x; } <- use of old foo. 1727 // 1728 Action::TagUseKind TUK; 1729 if (Tok.is(tok::l_brace)) 1730 TUK = Action::TUK_Definition; 1731 else if (Tok.is(tok::semi)) 1732 TUK = Action::TUK_Declaration; 1733 else 1734 TUK = Action::TUK_Reference; 1735 bool Owned = false; 1736 bool IsDependent = false; 1737 DeclPtrTy TagDecl = Actions.ActOnTag(CurScope, DeclSpec::TST_enum, TUK, 1738 StartLoc, SS, Name, NameLoc, Attr, AS, 1739 Action::MultiTemplateParamsArg(Actions), 1740 Owned, IsDependent); 1741 assert(!IsDependent && "didn't expect dependent enum"); 1742 1743 if (Tok.is(tok::l_brace)) 1744 ParseEnumBody(StartLoc, TagDecl); 1745 1746 // TODO: semantic analysis on the declspec for enums. 1747 const char *PrevSpec = 0; 1748 unsigned DiagID; 1749 if (DS.SetTypeSpecType(DeclSpec::TST_enum, StartLoc, PrevSpec, DiagID, 1750 TagDecl.getAs<void>(), Owned)) 1751 Diag(StartLoc, DiagID) << PrevSpec; 1752} 1753 1754/// ParseEnumBody - Parse a {} enclosed enumerator-list. 1755/// enumerator-list: 1756/// enumerator 1757/// enumerator-list ',' enumerator 1758/// enumerator: 1759/// enumeration-constant 1760/// enumeration-constant '=' constant-expression 1761/// enumeration-constant: 1762/// identifier 1763/// 1764void Parser::ParseEnumBody(SourceLocation StartLoc, DeclPtrTy EnumDecl) { 1765 // Enter the scope of the enum body and start the definition. 1766 ParseScope EnumScope(this, Scope::DeclScope); 1767 Actions.ActOnTagStartDefinition(CurScope, EnumDecl); 1768 1769 SourceLocation LBraceLoc = ConsumeBrace(); 1770 1771 // C does not allow an empty enumerator-list, C++ does [dcl.enum]. 1772 if (Tok.is(tok::r_brace) && !getLang().CPlusPlus) 1773 Diag(Tok, diag::ext_empty_struct_union_enum) << "enum"; 1774 1775 llvm::SmallVector<DeclPtrTy, 32> EnumConstantDecls; 1776 1777 DeclPtrTy LastEnumConstDecl; 1778 1779 // Parse the enumerator-list. 1780 while (Tok.is(tok::identifier)) { 1781 IdentifierInfo *Ident = Tok.getIdentifierInfo(); 1782 SourceLocation IdentLoc = ConsumeToken(); 1783 1784 SourceLocation EqualLoc; 1785 OwningExprResult AssignedVal(Actions); 1786 if (Tok.is(tok::equal)) { 1787 EqualLoc = ConsumeToken(); 1788 AssignedVal = ParseConstantExpression(); 1789 if (AssignedVal.isInvalid()) 1790 SkipUntil(tok::comma, tok::r_brace, true, true); 1791 } 1792 1793 // Install the enumerator constant into EnumDecl. 1794 DeclPtrTy EnumConstDecl = Actions.ActOnEnumConstant(CurScope, EnumDecl, 1795 LastEnumConstDecl, 1796 IdentLoc, Ident, 1797 EqualLoc, 1798 AssignedVal.release()); 1799 EnumConstantDecls.push_back(EnumConstDecl); 1800 LastEnumConstDecl = EnumConstDecl; 1801 1802 if (Tok.isNot(tok::comma)) 1803 break; 1804 SourceLocation CommaLoc = ConsumeToken(); 1805 1806 if (Tok.isNot(tok::identifier) && 1807 !(getLang().C99 || getLang().CPlusPlus0x)) 1808 Diag(CommaLoc, diag::ext_enumerator_list_comma) 1809 << getLang().CPlusPlus 1810 << CodeModificationHint::CreateRemoval((SourceRange(CommaLoc))); 1811 } 1812 1813 // Eat the }. 1814 SourceLocation RBraceLoc = MatchRHSPunctuation(tok::r_brace, LBraceLoc); 1815 1816 AttributeList *Attr = 0; 1817 // If attributes exist after the identifier list, parse them. 1818 if (Tok.is(tok::kw___attribute)) 1819 Attr = ParseAttributes(); 1820 1821 Actions.ActOnEnumBody(StartLoc, LBraceLoc, RBraceLoc, EnumDecl, 1822 EnumConstantDecls.data(), EnumConstantDecls.size(), 1823 CurScope, Attr); 1824 1825 EnumScope.Exit(); 1826 Actions.ActOnTagFinishDefinition(CurScope, EnumDecl, RBraceLoc); 1827} 1828 1829/// isTypeSpecifierQualifier - Return true if the current token could be the 1830/// start of a type-qualifier-list. 1831bool Parser::isTypeQualifier() const { 1832 switch (Tok.getKind()) { 1833 default: return false; 1834 // type-qualifier 1835 case tok::kw_const: 1836 case tok::kw_volatile: 1837 case tok::kw_restrict: 1838 return true; 1839 } 1840} 1841 1842/// isTypeSpecifierQualifier - Return true if the current token could be the 1843/// start of a specifier-qualifier-list. 1844bool Parser::isTypeSpecifierQualifier() { 1845 switch (Tok.getKind()) { 1846 default: return false; 1847 1848 case tok::identifier: // foo::bar 1849 case tok::kw_typename: // typename T::type 1850 // Annotate typenames and C++ scope specifiers. If we get one, just 1851 // recurse to handle whatever we get. 1852 if (TryAnnotateTypeOrScopeToken()) 1853 return isTypeSpecifierQualifier(); 1854 // Otherwise, not a type specifier. 1855 return false; 1856 1857 case tok::coloncolon: // ::foo::bar 1858 if (NextToken().is(tok::kw_new) || // ::new 1859 NextToken().is(tok::kw_delete)) // ::delete 1860 return false; 1861 1862 // Annotate typenames and C++ scope specifiers. If we get one, just 1863 // recurse to handle whatever we get. 1864 if (TryAnnotateTypeOrScopeToken()) 1865 return isTypeSpecifierQualifier(); 1866 // Otherwise, not a type specifier. 1867 return false; 1868 1869 // GNU attributes support. 1870 case tok::kw___attribute: 1871 // GNU typeof support. 1872 case tok::kw_typeof: 1873 1874 // type-specifiers 1875 case tok::kw_short: 1876 case tok::kw_long: 1877 case tok::kw_signed: 1878 case tok::kw_unsigned: 1879 case tok::kw__Complex: 1880 case tok::kw__Imaginary: 1881 case tok::kw_void: 1882 case tok::kw_char: 1883 case tok::kw_wchar_t: 1884 case tok::kw_char16_t: 1885 case tok::kw_char32_t: 1886 case tok::kw_int: 1887 case tok::kw_float: 1888 case tok::kw_double: 1889 case tok::kw_bool: 1890 case tok::kw__Bool: 1891 case tok::kw__Decimal32: 1892 case tok::kw__Decimal64: 1893 case tok::kw__Decimal128: 1894 1895 // struct-or-union-specifier (C99) or class-specifier (C++) 1896 case tok::kw_class: 1897 case tok::kw_struct: 1898 case tok::kw_union: 1899 // enum-specifier 1900 case tok::kw_enum: 1901 1902 // type-qualifier 1903 case tok::kw_const: 1904 case tok::kw_volatile: 1905 case tok::kw_restrict: 1906 1907 // typedef-name 1908 case tok::annot_typename: 1909 return true; 1910 1911 // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'. 1912 case tok::less: 1913 return getLang().ObjC1; 1914 1915 case tok::kw___cdecl: 1916 case tok::kw___stdcall: 1917 case tok::kw___fastcall: 1918 case tok::kw___w64: 1919 case tok::kw___ptr64: 1920 return true; 1921 } 1922} 1923 1924/// isDeclarationSpecifier() - Return true if the current token is part of a 1925/// declaration specifier. 1926bool Parser::isDeclarationSpecifier() { 1927 switch (Tok.getKind()) { 1928 default: return false; 1929 1930 case tok::identifier: // foo::bar 1931 // Unfortunate hack to support "Class.factoryMethod" notation. 1932 if (getLang().ObjC1 && NextToken().is(tok::period)) 1933 return false; 1934 // Fall through 1935 1936 case tok::kw_typename: // typename T::type 1937 // Annotate typenames and C++ scope specifiers. If we get one, just 1938 // recurse to handle whatever we get. 1939 if (TryAnnotateTypeOrScopeToken()) 1940 return isDeclarationSpecifier(); 1941 // Otherwise, not a declaration specifier. 1942 return false; 1943 case tok::coloncolon: // ::foo::bar 1944 if (NextToken().is(tok::kw_new) || // ::new 1945 NextToken().is(tok::kw_delete)) // ::delete 1946 return false; 1947 1948 // Annotate typenames and C++ scope specifiers. If we get one, just 1949 // recurse to handle whatever we get. 1950 if (TryAnnotateTypeOrScopeToken()) 1951 return isDeclarationSpecifier(); 1952 // Otherwise, not a declaration specifier. 1953 return false; 1954 1955 // storage-class-specifier 1956 case tok::kw_typedef: 1957 case tok::kw_extern: 1958 case tok::kw___private_extern__: 1959 case tok::kw_static: 1960 case tok::kw_auto: 1961 case tok::kw_register: 1962 case tok::kw___thread: 1963 1964 // type-specifiers 1965 case tok::kw_short: 1966 case tok::kw_long: 1967 case tok::kw_signed: 1968 case tok::kw_unsigned: 1969 case tok::kw__Complex: 1970 case tok::kw__Imaginary: 1971 case tok::kw_void: 1972 case tok::kw_char: 1973 case tok::kw_wchar_t: 1974 case tok::kw_char16_t: 1975 case tok::kw_char32_t: 1976 1977 case tok::kw_int: 1978 case tok::kw_float: 1979 case tok::kw_double: 1980 case tok::kw_bool: 1981 case tok::kw__Bool: 1982 case tok::kw__Decimal32: 1983 case tok::kw__Decimal64: 1984 case tok::kw__Decimal128: 1985 1986 // struct-or-union-specifier (C99) or class-specifier (C++) 1987 case tok::kw_class: 1988 case tok::kw_struct: 1989 case tok::kw_union: 1990 // enum-specifier 1991 case tok::kw_enum: 1992 1993 // type-qualifier 1994 case tok::kw_const: 1995 case tok::kw_volatile: 1996 case tok::kw_restrict: 1997 1998 // function-specifier 1999 case tok::kw_inline: 2000 case tok::kw_virtual: 2001 case tok::kw_explicit: 2002 2003 // typedef-name 2004 case tok::annot_typename: 2005 2006 // GNU typeof support. 2007 case tok::kw_typeof: 2008 2009 // GNU attributes. 2010 case tok::kw___attribute: 2011 return true; 2012 2013 // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'. 2014 case tok::less: 2015 return getLang().ObjC1; 2016 2017 case tok::kw___declspec: 2018 case tok::kw___cdecl: 2019 case tok::kw___stdcall: 2020 case tok::kw___fastcall: 2021 case tok::kw___w64: 2022 case tok::kw___ptr64: 2023 case tok::kw___forceinline: 2024 return true; 2025 } 2026} 2027 2028 2029/// ParseTypeQualifierListOpt 2030/// type-qualifier-list: [C99 6.7.5] 2031/// type-qualifier 2032/// [GNU] attributes [ only if AttributesAllowed=true ] 2033/// type-qualifier-list type-qualifier 2034/// [GNU] type-qualifier-list attributes [ only if AttributesAllowed=true ] 2035/// 2036void Parser::ParseTypeQualifierListOpt(DeclSpec &DS, bool AttributesAllowed) { 2037 while (1) { 2038 bool isInvalid = false; 2039 const char *PrevSpec = 0; 2040 unsigned DiagID = 0; 2041 SourceLocation Loc = Tok.getLocation(); 2042 2043 switch (Tok.getKind()) { 2044 case tok::kw_const: 2045 isInvalid = DS.SetTypeQual(DeclSpec::TQ_const , Loc, PrevSpec, DiagID, 2046 getLang()); 2047 break; 2048 case tok::kw_volatile: 2049 isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, DiagID, 2050 getLang()); 2051 break; 2052 case tok::kw_restrict: 2053 isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, DiagID, 2054 getLang()); 2055 break; 2056 case tok::kw___w64: 2057 case tok::kw___ptr64: 2058 case tok::kw___cdecl: 2059 case tok::kw___stdcall: 2060 case tok::kw___fastcall: 2061 if (AttributesAllowed) { 2062 DS.AddAttributes(ParseMicrosoftTypeAttributes()); 2063 continue; 2064 } 2065 goto DoneWithTypeQuals; 2066 case tok::kw___attribute: 2067 if (AttributesAllowed) { 2068 DS.AddAttributes(ParseAttributes()); 2069 continue; // do *not* consume the next token! 2070 } 2071 // otherwise, FALL THROUGH! 2072 default: 2073 DoneWithTypeQuals: 2074 // If this is not a type-qualifier token, we're done reading type 2075 // qualifiers. First verify that DeclSpec's are consistent. 2076 DS.Finish(Diags, PP); 2077 return; 2078 } 2079 2080 // If the specifier combination wasn't legal, issue a diagnostic. 2081 if (isInvalid) { 2082 assert(PrevSpec && "Method did not return previous specifier!"); 2083 Diag(Tok, DiagID) << PrevSpec; 2084 } 2085 ConsumeToken(); 2086 } 2087} 2088 2089 2090/// ParseDeclarator - Parse and verify a newly-initialized declarator. 2091/// 2092void Parser::ParseDeclarator(Declarator &D) { 2093 /// This implements the 'declarator' production in the C grammar, then checks 2094 /// for well-formedness and issues diagnostics. 2095 ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator); 2096} 2097 2098/// ParseDeclaratorInternal - Parse a C or C++ declarator. The direct-declarator 2099/// is parsed by the function passed to it. Pass null, and the direct-declarator 2100/// isn't parsed at all, making this function effectively parse the C++ 2101/// ptr-operator production. 2102/// 2103/// declarator: [C99 6.7.5] [C++ 8p4, dcl.decl] 2104/// [C] pointer[opt] direct-declarator 2105/// [C++] direct-declarator 2106/// [C++] ptr-operator declarator 2107/// 2108/// pointer: [C99 6.7.5] 2109/// '*' type-qualifier-list[opt] 2110/// '*' type-qualifier-list[opt] pointer 2111/// 2112/// ptr-operator: 2113/// '*' cv-qualifier-seq[opt] 2114/// '&' 2115/// [C++0x] '&&' 2116/// [GNU] '&' restrict[opt] attributes[opt] 2117/// [GNU?] '&&' restrict[opt] attributes[opt] 2118/// '::'[opt] nested-name-specifier '*' cv-qualifier-seq[opt] 2119void Parser::ParseDeclaratorInternal(Declarator &D, 2120 DirectDeclParseFunction DirectDeclParser) { 2121 2122 if (Diags.hasAllExtensionsSilenced()) 2123 D.setExtension(); 2124 // C++ member pointers start with a '::' or a nested-name. 2125 // Member pointers get special handling, since there's no place for the 2126 // scope spec in the generic path below. 2127 if (getLang().CPlusPlus && 2128 (Tok.is(tok::coloncolon) || Tok.is(tok::identifier) || 2129 Tok.is(tok::annot_cxxscope))) { 2130 CXXScopeSpec SS; 2131 if (ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/0, true)) { 2132 if (Tok.isNot(tok::star)) { 2133 // The scope spec really belongs to the direct-declarator. 2134 D.getCXXScopeSpec() = SS; 2135 if (DirectDeclParser) 2136 (this->*DirectDeclParser)(D); 2137 return; 2138 } 2139 2140 SourceLocation Loc = ConsumeToken(); 2141 D.SetRangeEnd(Loc); 2142 DeclSpec DS; 2143 ParseTypeQualifierListOpt(DS); 2144 D.ExtendWithDeclSpec(DS); 2145 2146 // Recurse to parse whatever is left. 2147 ParseDeclaratorInternal(D, DirectDeclParser); 2148 2149 // Sema will have to catch (syntactically invalid) pointers into global 2150 // scope. It has to catch pointers into namespace scope anyway. 2151 D.AddTypeInfo(DeclaratorChunk::getMemberPointer(SS,DS.getTypeQualifiers(), 2152 Loc, DS.TakeAttributes()), 2153 /* Don't replace range end. */SourceLocation()); 2154 return; 2155 } 2156 } 2157 2158 tok::TokenKind Kind = Tok.getKind(); 2159 // Not a pointer, C++ reference, or block. 2160 if (Kind != tok::star && Kind != tok::caret && 2161 (Kind != tok::amp || !getLang().CPlusPlus) && 2162 // We parse rvalue refs in C++03, because otherwise the errors are scary. 2163 (Kind != tok::ampamp || !getLang().CPlusPlus)) { 2164 if (DirectDeclParser) 2165 (this->*DirectDeclParser)(D); 2166 return; 2167 } 2168 2169 // Otherwise, '*' -> pointer, '^' -> block, '&' -> lvalue reference, 2170 // '&&' -> rvalue reference 2171 SourceLocation Loc = ConsumeToken(); // Eat the *, ^, & or &&. 2172 D.SetRangeEnd(Loc); 2173 2174 if (Kind == tok::star || Kind == tok::caret) { 2175 // Is a pointer. 2176 DeclSpec DS; 2177 2178 ParseTypeQualifierListOpt(DS); 2179 D.ExtendWithDeclSpec(DS); 2180 2181 // Recursively parse the declarator. 2182 ParseDeclaratorInternal(D, DirectDeclParser); 2183 if (Kind == tok::star) 2184 // Remember that we parsed a pointer type, and remember the type-quals. 2185 D.AddTypeInfo(DeclaratorChunk::getPointer(DS.getTypeQualifiers(), Loc, 2186 DS.TakeAttributes()), 2187 SourceLocation()); 2188 else 2189 // Remember that we parsed a Block type, and remember the type-quals. 2190 D.AddTypeInfo(DeclaratorChunk::getBlockPointer(DS.getTypeQualifiers(), 2191 Loc, DS.TakeAttributes()), 2192 SourceLocation()); 2193 } else { 2194 // Is a reference 2195 DeclSpec DS; 2196 2197 // Complain about rvalue references in C++03, but then go on and build 2198 // the declarator. 2199 if (Kind == tok::ampamp && !getLang().CPlusPlus0x) 2200 Diag(Loc, diag::err_rvalue_reference); 2201 2202 // C++ 8.3.2p1: cv-qualified references are ill-formed except when the 2203 // cv-qualifiers are introduced through the use of a typedef or of a 2204 // template type argument, in which case the cv-qualifiers are ignored. 2205 // 2206 // [GNU] Retricted references are allowed. 2207 // [GNU] Attributes on references are allowed. 2208 ParseTypeQualifierListOpt(DS); 2209 D.ExtendWithDeclSpec(DS); 2210 2211 if (DS.getTypeQualifiers() != DeclSpec::TQ_unspecified) { 2212 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 2213 Diag(DS.getConstSpecLoc(), 2214 diag::err_invalid_reference_qualifier_application) << "const"; 2215 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 2216 Diag(DS.getVolatileSpecLoc(), 2217 diag::err_invalid_reference_qualifier_application) << "volatile"; 2218 } 2219 2220 // Recursively parse the declarator. 2221 ParseDeclaratorInternal(D, DirectDeclParser); 2222 2223 if (D.getNumTypeObjects() > 0) { 2224 // C++ [dcl.ref]p4: There shall be no references to references. 2225 DeclaratorChunk& InnerChunk = D.getTypeObject(D.getNumTypeObjects() - 1); 2226 if (InnerChunk.Kind == DeclaratorChunk::Reference) { 2227 if (const IdentifierInfo *II = D.getIdentifier()) 2228 Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference) 2229 << II; 2230 else 2231 Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference) 2232 << "type name"; 2233 2234 // Once we've complained about the reference-to-reference, we 2235 // can go ahead and build the (technically ill-formed) 2236 // declarator: reference collapsing will take care of it. 2237 } 2238 } 2239 2240 // Remember that we parsed a reference type. It doesn't have type-quals. 2241 D.AddTypeInfo(DeclaratorChunk::getReference(DS.getTypeQualifiers(), Loc, 2242 DS.TakeAttributes(), 2243 Kind == tok::amp), 2244 SourceLocation()); 2245 } 2246} 2247 2248/// ParseDirectDeclarator 2249/// direct-declarator: [C99 6.7.5] 2250/// [C99] identifier 2251/// '(' declarator ')' 2252/// [GNU] '(' attributes declarator ')' 2253/// [C90] direct-declarator '[' constant-expression[opt] ']' 2254/// [C99] direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']' 2255/// [C99] direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']' 2256/// [C99] direct-declarator '[' type-qual-list 'static' assignment-expr ']' 2257/// [C99] direct-declarator '[' type-qual-list[opt] '*' ']' 2258/// direct-declarator '(' parameter-type-list ')' 2259/// direct-declarator '(' identifier-list[opt] ')' 2260/// [GNU] direct-declarator '(' parameter-forward-declarations 2261/// parameter-type-list[opt] ')' 2262/// [C++] direct-declarator '(' parameter-declaration-clause ')' 2263/// cv-qualifier-seq[opt] exception-specification[opt] 2264/// [C++] declarator-id 2265/// 2266/// declarator-id: [C++ 8] 2267/// id-expression 2268/// '::'[opt] nested-name-specifier[opt] type-name 2269/// 2270/// id-expression: [C++ 5.1] 2271/// unqualified-id 2272/// qualified-id 2273/// 2274/// unqualified-id: [C++ 5.1] 2275/// identifier 2276/// operator-function-id 2277/// conversion-function-id 2278/// '~' class-name 2279/// template-id 2280/// 2281void Parser::ParseDirectDeclarator(Declarator &D) { 2282 DeclaratorScopeObj DeclScopeObj(*this, D.getCXXScopeSpec()); 2283 2284 if (getLang().CPlusPlus && D.mayHaveIdentifier()) { 2285 // ParseDeclaratorInternal might already have parsed the scope. 2286 bool afterCXXScope = D.getCXXScopeSpec().isSet() || 2287 ParseOptionalCXXScopeSpecifier(D.getCXXScopeSpec(), /*ObjectType=*/0, 2288 true); 2289 if (afterCXXScope) { 2290 // Change the declaration context for name lookup, until this function 2291 // is exited (and the declarator has been parsed). 2292 DeclScopeObj.EnterDeclaratorScope(); 2293 } 2294 2295 if (Tok.is(tok::identifier) || Tok.is(tok::kw_operator) || 2296 Tok.is(tok::annot_template_id) || Tok.is(tok::tilde)) { 2297 // We found something that indicates the start of an unqualified-id. 2298 // Parse that unqualified-id. 2299 if (ParseUnqualifiedId(D.getCXXScopeSpec(), 2300 /*EnteringContext=*/true, 2301 /*AllowDestructorName=*/true, 2302 /*AllowConstructorName=*/!D.getDeclSpec().hasTypeSpecifier(), 2303 D.getName())) { 2304 D.SetIdentifier(0, Tok.getLocation()); 2305 D.setInvalidType(true); 2306 } else { 2307 // Parsed the unqualified-id; update range information and move along. 2308 if (D.getSourceRange().getBegin().isInvalid()) 2309 D.SetRangeBegin(D.getName().getSourceRange().getBegin()); 2310 D.SetRangeEnd(D.getName().getSourceRange().getEnd()); 2311 } 2312 goto PastIdentifier; 2313 } 2314 } else if (Tok.is(tok::identifier) && D.mayHaveIdentifier()) { 2315 assert(!getLang().CPlusPlus && 2316 "There's a C++-specific check for tok::identifier above"); 2317 assert(Tok.getIdentifierInfo() && "Not an identifier?"); 2318 D.SetIdentifier(Tok.getIdentifierInfo(), Tok.getLocation()); 2319 ConsumeToken(); 2320 goto PastIdentifier; 2321 } 2322 2323 if (Tok.is(tok::l_paren)) { 2324 // direct-declarator: '(' declarator ')' 2325 // direct-declarator: '(' attributes declarator ')' 2326 // Example: 'char (*X)' or 'int (*XX)(void)' 2327 ParseParenDeclarator(D); 2328 } else if (D.mayOmitIdentifier()) { 2329 // This could be something simple like "int" (in which case the declarator 2330 // portion is empty), if an abstract-declarator is allowed. 2331 D.SetIdentifier(0, Tok.getLocation()); 2332 } else { 2333 if (D.getContext() == Declarator::MemberContext) 2334 Diag(Tok, diag::err_expected_member_name_or_semi) 2335 << D.getDeclSpec().getSourceRange(); 2336 else if (getLang().CPlusPlus) 2337 Diag(Tok, diag::err_expected_unqualified_id); 2338 else 2339 Diag(Tok, diag::err_expected_ident_lparen); 2340 D.SetIdentifier(0, Tok.getLocation()); 2341 D.setInvalidType(true); 2342 } 2343 2344 PastIdentifier: 2345 assert(D.isPastIdentifier() && 2346 "Haven't past the location of the identifier yet?"); 2347 2348 while (1) { 2349 if (Tok.is(tok::l_paren)) { 2350 // The paren may be part of a C++ direct initializer, eg. "int x(1);". 2351 // In such a case, check if we actually have a function declarator; if it 2352 // is not, the declarator has been fully parsed. 2353 if (getLang().CPlusPlus && D.mayBeFollowedByCXXDirectInit()) { 2354 // When not in file scope, warn for ambiguous function declarators, just 2355 // in case the author intended it as a variable definition. 2356 bool warnIfAmbiguous = D.getContext() != Declarator::FileContext; 2357 if (!isCXXFunctionDeclarator(warnIfAmbiguous)) 2358 break; 2359 } 2360 ParseFunctionDeclarator(ConsumeParen(), D); 2361 } else if (Tok.is(tok::l_square)) { 2362 ParseBracketDeclarator(D); 2363 } else { 2364 break; 2365 } 2366 } 2367} 2368 2369/// ParseParenDeclarator - We parsed the declarator D up to a paren. This is 2370/// only called before the identifier, so these are most likely just grouping 2371/// parens for precedence. If we find that these are actually function 2372/// parameter parens in an abstract-declarator, we call ParseFunctionDeclarator. 2373/// 2374/// direct-declarator: 2375/// '(' declarator ')' 2376/// [GNU] '(' attributes declarator ')' 2377/// direct-declarator '(' parameter-type-list ')' 2378/// direct-declarator '(' identifier-list[opt] ')' 2379/// [GNU] direct-declarator '(' parameter-forward-declarations 2380/// parameter-type-list[opt] ')' 2381/// 2382void Parser::ParseParenDeclarator(Declarator &D) { 2383 SourceLocation StartLoc = ConsumeParen(); 2384 assert(!D.isPastIdentifier() && "Should be called before passing identifier"); 2385 2386 // Eat any attributes before we look at whether this is a grouping or function 2387 // declarator paren. If this is a grouping paren, the attribute applies to 2388 // the type being built up, for example: 2389 // int (__attribute__(()) *x)(long y) 2390 // If this ends up not being a grouping paren, the attribute applies to the 2391 // first argument, for example: 2392 // int (__attribute__(()) int x) 2393 // In either case, we need to eat any attributes to be able to determine what 2394 // sort of paren this is. 2395 // 2396 AttributeList *AttrList = 0; 2397 bool RequiresArg = false; 2398 if (Tok.is(tok::kw___attribute)) { 2399 AttrList = ParseAttributes(); 2400 2401 // We require that the argument list (if this is a non-grouping paren) be 2402 // present even if the attribute list was empty. 2403 RequiresArg = true; 2404 } 2405 // Eat any Microsoft extensions. 2406 if (Tok.is(tok::kw___cdecl) || Tok.is(tok::kw___stdcall) || 2407 Tok.is(tok::kw___fastcall) || Tok.is(tok::kw___w64) || 2408 Tok.is(tok::kw___ptr64)) { 2409 AttrList = ParseMicrosoftTypeAttributes(AttrList); 2410 } 2411 2412 // If we haven't past the identifier yet (or where the identifier would be 2413 // stored, if this is an abstract declarator), then this is probably just 2414 // grouping parens. However, if this could be an abstract-declarator, then 2415 // this could also be the start of function arguments (consider 'void()'). 2416 bool isGrouping; 2417 2418 if (!D.mayOmitIdentifier()) { 2419 // If this can't be an abstract-declarator, this *must* be a grouping 2420 // paren, because we haven't seen the identifier yet. 2421 isGrouping = true; 2422 } else if (Tok.is(tok::r_paren) || // 'int()' is a function. 2423 (getLang().CPlusPlus && Tok.is(tok::ellipsis)) || // C++ int(...) 2424 isDeclarationSpecifier()) { // 'int(int)' is a function. 2425 // This handles C99 6.7.5.3p11: in "typedef int X; void foo(X)", X is 2426 // considered to be a type, not a K&R identifier-list. 2427 isGrouping = false; 2428 } else { 2429 // Otherwise, this is a grouping paren, e.g. 'int (*X)' or 'int(X)'. 2430 isGrouping = true; 2431 } 2432 2433 // If this is a grouping paren, handle: 2434 // direct-declarator: '(' declarator ')' 2435 // direct-declarator: '(' attributes declarator ')' 2436 if (isGrouping) { 2437 bool hadGroupingParens = D.hasGroupingParens(); 2438 D.setGroupingParens(true); 2439 if (AttrList) 2440 D.AddAttributes(AttrList, SourceLocation()); 2441 2442 ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator); 2443 // Match the ')'. 2444 SourceLocation Loc = MatchRHSPunctuation(tok::r_paren, StartLoc); 2445 2446 D.setGroupingParens(hadGroupingParens); 2447 D.SetRangeEnd(Loc); 2448 return; 2449 } 2450 2451 // Okay, if this wasn't a grouping paren, it must be the start of a function 2452 // argument list. Recognize that this declarator will never have an 2453 // identifier (and remember where it would have been), then call into 2454 // ParseFunctionDeclarator to handle of argument list. 2455 D.SetIdentifier(0, Tok.getLocation()); 2456 2457 ParseFunctionDeclarator(StartLoc, D, AttrList, RequiresArg); 2458} 2459 2460/// ParseFunctionDeclarator - We are after the identifier and have parsed the 2461/// declarator D up to a paren, which indicates that we are parsing function 2462/// arguments. 2463/// 2464/// If AttrList is non-null, then the caller parsed those arguments immediately 2465/// after the open paren - they should be considered to be the first argument of 2466/// a parameter. If RequiresArg is true, then the first argument of the 2467/// function is required to be present and required to not be an identifier 2468/// list. 2469/// 2470/// This method also handles this portion of the grammar: 2471/// parameter-type-list: [C99 6.7.5] 2472/// parameter-list 2473/// parameter-list ',' '...' 2474/// [C++] parameter-list '...' 2475/// 2476/// parameter-list: [C99 6.7.5] 2477/// parameter-declaration 2478/// parameter-list ',' parameter-declaration 2479/// 2480/// parameter-declaration: [C99 6.7.5] 2481/// declaration-specifiers declarator 2482/// [C++] declaration-specifiers declarator '=' assignment-expression 2483/// [GNU] declaration-specifiers declarator attributes 2484/// declaration-specifiers abstract-declarator[opt] 2485/// [C++] declaration-specifiers abstract-declarator[opt] 2486/// '=' assignment-expression 2487/// [GNU] declaration-specifiers abstract-declarator[opt] attributes 2488/// 2489/// For C++, after the parameter-list, it also parses "cv-qualifier-seq[opt]" 2490/// and "exception-specification[opt]". 2491/// 2492void Parser::ParseFunctionDeclarator(SourceLocation LParenLoc, Declarator &D, 2493 AttributeList *AttrList, 2494 bool RequiresArg) { 2495 // lparen is already consumed! 2496 assert(D.isPastIdentifier() && "Should not call before identifier!"); 2497 2498 // This parameter list may be empty. 2499 if (Tok.is(tok::r_paren)) { 2500 if (RequiresArg) { 2501 Diag(Tok, diag::err_argument_required_after_attribute); 2502 delete AttrList; 2503 } 2504 2505 SourceLocation RParenLoc = ConsumeParen(); // Eat the closing ')'. 2506 SourceLocation EndLoc = RParenLoc; 2507 2508 // cv-qualifier-seq[opt]. 2509 DeclSpec DS; 2510 bool hasExceptionSpec = false; 2511 SourceLocation ThrowLoc; 2512 bool hasAnyExceptionSpec = false; 2513 llvm::SmallVector<TypeTy*, 2> Exceptions; 2514 llvm::SmallVector<SourceRange, 2> ExceptionRanges; 2515 if (getLang().CPlusPlus) { 2516 ParseTypeQualifierListOpt(DS, false /*no attributes*/); 2517 if (!DS.getSourceRange().getEnd().isInvalid()) 2518 EndLoc = DS.getSourceRange().getEnd(); 2519 2520 // Parse exception-specification[opt]. 2521 if (Tok.is(tok::kw_throw)) { 2522 hasExceptionSpec = true; 2523 ThrowLoc = Tok.getLocation(); 2524 ParseExceptionSpecification(EndLoc, Exceptions, ExceptionRanges, 2525 hasAnyExceptionSpec); 2526 assert(Exceptions.size() == ExceptionRanges.size() && 2527 "Produced different number of exception types and ranges."); 2528 } 2529 } 2530 2531 // Remember that we parsed a function type, and remember the attributes. 2532 // int() -> no prototype, no '...'. 2533 D.AddTypeInfo(DeclaratorChunk::getFunction(/*prototype*/getLang().CPlusPlus, 2534 /*variadic*/ false, 2535 SourceLocation(), 2536 /*arglist*/ 0, 0, 2537 DS.getTypeQualifiers(), 2538 hasExceptionSpec, ThrowLoc, 2539 hasAnyExceptionSpec, 2540 Exceptions.data(), 2541 ExceptionRanges.data(), 2542 Exceptions.size(), 2543 LParenLoc, RParenLoc, D), 2544 EndLoc); 2545 return; 2546 } 2547 2548 // Alternatively, this parameter list may be an identifier list form for a 2549 // K&R-style function: void foo(a,b,c) 2550 if (!getLang().CPlusPlus && Tok.is(tok::identifier)) { 2551 if (!TryAnnotateTypeOrScopeToken()) { 2552 // K&R identifier lists can't have typedefs as identifiers, per 2553 // C99 6.7.5.3p11. 2554 if (RequiresArg) { 2555 Diag(Tok, diag::err_argument_required_after_attribute); 2556 delete AttrList; 2557 } 2558 // Identifier list. Note that '(' identifier-list ')' is only allowed for 2559 // normal declarators, not for abstract-declarators. 2560 return ParseFunctionDeclaratorIdentifierList(LParenLoc, D); 2561 } 2562 } 2563 2564 // Finally, a normal, non-empty parameter type list. 2565 2566 // Build up an array of information about the parsed arguments. 2567 llvm::SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo; 2568 2569 // Enter function-declaration scope, limiting any declarators to the 2570 // function prototype scope, including parameter declarators. 2571 ParseScope PrototypeScope(this, 2572 Scope::FunctionPrototypeScope|Scope::DeclScope); 2573 2574 bool IsVariadic = false; 2575 SourceLocation EllipsisLoc; 2576 while (1) { 2577 if (Tok.is(tok::ellipsis)) { 2578 IsVariadic = true; 2579 EllipsisLoc = ConsumeToken(); // Consume the ellipsis. 2580 break; 2581 } 2582 2583 SourceLocation DSStart = Tok.getLocation(); 2584 2585 // Parse the declaration-specifiers. 2586 DeclSpec DS; 2587 2588 // If the caller parsed attributes for the first argument, add them now. 2589 if (AttrList) { 2590 DS.AddAttributes(AttrList); 2591 AttrList = 0; // Only apply the attributes to the first parameter. 2592 } 2593 ParseDeclarationSpecifiers(DS); 2594 2595 // Parse the declarator. This is "PrototypeContext", because we must 2596 // accept either 'declarator' or 'abstract-declarator' here. 2597 Declarator ParmDecl(DS, Declarator::PrototypeContext); 2598 ParseDeclarator(ParmDecl); 2599 2600 // Parse GNU attributes, if present. 2601 if (Tok.is(tok::kw___attribute)) { 2602 SourceLocation Loc; 2603 AttributeList *AttrList = ParseAttributes(&Loc); 2604 ParmDecl.AddAttributes(AttrList, Loc); 2605 } 2606 2607 // Remember this parsed parameter in ParamInfo. 2608 IdentifierInfo *ParmII = ParmDecl.getIdentifier(); 2609 2610 // DefArgToks is used when the parsing of default arguments needs 2611 // to be delayed. 2612 CachedTokens *DefArgToks = 0; 2613 2614 // If no parameter was specified, verify that *something* was specified, 2615 // otherwise we have a missing type and identifier. 2616 if (DS.isEmpty() && ParmDecl.getIdentifier() == 0 && 2617 ParmDecl.getNumTypeObjects() == 0) { 2618 // Completely missing, emit error. 2619 Diag(DSStart, diag::err_missing_param); 2620 } else { 2621 // Otherwise, we have something. Add it and let semantic analysis try 2622 // to grok it and add the result to the ParamInfo we are building. 2623 2624 // Inform the actions module about the parameter declarator, so it gets 2625 // added to the current scope. 2626 DeclPtrTy Param = Actions.ActOnParamDeclarator(CurScope, ParmDecl); 2627 2628 // Parse the default argument, if any. We parse the default 2629 // arguments in all dialects; the semantic analysis in 2630 // ActOnParamDefaultArgument will reject the default argument in 2631 // C. 2632 if (Tok.is(tok::equal)) { 2633 SourceLocation EqualLoc = Tok.getLocation(); 2634 2635 // Parse the default argument 2636 if (D.getContext() == Declarator::MemberContext) { 2637 // If we're inside a class definition, cache the tokens 2638 // corresponding to the default argument. We'll actually parse 2639 // them when we see the end of the class definition. 2640 // FIXME: Templates will require something similar. 2641 // FIXME: Can we use a smart pointer for Toks? 2642 DefArgToks = new CachedTokens; 2643 2644 if (!ConsumeAndStoreUntil(tok::comma, tok::r_paren, *DefArgToks, 2645 tok::semi, false)) { 2646 delete DefArgToks; 2647 DefArgToks = 0; 2648 Actions.ActOnParamDefaultArgumentError(Param); 2649 } else 2650 Actions.ActOnParamUnparsedDefaultArgument(Param, EqualLoc, 2651 (*DefArgToks)[1].getLocation()); 2652 } else { 2653 // Consume the '='. 2654 ConsumeToken(); 2655 2656 OwningExprResult DefArgResult(ParseAssignmentExpression()); 2657 if (DefArgResult.isInvalid()) { 2658 Actions.ActOnParamDefaultArgumentError(Param); 2659 SkipUntil(tok::comma, tok::r_paren, true, true); 2660 } else { 2661 // Inform the actions module about the default argument 2662 Actions.ActOnParamDefaultArgument(Param, EqualLoc, 2663 move(DefArgResult)); 2664 } 2665 } 2666 } 2667 2668 ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII, 2669 ParmDecl.getIdentifierLoc(), Param, 2670 DefArgToks)); 2671 } 2672 2673 // If the next token is a comma, consume it and keep reading arguments. 2674 if (Tok.isNot(tok::comma)) { 2675 if (Tok.is(tok::ellipsis)) { 2676 IsVariadic = true; 2677 EllipsisLoc = ConsumeToken(); // Consume the ellipsis. 2678 2679 if (!getLang().CPlusPlus) { 2680 // We have ellipsis without a preceding ',', which is ill-formed 2681 // in C. Complain and provide the fix. 2682 Diag(EllipsisLoc, diag::err_missing_comma_before_ellipsis) 2683 << CodeModificationHint::CreateInsertion(EllipsisLoc, ", "); 2684 } 2685 } 2686 2687 break; 2688 } 2689 2690 // Consume the comma. 2691 ConsumeToken(); 2692 } 2693 2694 // Leave prototype scope. 2695 PrototypeScope.Exit(); 2696 2697 // If we have the closing ')', eat it. 2698 SourceLocation RParenLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc); 2699 SourceLocation EndLoc = RParenLoc; 2700 2701 DeclSpec DS; 2702 bool hasExceptionSpec = false; 2703 SourceLocation ThrowLoc; 2704 bool hasAnyExceptionSpec = false; 2705 llvm::SmallVector<TypeTy*, 2> Exceptions; 2706 llvm::SmallVector<SourceRange, 2> ExceptionRanges; 2707 if (getLang().CPlusPlus) { 2708 // Parse cv-qualifier-seq[opt]. 2709 ParseTypeQualifierListOpt(DS, false /*no attributes*/); 2710 if (!DS.getSourceRange().getEnd().isInvalid()) 2711 EndLoc = DS.getSourceRange().getEnd(); 2712 2713 // Parse exception-specification[opt]. 2714 if (Tok.is(tok::kw_throw)) { 2715 hasExceptionSpec = true; 2716 ThrowLoc = Tok.getLocation(); 2717 ParseExceptionSpecification(EndLoc, Exceptions, ExceptionRanges, 2718 hasAnyExceptionSpec); 2719 assert(Exceptions.size() == ExceptionRanges.size() && 2720 "Produced different number of exception types and ranges."); 2721 } 2722 } 2723 2724 // Remember that we parsed a function type, and remember the attributes. 2725 D.AddTypeInfo(DeclaratorChunk::getFunction(/*proto*/true, IsVariadic, 2726 EllipsisLoc, 2727 ParamInfo.data(), ParamInfo.size(), 2728 DS.getTypeQualifiers(), 2729 hasExceptionSpec, ThrowLoc, 2730 hasAnyExceptionSpec, 2731 Exceptions.data(), 2732 ExceptionRanges.data(), 2733 Exceptions.size(), 2734 LParenLoc, RParenLoc, D), 2735 EndLoc); 2736} 2737 2738/// ParseFunctionDeclaratorIdentifierList - While parsing a function declarator 2739/// we found a K&R-style identifier list instead of a type argument list. The 2740/// current token is known to be the first identifier in the list. 2741/// 2742/// identifier-list: [C99 6.7.5] 2743/// identifier 2744/// identifier-list ',' identifier 2745/// 2746void Parser::ParseFunctionDeclaratorIdentifierList(SourceLocation LParenLoc, 2747 Declarator &D) { 2748 // Build up an array of information about the parsed arguments. 2749 llvm::SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo; 2750 llvm::SmallSet<const IdentifierInfo*, 16> ParamsSoFar; 2751 2752 // If there was no identifier specified for the declarator, either we are in 2753 // an abstract-declarator, or we are in a parameter declarator which was found 2754 // to be abstract. In abstract-declarators, identifier lists are not valid: 2755 // diagnose this. 2756 if (!D.getIdentifier()) 2757 Diag(Tok, diag::ext_ident_list_in_param); 2758 2759 // Tok is known to be the first identifier in the list. Remember this 2760 // identifier in ParamInfo. 2761 ParamsSoFar.insert(Tok.getIdentifierInfo()); 2762 ParamInfo.push_back(DeclaratorChunk::ParamInfo(Tok.getIdentifierInfo(), 2763 Tok.getLocation(), 2764 DeclPtrTy())); 2765 2766 ConsumeToken(); // eat the first identifier. 2767 2768 while (Tok.is(tok::comma)) { 2769 // Eat the comma. 2770 ConsumeToken(); 2771 2772 // If this isn't an identifier, report the error and skip until ')'. 2773 if (Tok.isNot(tok::identifier)) { 2774 Diag(Tok, diag::err_expected_ident); 2775 SkipUntil(tok::r_paren); 2776 return; 2777 } 2778 2779 IdentifierInfo *ParmII = Tok.getIdentifierInfo(); 2780 2781 // Reject 'typedef int y; int test(x, y)', but continue parsing. 2782 if (Actions.getTypeName(*ParmII, Tok.getLocation(), CurScope)) 2783 Diag(Tok, diag::err_unexpected_typedef_ident) << ParmII; 2784 2785 // Verify that the argument identifier has not already been mentioned. 2786 if (!ParamsSoFar.insert(ParmII)) { 2787 Diag(Tok, diag::err_param_redefinition) << ParmII; 2788 } else { 2789 // Remember this identifier in ParamInfo. 2790 ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII, 2791 Tok.getLocation(), 2792 DeclPtrTy())); 2793 } 2794 2795 // Eat the identifier. 2796 ConsumeToken(); 2797 } 2798 2799 // If we have the closing ')', eat it and we're done. 2800 SourceLocation RLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc); 2801 2802 // Remember that we parsed a function type, and remember the attributes. This 2803 // function type is always a K&R style function type, which is not varargs and 2804 // has no prototype. 2805 D.AddTypeInfo(DeclaratorChunk::getFunction(/*proto*/false, /*varargs*/false, 2806 SourceLocation(), 2807 &ParamInfo[0], ParamInfo.size(), 2808 /*TypeQuals*/0, 2809 /*exception*/false, 2810 SourceLocation(), false, 0, 0, 0, 2811 LParenLoc, RLoc, D), 2812 RLoc); 2813} 2814 2815/// [C90] direct-declarator '[' constant-expression[opt] ']' 2816/// [C99] direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']' 2817/// [C99] direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']' 2818/// [C99] direct-declarator '[' type-qual-list 'static' assignment-expr ']' 2819/// [C99] direct-declarator '[' type-qual-list[opt] '*' ']' 2820void Parser::ParseBracketDeclarator(Declarator &D) { 2821 SourceLocation StartLoc = ConsumeBracket(); 2822 2823 // C array syntax has many features, but by-far the most common is [] and [4]. 2824 // This code does a fast path to handle some of the most obvious cases. 2825 if (Tok.getKind() == tok::r_square) { 2826 SourceLocation EndLoc = MatchRHSPunctuation(tok::r_square, StartLoc); 2827 // Remember that we parsed the empty array type. 2828 OwningExprResult NumElements(Actions); 2829 D.AddTypeInfo(DeclaratorChunk::getArray(0, false, false, 0, 2830 StartLoc, EndLoc), 2831 EndLoc); 2832 return; 2833 } else if (Tok.getKind() == tok::numeric_constant && 2834 GetLookAheadToken(1).is(tok::r_square)) { 2835 // [4] is very common. Parse the numeric constant expression. 2836 OwningExprResult ExprRes(Actions.ActOnNumericConstant(Tok)); 2837 ConsumeToken(); 2838 2839 SourceLocation EndLoc = MatchRHSPunctuation(tok::r_square, StartLoc); 2840 2841 // If there was an error parsing the assignment-expression, recover. 2842 if (ExprRes.isInvalid()) 2843 ExprRes.release(); // Deallocate expr, just use []. 2844 2845 // Remember that we parsed a array type, and remember its features. 2846 D.AddTypeInfo(DeclaratorChunk::getArray(0, false, 0, ExprRes.release(), 2847 StartLoc, EndLoc), 2848 EndLoc); 2849 return; 2850 } 2851 2852 // If valid, this location is the position where we read the 'static' keyword. 2853 SourceLocation StaticLoc; 2854 if (Tok.is(tok::kw_static)) 2855 StaticLoc = ConsumeToken(); 2856 2857 // If there is a type-qualifier-list, read it now. 2858 // Type qualifiers in an array subscript are a C99 feature. 2859 DeclSpec DS; 2860 ParseTypeQualifierListOpt(DS, false /*no attributes*/); 2861 2862 // If we haven't already read 'static', check to see if there is one after the 2863 // type-qualifier-list. 2864 if (!StaticLoc.isValid() && Tok.is(tok::kw_static)) 2865 StaticLoc = ConsumeToken(); 2866 2867 // Handle "direct-declarator [ type-qual-list[opt] * ]". 2868 bool isStar = false; 2869 OwningExprResult NumElements(Actions); 2870 2871 // Handle the case where we have '[*]' as the array size. However, a leading 2872 // star could be the start of an expression, for example 'X[*p + 4]'. Verify 2873 // the the token after the star is a ']'. Since stars in arrays are 2874 // infrequent, use of lookahead is not costly here. 2875 if (Tok.is(tok::star) && GetLookAheadToken(1).is(tok::r_square)) { 2876 ConsumeToken(); // Eat the '*'. 2877 2878 if (StaticLoc.isValid()) { 2879 Diag(StaticLoc, diag::err_unspecified_vla_size_with_static); 2880 StaticLoc = SourceLocation(); // Drop the static. 2881 } 2882 isStar = true; 2883 } else if (Tok.isNot(tok::r_square)) { 2884 // Note, in C89, this production uses the constant-expr production instead 2885 // of assignment-expr. The only difference is that assignment-expr allows 2886 // things like '=' and '*='. Sema rejects these in C89 mode because they 2887 // are not i-c-e's, so we don't need to distinguish between the two here. 2888 2889 // Parse the constant-expression or assignment-expression now (depending 2890 // on dialect). 2891 if (getLang().CPlusPlus) 2892 NumElements = ParseConstantExpression(); 2893 else 2894 NumElements = ParseAssignmentExpression(); 2895 } 2896 2897 // If there was an error parsing the assignment-expression, recover. 2898 if (NumElements.isInvalid()) { 2899 D.setInvalidType(true); 2900 // If the expression was invalid, skip it. 2901 SkipUntil(tok::r_square); 2902 return; 2903 } 2904 2905 SourceLocation EndLoc = MatchRHSPunctuation(tok::r_square, StartLoc); 2906 2907 // Remember that we parsed a array type, and remember its features. 2908 D.AddTypeInfo(DeclaratorChunk::getArray(DS.getTypeQualifiers(), 2909 StaticLoc.isValid(), isStar, 2910 NumElements.release(), 2911 StartLoc, EndLoc), 2912 EndLoc); 2913} 2914 2915/// [GNU] typeof-specifier: 2916/// typeof ( expressions ) 2917/// typeof ( type-name ) 2918/// [GNU/C++] typeof unary-expression 2919/// 2920void Parser::ParseTypeofSpecifier(DeclSpec &DS) { 2921 assert(Tok.is(tok::kw_typeof) && "Not a typeof specifier"); 2922 Token OpTok = Tok; 2923 SourceLocation StartLoc = ConsumeToken(); 2924 2925 bool isCastExpr; 2926 TypeTy *CastTy; 2927 SourceRange CastRange; 2928 OwningExprResult Operand = ParseExprAfterTypeofSizeofAlignof(OpTok, 2929 isCastExpr, 2930 CastTy, 2931 CastRange); 2932 2933 if (CastRange.getEnd().isInvalid()) 2934 // FIXME: Not accurate, the range gets one token more than it should. 2935 DS.SetRangeEnd(Tok.getLocation()); 2936 else 2937 DS.SetRangeEnd(CastRange.getEnd()); 2938 2939 if (isCastExpr) { 2940 if (!CastTy) { 2941 DS.SetTypeSpecError(); 2942 return; 2943 } 2944 2945 const char *PrevSpec = 0; 2946 unsigned DiagID; 2947 // Check for duplicate type specifiers (e.g. "int typeof(int)"). 2948 if (DS.SetTypeSpecType(DeclSpec::TST_typeofType, StartLoc, PrevSpec, 2949 DiagID, CastTy)) 2950 Diag(StartLoc, DiagID) << PrevSpec; 2951 return; 2952 } 2953 2954 // If we get here, the operand to the typeof was an expresion. 2955 if (Operand.isInvalid()) { 2956 DS.SetTypeSpecError(); 2957 return; 2958 } 2959 2960 const char *PrevSpec = 0; 2961 unsigned DiagID; 2962 // Check for duplicate type specifiers (e.g. "int typeof(int)"). 2963 if (DS.SetTypeSpecType(DeclSpec::TST_typeofExpr, StartLoc, PrevSpec, 2964 DiagID, Operand.release())) 2965 Diag(StartLoc, DiagID) << PrevSpec; 2966} 2967