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