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