ParseDeclCXX.cpp revision b1f6fa48960eae269a3931d1fc545ed468d9a4d2
1//===--- ParseDeclCXX.cpp - C++ 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 C++ Declaration portions of the Parser interfaces. 11// 12//===----------------------------------------------------------------------===// 13 14#include "clang/Basic/OperatorKinds.h" 15#include "clang/Parse/Parser.h" 16#include "clang/Parse/ParseDiagnostic.h" 17#include "clang/Sema/DeclSpec.h" 18#include "clang/Sema/Scope.h" 19#include "clang/Sema/ParsedTemplate.h" 20#include "clang/Sema/PrettyDeclStackTrace.h" 21#include "RAIIObjectsForParser.h" 22using namespace clang; 23 24/// ParseNamespace - We know that the current token is a namespace keyword. This 25/// may either be a top level namespace or a block-level namespace alias. If 26/// there was an inline keyword, it has already been parsed. 27/// 28/// namespace-definition: [C++ 7.3: basic.namespace] 29/// named-namespace-definition 30/// unnamed-namespace-definition 31/// 32/// unnamed-namespace-definition: 33/// 'inline'[opt] 'namespace' attributes[opt] '{' namespace-body '}' 34/// 35/// named-namespace-definition: 36/// original-namespace-definition 37/// extension-namespace-definition 38/// 39/// original-namespace-definition: 40/// 'inline'[opt] 'namespace' identifier attributes[opt] 41/// '{' namespace-body '}' 42/// 43/// extension-namespace-definition: 44/// 'inline'[opt] 'namespace' original-namespace-name 45/// '{' namespace-body '}' 46/// 47/// namespace-alias-definition: [C++ 7.3.2: namespace.alias] 48/// 'namespace' identifier '=' qualified-namespace-specifier ';' 49/// 50Decl *Parser::ParseNamespace(unsigned Context, 51 SourceLocation &DeclEnd, 52 SourceLocation InlineLoc) { 53 assert(Tok.is(tok::kw_namespace) && "Not a namespace!"); 54 SourceLocation NamespaceLoc = ConsumeToken(); // eat the 'namespace'. 55 56 if (Tok.is(tok::code_completion)) { 57 Actions.CodeCompleteNamespaceDecl(getCurScope()); 58 ConsumeCodeCompletionToken(); 59 } 60 61 SourceLocation IdentLoc; 62 IdentifierInfo *Ident = 0; 63 64 Token attrTok; 65 66 if (Tok.is(tok::identifier)) { 67 Ident = Tok.getIdentifierInfo(); 68 IdentLoc = ConsumeToken(); // eat the identifier. 69 } 70 71 // Read label attributes, if present. 72 llvm::OwningPtr<AttributeList> AttrList; 73 if (Tok.is(tok::kw___attribute)) { 74 attrTok = Tok; 75 76 // FIXME: save these somewhere. 77 AttrList.reset(ParseGNUAttributes()); 78 } 79 80 if (Tok.is(tok::equal)) { 81 if (AttrList) 82 Diag(attrTok, diag::err_unexpected_namespace_attributes_alias); 83 if (InlineLoc.isValid()) 84 Diag(InlineLoc, diag::err_inline_namespace_alias) 85 << FixItHint::CreateRemoval(InlineLoc); 86 87 return ParseNamespaceAlias(NamespaceLoc, IdentLoc, Ident, DeclEnd); 88 } 89 90 if (Tok.isNot(tok::l_brace)) { 91 Diag(Tok, Ident ? diag::err_expected_lbrace : 92 diag::err_expected_ident_lbrace); 93 return 0; 94 } 95 96 SourceLocation LBrace = ConsumeBrace(); 97 98 if (getCurScope()->isClassScope() || getCurScope()->isTemplateParamScope() || 99 getCurScope()->isInObjcMethodScope() || getCurScope()->getBlockParent() || 100 getCurScope()->getFnParent()) { 101 Diag(LBrace, diag::err_namespace_nonnamespace_scope); 102 SkipUntil(tok::r_brace, false); 103 return 0; 104 } 105 106 // If we're still good, complain about inline namespaces in non-C++0x now. 107 if (!getLang().CPlusPlus0x && InlineLoc.isValid()) 108 Diag(InlineLoc, diag::ext_inline_namespace); 109 110 // Enter a scope for the namespace. 111 ParseScope NamespaceScope(this, Scope::DeclScope); 112 113 Decl *NamespcDecl = 114 Actions.ActOnStartNamespaceDef(getCurScope(), InlineLoc, IdentLoc, Ident, 115 LBrace, AttrList.get()); 116 117 PrettyDeclStackTraceEntry CrashInfo(Actions, NamespcDecl, NamespaceLoc, 118 "parsing namespace"); 119 120 while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) { 121 CXX0XAttributeList Attr; 122 if (getLang().CPlusPlus0x && isCXX0XAttributeSpecifier()) 123 Attr = ParseCXX0XAttributes(); 124 ParseExternalDeclaration(Attr); 125 } 126 127 // Leave the namespace scope. 128 NamespaceScope.Exit(); 129 130 SourceLocation RBraceLoc = MatchRHSPunctuation(tok::r_brace, LBrace); 131 Actions.ActOnFinishNamespaceDef(NamespcDecl, RBraceLoc); 132 133 DeclEnd = RBraceLoc; 134 return NamespcDecl; 135} 136 137/// ParseNamespaceAlias - Parse the part after the '=' in a namespace 138/// alias definition. 139/// 140Decl *Parser::ParseNamespaceAlias(SourceLocation NamespaceLoc, 141 SourceLocation AliasLoc, 142 IdentifierInfo *Alias, 143 SourceLocation &DeclEnd) { 144 assert(Tok.is(tok::equal) && "Not equal token"); 145 146 ConsumeToken(); // eat the '='. 147 148 if (Tok.is(tok::code_completion)) { 149 Actions.CodeCompleteNamespaceAliasDecl(getCurScope()); 150 ConsumeCodeCompletionToken(); 151 } 152 153 CXXScopeSpec SS; 154 // Parse (optional) nested-name-specifier. 155 ParseOptionalCXXScopeSpecifier(SS, ParsedType(), false); 156 157 if (SS.isInvalid() || Tok.isNot(tok::identifier)) { 158 Diag(Tok, diag::err_expected_namespace_name); 159 // Skip to end of the definition and eat the ';'. 160 SkipUntil(tok::semi); 161 return 0; 162 } 163 164 // Parse identifier. 165 IdentifierInfo *Ident = Tok.getIdentifierInfo(); 166 SourceLocation IdentLoc = ConsumeToken(); 167 168 // Eat the ';'. 169 DeclEnd = Tok.getLocation(); 170 ExpectAndConsume(tok::semi, diag::err_expected_semi_after_namespace_name, 171 "", tok::semi); 172 173 return Actions.ActOnNamespaceAliasDef(getCurScope(), NamespaceLoc, AliasLoc, Alias, 174 SS, IdentLoc, Ident); 175} 176 177/// ParseLinkage - We know that the current token is a string_literal 178/// and just before that, that extern was seen. 179/// 180/// linkage-specification: [C++ 7.5p2: dcl.link] 181/// 'extern' string-literal '{' declaration-seq[opt] '}' 182/// 'extern' string-literal declaration 183/// 184Decl *Parser::ParseLinkage(ParsingDeclSpec &DS, 185 unsigned Context) { 186 assert(Tok.is(tok::string_literal) && "Not a string literal!"); 187 llvm::SmallString<8> LangBuffer; 188 // LangBuffer is guaranteed to be big enough. 189 bool Invalid = false; 190 llvm::StringRef Lang = PP.getSpelling(Tok, LangBuffer, &Invalid); 191 if (Invalid) 192 return 0; 193 194 SourceLocation Loc = ConsumeStringToken(); 195 196 ParseScope LinkageScope(this, Scope::DeclScope); 197 Decl *LinkageSpec 198 = Actions.ActOnStartLinkageSpecification(getCurScope(), 199 /*FIXME: */SourceLocation(), 200 Loc, Lang, 201 Tok.is(tok::l_brace)? Tok.getLocation() 202 : SourceLocation()); 203 204 CXX0XAttributeList Attr; 205 if (getLang().CPlusPlus0x && isCXX0XAttributeSpecifier()) { 206 Attr = ParseCXX0XAttributes(); 207 } 208 209 if (Tok.isNot(tok::l_brace)) { 210 DS.setExternInLinkageSpec(true); 211 ParseExternalDeclaration(Attr, &DS); 212 return Actions.ActOnFinishLinkageSpecification(getCurScope(), LinkageSpec, 213 SourceLocation()); 214 } 215 216 DS.abort(); 217 218 if (Attr.HasAttr) 219 Diag(Attr.Range.getBegin(), diag::err_attributes_not_allowed) 220 << Attr.Range; 221 222 SourceLocation LBrace = ConsumeBrace(); 223 while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) { 224 CXX0XAttributeList Attr; 225 if (getLang().CPlusPlus0x && isCXX0XAttributeSpecifier()) 226 Attr = ParseCXX0XAttributes(); 227 ParseExternalDeclaration(Attr); 228 } 229 230 SourceLocation RBrace = MatchRHSPunctuation(tok::r_brace, LBrace); 231 return Actions.ActOnFinishLinkageSpecification(getCurScope(), LinkageSpec, RBrace); 232} 233 234/// ParseUsingDirectiveOrDeclaration - Parse C++ using using-declaration or 235/// using-directive. Assumes that current token is 'using'. 236Decl *Parser::ParseUsingDirectiveOrDeclaration(unsigned Context, 237 SourceLocation &DeclEnd, 238 CXX0XAttributeList Attr) { 239 assert(Tok.is(tok::kw_using) && "Not using token"); 240 241 // Eat 'using'. 242 SourceLocation UsingLoc = ConsumeToken(); 243 244 if (Tok.is(tok::code_completion)) { 245 Actions.CodeCompleteUsing(getCurScope()); 246 ConsumeCodeCompletionToken(); 247 } 248 249 if (Tok.is(tok::kw_namespace)) 250 // Next token after 'using' is 'namespace' so it must be using-directive 251 return ParseUsingDirective(Context, UsingLoc, DeclEnd, Attr.AttrList); 252 253 if (Attr.HasAttr) 254 Diag(Attr.Range.getBegin(), diag::err_attributes_not_allowed) 255 << Attr.Range; 256 257 // Otherwise, it must be using-declaration. 258 // Ignore illegal attributes (the caller should already have issued an error. 259 return ParseUsingDeclaration(Context, UsingLoc, DeclEnd); 260} 261 262/// ParseUsingDirective - Parse C++ using-directive, assumes 263/// that current token is 'namespace' and 'using' was already parsed. 264/// 265/// using-directive: [C++ 7.3.p4: namespace.udir] 266/// 'using' 'namespace' ::[opt] nested-name-specifier[opt] 267/// namespace-name ; 268/// [GNU] using-directive: 269/// 'using' 'namespace' ::[opt] nested-name-specifier[opt] 270/// namespace-name attributes[opt] ; 271/// 272Decl *Parser::ParseUsingDirective(unsigned Context, 273 SourceLocation UsingLoc, 274 SourceLocation &DeclEnd, 275 AttributeList *Attr) { 276 assert(Tok.is(tok::kw_namespace) && "Not 'namespace' token"); 277 278 // Eat 'namespace'. 279 SourceLocation NamespcLoc = ConsumeToken(); 280 281 if (Tok.is(tok::code_completion)) { 282 Actions.CodeCompleteUsingDirective(getCurScope()); 283 ConsumeCodeCompletionToken(); 284 } 285 286 CXXScopeSpec SS; 287 // Parse (optional) nested-name-specifier. 288 ParseOptionalCXXScopeSpecifier(SS, ParsedType(), false); 289 290 IdentifierInfo *NamespcName = 0; 291 SourceLocation IdentLoc = SourceLocation(); 292 293 // Parse namespace-name. 294 if (SS.isInvalid() || Tok.isNot(tok::identifier)) { 295 Diag(Tok, diag::err_expected_namespace_name); 296 // If there was invalid namespace name, skip to end of decl, and eat ';'. 297 SkipUntil(tok::semi); 298 // FIXME: Are there cases, when we would like to call ActOnUsingDirective? 299 return 0; 300 } 301 302 // Parse identifier. 303 NamespcName = Tok.getIdentifierInfo(); 304 IdentLoc = ConsumeToken(); 305 306 // Parse (optional) attributes (most likely GNU strong-using extension). 307 bool GNUAttr = false; 308 if (Tok.is(tok::kw___attribute)) { 309 GNUAttr = true; 310 Attr = addAttributeLists(Attr, ParseGNUAttributes()); 311 } 312 313 // Eat ';'. 314 DeclEnd = Tok.getLocation(); 315 ExpectAndConsume(tok::semi, 316 GNUAttr ? diag::err_expected_semi_after_attribute_list : 317 diag::err_expected_semi_after_namespace_name, "", tok::semi); 318 319 return Actions.ActOnUsingDirective(getCurScope(), UsingLoc, NamespcLoc, SS, 320 IdentLoc, NamespcName, Attr); 321} 322 323/// ParseUsingDeclaration - Parse C++ using-declaration. Assumes that 324/// 'using' was already seen. 325/// 326/// using-declaration: [C++ 7.3.p3: namespace.udecl] 327/// 'using' 'typename'[opt] ::[opt] nested-name-specifier 328/// unqualified-id 329/// 'using' :: unqualified-id 330/// 331Decl *Parser::ParseUsingDeclaration(unsigned Context, 332 SourceLocation UsingLoc, 333 SourceLocation &DeclEnd, 334 AccessSpecifier AS) { 335 CXXScopeSpec SS; 336 SourceLocation TypenameLoc; 337 bool IsTypeName; 338 339 // Ignore optional 'typename'. 340 // FIXME: This is wrong; we should parse this as a typename-specifier. 341 if (Tok.is(tok::kw_typename)) { 342 TypenameLoc = Tok.getLocation(); 343 ConsumeToken(); 344 IsTypeName = true; 345 } 346 else 347 IsTypeName = false; 348 349 // Parse nested-name-specifier. 350 ParseOptionalCXXScopeSpecifier(SS, ParsedType(), false); 351 352 // Check nested-name specifier. 353 if (SS.isInvalid()) { 354 SkipUntil(tok::semi); 355 return 0; 356 } 357 358 // Parse the unqualified-id. We allow parsing of both constructor and 359 // destructor names and allow the action module to diagnose any semantic 360 // errors. 361 UnqualifiedId Name; 362 if (ParseUnqualifiedId(SS, 363 /*EnteringContext=*/false, 364 /*AllowDestructorName=*/true, 365 /*AllowConstructorName=*/true, 366 ParsedType(), 367 Name)) { 368 SkipUntil(tok::semi); 369 return 0; 370 } 371 372 // Parse (optional) attributes (most likely GNU strong-using extension). 373 llvm::OwningPtr<AttributeList> AttrList; 374 if (Tok.is(tok::kw___attribute)) 375 AttrList.reset(ParseGNUAttributes()); 376 377 // Eat ';'. 378 DeclEnd = Tok.getLocation(); 379 ExpectAndConsume(tok::semi, diag::err_expected_semi_after, 380 AttrList ? "attributes list" : "using declaration", 381 tok::semi); 382 383 return Actions.ActOnUsingDeclaration(getCurScope(), AS, true, UsingLoc, SS, Name, 384 AttrList.get(), IsTypeName, TypenameLoc); 385} 386 387/// ParseStaticAssertDeclaration - Parse C++0x static_assert-declaratoion. 388/// 389/// static_assert-declaration: 390/// static_assert ( constant-expression , string-literal ) ; 391/// 392Decl *Parser::ParseStaticAssertDeclaration(SourceLocation &DeclEnd){ 393 assert(Tok.is(tok::kw_static_assert) && "Not a static_assert declaration"); 394 SourceLocation StaticAssertLoc = ConsumeToken(); 395 396 if (Tok.isNot(tok::l_paren)) { 397 Diag(Tok, diag::err_expected_lparen); 398 return 0; 399 } 400 401 SourceLocation LParenLoc = ConsumeParen(); 402 403 ExprResult AssertExpr(ParseConstantExpression()); 404 if (AssertExpr.isInvalid()) { 405 SkipUntil(tok::semi); 406 return 0; 407 } 408 409 if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "", tok::semi)) 410 return 0; 411 412 if (Tok.isNot(tok::string_literal)) { 413 Diag(Tok, diag::err_expected_string_literal); 414 SkipUntil(tok::semi); 415 return 0; 416 } 417 418 ExprResult AssertMessage(ParseStringLiteralExpression()); 419 if (AssertMessage.isInvalid()) 420 return 0; 421 422 MatchRHSPunctuation(tok::r_paren, LParenLoc); 423 424 DeclEnd = Tok.getLocation(); 425 ExpectAndConsume(tok::semi, diag::err_expected_semi_after_static_assert); 426 427 return Actions.ActOnStaticAssertDeclaration(StaticAssertLoc, 428 AssertExpr.take(), 429 AssertMessage.take()); 430} 431 432/// ParseDecltypeSpecifier - Parse a C++0x decltype specifier. 433/// 434/// 'decltype' ( expression ) 435/// 436void Parser::ParseDecltypeSpecifier(DeclSpec &DS) { 437 assert(Tok.is(tok::kw_decltype) && "Not a decltype specifier"); 438 439 SourceLocation StartLoc = ConsumeToken(); 440 SourceLocation LParenLoc = Tok.getLocation(); 441 442 if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after, 443 "decltype")) { 444 SkipUntil(tok::r_paren); 445 return; 446 } 447 448 // Parse the expression 449 450 // C++0x [dcl.type.simple]p4: 451 // The operand of the decltype specifier is an unevaluated operand. 452 EnterExpressionEvaluationContext Unevaluated(Actions, 453 Sema::Unevaluated); 454 ExprResult Result = ParseExpression(); 455 if (Result.isInvalid()) { 456 SkipUntil(tok::r_paren); 457 return; 458 } 459 460 // Match the ')' 461 SourceLocation RParenLoc; 462 if (Tok.is(tok::r_paren)) 463 RParenLoc = ConsumeParen(); 464 else 465 MatchRHSPunctuation(tok::r_paren, LParenLoc); 466 467 if (RParenLoc.isInvalid()) 468 return; 469 470 const char *PrevSpec = 0; 471 unsigned DiagID; 472 // Check for duplicate type specifiers (e.g. "int decltype(a)"). 473 if (DS.SetTypeSpecType(DeclSpec::TST_decltype, StartLoc, PrevSpec, 474 DiagID, Result.release())) 475 Diag(StartLoc, DiagID) << PrevSpec; 476} 477 478/// ParseClassName - Parse a C++ class-name, which names a class. Note 479/// that we only check that the result names a type; semantic analysis 480/// will need to verify that the type names a class. The result is 481/// either a type or NULL, depending on whether a type name was 482/// found. 483/// 484/// class-name: [C++ 9.1] 485/// identifier 486/// simple-template-id 487/// 488Parser::TypeResult Parser::ParseClassName(SourceLocation &EndLocation, 489 CXXScopeSpec *SS) { 490 // Check whether we have a template-id that names a type. 491 if (Tok.is(tok::annot_template_id)) { 492 TemplateIdAnnotation *TemplateId 493 = static_cast<TemplateIdAnnotation *>(Tok.getAnnotationValue()); 494 if (TemplateId->Kind == TNK_Type_template || 495 TemplateId->Kind == TNK_Dependent_template_name) { 496 AnnotateTemplateIdTokenAsType(SS); 497 498 assert(Tok.is(tok::annot_typename) && "template-id -> type failed"); 499 ParsedType Type = getTypeAnnotation(Tok); 500 EndLocation = Tok.getAnnotationEndLoc(); 501 ConsumeToken(); 502 503 if (Type) 504 return Type; 505 return true; 506 } 507 508 // Fall through to produce an error below. 509 } 510 511 if (Tok.isNot(tok::identifier)) { 512 Diag(Tok, diag::err_expected_class_name); 513 return true; 514 } 515 516 IdentifierInfo *Id = Tok.getIdentifierInfo(); 517 SourceLocation IdLoc = ConsumeToken(); 518 519 if (Tok.is(tok::less)) { 520 // It looks the user intended to write a template-id here, but the 521 // template-name was wrong. Try to fix that. 522 TemplateNameKind TNK = TNK_Type_template; 523 TemplateTy Template; 524 if (!Actions.DiagnoseUnknownTemplateName(*Id, IdLoc, getCurScope(), 525 SS, Template, TNK)) { 526 Diag(IdLoc, diag::err_unknown_template_name) 527 << Id; 528 } 529 530 if (!Template) 531 return true; 532 533 // Form the template name 534 UnqualifiedId TemplateName; 535 TemplateName.setIdentifier(Id, IdLoc); 536 537 // Parse the full template-id, then turn it into a type. 538 if (AnnotateTemplateIdToken(Template, TNK, SS, TemplateName, 539 SourceLocation(), true)) 540 return true; 541 if (TNK == TNK_Dependent_template_name) 542 AnnotateTemplateIdTokenAsType(SS); 543 544 // If we didn't end up with a typename token, there's nothing more we 545 // can do. 546 if (Tok.isNot(tok::annot_typename)) 547 return true; 548 549 // Retrieve the type from the annotation token, consume that token, and 550 // return. 551 EndLocation = Tok.getAnnotationEndLoc(); 552 ParsedType Type = getTypeAnnotation(Tok); 553 ConsumeToken(); 554 return Type; 555 } 556 557 // We have an identifier; check whether it is actually a type. 558 ParsedType Type = Actions.getTypeName(*Id, IdLoc, getCurScope(), SS, true); 559 if (!Type) { 560 Diag(IdLoc, diag::err_expected_class_name); 561 return true; 562 } 563 564 // Consume the identifier. 565 EndLocation = IdLoc; 566 567 // Fake up a Declarator to use with ActOnTypeName. 568 DeclSpec DS; 569 DS.SetRangeStart(IdLoc); 570 DS.SetRangeEnd(EndLocation); 571 DS.getTypeSpecScope() = *SS; 572 573 const char *PrevSpec = 0; 574 unsigned DiagID; 575 DS.SetTypeSpecType(TST_typename, IdLoc, PrevSpec, DiagID, Type); 576 577 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext); 578 return Actions.ActOnTypeName(getCurScope(), DeclaratorInfo); 579} 580 581/// ParseClassSpecifier - Parse a C++ class-specifier [C++ class] or 582/// elaborated-type-specifier [C++ dcl.type.elab]; we can't tell which 583/// until we reach the start of a definition or see a token that 584/// cannot start a definition. If SuppressDeclarations is true, we do know. 585/// 586/// class-specifier: [C++ class] 587/// class-head '{' member-specification[opt] '}' 588/// class-head '{' member-specification[opt] '}' attributes[opt] 589/// class-head: 590/// class-key identifier[opt] base-clause[opt] 591/// class-key nested-name-specifier identifier base-clause[opt] 592/// class-key nested-name-specifier[opt] simple-template-id 593/// base-clause[opt] 594/// [GNU] class-key attributes[opt] identifier[opt] base-clause[opt] 595/// [GNU] class-key attributes[opt] nested-name-specifier 596/// identifier base-clause[opt] 597/// [GNU] class-key attributes[opt] nested-name-specifier[opt] 598/// simple-template-id base-clause[opt] 599/// class-key: 600/// 'class' 601/// 'struct' 602/// 'union' 603/// 604/// elaborated-type-specifier: [C++ dcl.type.elab] 605/// class-key ::[opt] nested-name-specifier[opt] identifier 606/// class-key ::[opt] nested-name-specifier[opt] 'template'[opt] 607/// simple-template-id 608/// 609/// Note that the C++ class-specifier and elaborated-type-specifier, 610/// together, subsume the C99 struct-or-union-specifier: 611/// 612/// struct-or-union-specifier: [C99 6.7.2.1] 613/// struct-or-union identifier[opt] '{' struct-contents '}' 614/// struct-or-union identifier 615/// [GNU] struct-or-union attributes[opt] identifier[opt] '{' struct-contents 616/// '}' attributes[opt] 617/// [GNU] struct-or-union attributes[opt] identifier 618/// struct-or-union: 619/// 'struct' 620/// 'union' 621void Parser::ParseClassSpecifier(tok::TokenKind TagTokKind, 622 SourceLocation StartLoc, DeclSpec &DS, 623 const ParsedTemplateInfo &TemplateInfo, 624 AccessSpecifier AS, bool SuppressDeclarations){ 625 DeclSpec::TST TagType; 626 if (TagTokKind == tok::kw_struct) 627 TagType = DeclSpec::TST_struct; 628 else if (TagTokKind == tok::kw_class) 629 TagType = DeclSpec::TST_class; 630 else { 631 assert(TagTokKind == tok::kw_union && "Not a class specifier"); 632 TagType = DeclSpec::TST_union; 633 } 634 635 if (Tok.is(tok::code_completion)) { 636 // Code completion for a struct, class, or union name. 637 Actions.CodeCompleteTag(getCurScope(), TagType); 638 ConsumeCodeCompletionToken(); 639 } 640 641 // C++03 [temp.explicit] 14.7.2/8: 642 // The usual access checking rules do not apply to names used to specify 643 // explicit instantiations. 644 // 645 // As an extension we do not perform access checking on the names used to 646 // specify explicit specializations either. This is important to allow 647 // specializing traits classes for private types. 648 bool SuppressingAccessChecks = false; 649 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation || 650 TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization) { 651 Actions.ActOnStartSuppressingAccessChecks(); 652 SuppressingAccessChecks = true; 653 } 654 655 AttributeList *AttrList = 0; 656 // If attributes exist after tag, parse them. 657 if (Tok.is(tok::kw___attribute)) 658 AttrList = ParseGNUAttributes(); 659 660 // If declspecs exist after tag, parse them. 661 while (Tok.is(tok::kw___declspec)) 662 AttrList = ParseMicrosoftDeclSpec(AttrList); 663 664 // If C++0x attributes exist here, parse them. 665 // FIXME: Are we consistent with the ordering of parsing of different 666 // styles of attributes? 667 if (isCXX0XAttributeSpecifier()) 668 AttrList = addAttributeLists(AttrList, ParseCXX0XAttributes().AttrList); 669 670 if (TagType == DeclSpec::TST_struct && Tok.is(tok::kw___is_pod)) { 671 // GNU libstdc++ 4.2 uses __is_pod as the name of a struct template, but 672 // __is_pod is a keyword in GCC >= 4.3. Therefore, when we see the 673 // token sequence "struct __is_pod", make __is_pod into a normal 674 // identifier rather than a keyword, to allow libstdc++ 4.2 to work 675 // properly. 676 Tok.getIdentifierInfo()->RevertTokenIDToIdentifier(); 677 Tok.setKind(tok::identifier); 678 } 679 680 if (TagType == DeclSpec::TST_struct && Tok.is(tok::kw___is_empty)) { 681 // GNU libstdc++ 4.2 uses __is_empty as the name of a struct template, but 682 // __is_empty is a keyword in GCC >= 4.3. Therefore, when we see the 683 // token sequence "struct __is_empty", make __is_empty into a normal 684 // identifier rather than a keyword, to allow libstdc++ 4.2 to work 685 // properly. 686 Tok.getIdentifierInfo()->RevertTokenIDToIdentifier(); 687 Tok.setKind(tok::identifier); 688 } 689 690 // Parse the (optional) nested-name-specifier. 691 CXXScopeSpec &SS = DS.getTypeSpecScope(); 692 if (getLang().CPlusPlus) { 693 // "FOO : BAR" is not a potential typo for "FOO::BAR". 694 ColonProtectionRAIIObject X(*this); 695 696 if (ParseOptionalCXXScopeSpecifier(SS, ParsedType(), true)) 697 DS.SetTypeSpecError(); 698 if (SS.isSet()) 699 if (Tok.isNot(tok::identifier) && Tok.isNot(tok::annot_template_id)) 700 Diag(Tok, diag::err_expected_ident); 701 } 702 703 TemplateParameterLists *TemplateParams = TemplateInfo.TemplateParams; 704 705 // Parse the (optional) class name or simple-template-id. 706 IdentifierInfo *Name = 0; 707 SourceLocation NameLoc; 708 TemplateIdAnnotation *TemplateId = 0; 709 if (Tok.is(tok::identifier)) { 710 Name = Tok.getIdentifierInfo(); 711 NameLoc = ConsumeToken(); 712 713 if (Tok.is(tok::less) && getLang().CPlusPlus) { 714 // The name was supposed to refer to a template, but didn't. 715 // Eat the template argument list and try to continue parsing this as 716 // a class (or template thereof). 717 TemplateArgList TemplateArgs; 718 SourceLocation LAngleLoc, RAngleLoc; 719 if (ParseTemplateIdAfterTemplateName(TemplateTy(), NameLoc, &SS, 720 true, LAngleLoc, 721 TemplateArgs, RAngleLoc)) { 722 // We couldn't parse the template argument list at all, so don't 723 // try to give any location information for the list. 724 LAngleLoc = RAngleLoc = SourceLocation(); 725 } 726 727 Diag(NameLoc, diag::err_explicit_spec_non_template) 728 << (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) 729 << (TagType == DeclSpec::TST_class? 0 730 : TagType == DeclSpec::TST_struct? 1 731 : 2) 732 << Name 733 << SourceRange(LAngleLoc, RAngleLoc); 734 735 // Strip off the last template parameter list if it was empty, since 736 // we've removed its template argument list. 737 if (TemplateParams && TemplateInfo.LastParameterListWasEmpty) { 738 if (TemplateParams && TemplateParams->size() > 1) { 739 TemplateParams->pop_back(); 740 } else { 741 TemplateParams = 0; 742 const_cast<ParsedTemplateInfo&>(TemplateInfo).Kind 743 = ParsedTemplateInfo::NonTemplate; 744 } 745 } else if (TemplateInfo.Kind 746 == ParsedTemplateInfo::ExplicitInstantiation) { 747 // Pretend this is just a forward declaration. 748 TemplateParams = 0; 749 const_cast<ParsedTemplateInfo&>(TemplateInfo).Kind 750 = ParsedTemplateInfo::NonTemplate; 751 const_cast<ParsedTemplateInfo&>(TemplateInfo).TemplateLoc 752 = SourceLocation(); 753 const_cast<ParsedTemplateInfo&>(TemplateInfo).ExternLoc 754 = SourceLocation(); 755 } 756 } 757 } else if (Tok.is(tok::annot_template_id)) { 758 TemplateId = static_cast<TemplateIdAnnotation *>(Tok.getAnnotationValue()); 759 NameLoc = ConsumeToken(); 760 761 if (TemplateId->Kind != TNK_Type_template) { 762 // The template-name in the simple-template-id refers to 763 // something other than a class template. Give an appropriate 764 // error message and skip to the ';'. 765 SourceRange Range(NameLoc); 766 if (SS.isNotEmpty()) 767 Range.setBegin(SS.getBeginLoc()); 768 769 Diag(TemplateId->LAngleLoc, diag::err_template_spec_syntax_non_template) 770 << Name << static_cast<int>(TemplateId->Kind) << Range; 771 772 DS.SetTypeSpecError(); 773 SkipUntil(tok::semi, false, true); 774 TemplateId->Destroy(); 775 if (SuppressingAccessChecks) 776 Actions.ActOnStopSuppressingAccessChecks(); 777 778 return; 779 } 780 } 781 782 // As soon as we're finished parsing the class's template-id, turn access 783 // checking back on. 784 if (SuppressingAccessChecks) 785 Actions.ActOnStopSuppressingAccessChecks(); 786 787 // There are four options here. If we have 'struct foo;', then this 788 // is either a forward declaration or a friend declaration, which 789 // have to be treated differently. If we have 'struct foo {...' or 790 // 'struct foo :...' then this is a definition. Otherwise we have 791 // something like 'struct foo xyz', a reference. 792 // However, in some contexts, things look like declarations but are just 793 // references, e.g. 794 // new struct s; 795 // or 796 // &T::operator struct s; 797 // For these, SuppressDeclarations is true. 798 Sema::TagUseKind TUK; 799 if (SuppressDeclarations) 800 TUK = Sema::TUK_Reference; 801 else if (Tok.is(tok::l_brace) || (getLang().CPlusPlus && Tok.is(tok::colon))){ 802 if (DS.isFriendSpecified()) { 803 // C++ [class.friend]p2: 804 // A class shall not be defined in a friend declaration. 805 Diag(Tok.getLocation(), diag::err_friend_decl_defines_class) 806 << SourceRange(DS.getFriendSpecLoc()); 807 808 // Skip everything up to the semicolon, so that this looks like a proper 809 // friend class (or template thereof) declaration. 810 SkipUntil(tok::semi, true, true); 811 TUK = Sema::TUK_Friend; 812 } else { 813 // Okay, this is a class definition. 814 TUK = Sema::TUK_Definition; 815 } 816 } else if (Tok.is(tok::semi)) 817 TUK = DS.isFriendSpecified() ? Sema::TUK_Friend : Sema::TUK_Declaration; 818 else 819 TUK = Sema::TUK_Reference; 820 821 if (!Name && !TemplateId && (DS.getTypeSpecType() == DeclSpec::TST_error || 822 TUK != Sema::TUK_Definition)) { 823 if (DS.getTypeSpecType() != DeclSpec::TST_error) { 824 // We have a declaration or reference to an anonymous class. 825 Diag(StartLoc, diag::err_anon_type_definition) 826 << DeclSpec::getSpecifierName(TagType); 827 } 828 829 SkipUntil(tok::comma, true); 830 831 if (TemplateId) 832 TemplateId->Destroy(); 833 return; 834 } 835 836 // Create the tag portion of the class or class template. 837 DeclResult TagOrTempResult = true; // invalid 838 TypeResult TypeResult = true; // invalid 839 840 bool Owned = false; 841 if (TemplateId) { 842 // Explicit specialization, class template partial specialization, 843 // or explicit instantiation. 844 ASTTemplateArgsPtr TemplateArgsPtr(Actions, 845 TemplateId->getTemplateArgs(), 846 TemplateId->NumArgs); 847 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation && 848 TUK == Sema::TUK_Declaration) { 849 // This is an explicit instantiation of a class template. 850 TagOrTempResult 851 = Actions.ActOnExplicitInstantiation(getCurScope(), 852 TemplateInfo.ExternLoc, 853 TemplateInfo.TemplateLoc, 854 TagType, 855 StartLoc, 856 SS, 857 TemplateId->Template, 858 TemplateId->TemplateNameLoc, 859 TemplateId->LAngleLoc, 860 TemplateArgsPtr, 861 TemplateId->RAngleLoc, 862 AttrList); 863 864 // Friend template-ids are treated as references unless 865 // they have template headers, in which case they're ill-formed 866 // (FIXME: "template <class T> friend class A<T>::B<int>;"). 867 // We diagnose this error in ActOnClassTemplateSpecialization. 868 } else if (TUK == Sema::TUK_Reference || 869 (TUK == Sema::TUK_Friend && 870 TemplateInfo.Kind == ParsedTemplateInfo::NonTemplate)) { 871 TypeResult 872 = Actions.ActOnTemplateIdType(TemplateId->Template, 873 TemplateId->TemplateNameLoc, 874 TemplateId->LAngleLoc, 875 TemplateArgsPtr, 876 TemplateId->RAngleLoc); 877 878 TypeResult = Actions.ActOnTagTemplateIdType(TypeResult, TUK, 879 TagType, StartLoc); 880 } else { 881 // This is an explicit specialization or a class template 882 // partial specialization. 883 TemplateParameterLists FakedParamLists; 884 885 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) { 886 // This looks like an explicit instantiation, because we have 887 // something like 888 // 889 // template class Foo<X> 890 // 891 // but it actually has a definition. Most likely, this was 892 // meant to be an explicit specialization, but the user forgot 893 // the '<>' after 'template'. 894 assert(TUK == Sema::TUK_Definition && "Expected a definition here"); 895 896 SourceLocation LAngleLoc 897 = PP.getLocForEndOfToken(TemplateInfo.TemplateLoc); 898 Diag(TemplateId->TemplateNameLoc, 899 diag::err_explicit_instantiation_with_definition) 900 << SourceRange(TemplateInfo.TemplateLoc) 901 << FixItHint::CreateInsertion(LAngleLoc, "<>"); 902 903 // Create a fake template parameter list that contains only 904 // "template<>", so that we treat this construct as a class 905 // template specialization. 906 FakedParamLists.push_back( 907 Actions.ActOnTemplateParameterList(0, SourceLocation(), 908 TemplateInfo.TemplateLoc, 909 LAngleLoc, 910 0, 0, 911 LAngleLoc)); 912 TemplateParams = &FakedParamLists; 913 } 914 915 // Build the class template specialization. 916 TagOrTempResult 917 = Actions.ActOnClassTemplateSpecialization(getCurScope(), TagType, TUK, 918 StartLoc, SS, 919 TemplateId->Template, 920 TemplateId->TemplateNameLoc, 921 TemplateId->LAngleLoc, 922 TemplateArgsPtr, 923 TemplateId->RAngleLoc, 924 AttrList, 925 MultiTemplateParamsArg(Actions, 926 TemplateParams? &(*TemplateParams)[0] : 0, 927 TemplateParams? TemplateParams->size() : 0)); 928 } 929 TemplateId->Destroy(); 930 } else if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation && 931 TUK == Sema::TUK_Declaration) { 932 // Explicit instantiation of a member of a class template 933 // specialization, e.g., 934 // 935 // template struct Outer<int>::Inner; 936 // 937 TagOrTempResult 938 = Actions.ActOnExplicitInstantiation(getCurScope(), 939 TemplateInfo.ExternLoc, 940 TemplateInfo.TemplateLoc, 941 TagType, StartLoc, SS, Name, 942 NameLoc, AttrList); 943 } else { 944 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation && 945 TUK == Sema::TUK_Definition) { 946 // FIXME: Diagnose this particular error. 947 } 948 949 bool IsDependent = false; 950 951 // Declaration or definition of a class type 952 TagOrTempResult = Actions.ActOnTag(getCurScope(), TagType, TUK, StartLoc, SS, 953 Name, NameLoc, AttrList, AS, 954 MultiTemplateParamsArg(Actions, 955 TemplateParams? &(*TemplateParams)[0] : 0, 956 TemplateParams? TemplateParams->size() : 0), 957 Owned, IsDependent); 958 959 // If ActOnTag said the type was dependent, try again with the 960 // less common call. 961 if (IsDependent) 962 TypeResult = Actions.ActOnDependentTag(getCurScope(), TagType, TUK, 963 SS, Name, StartLoc, NameLoc); 964 } 965 966 // If there is a body, parse it and inform the actions module. 967 if (TUK == Sema::TUK_Definition) { 968 assert(Tok.is(tok::l_brace) || 969 (getLang().CPlusPlus && Tok.is(tok::colon))); 970 if (getLang().CPlusPlus) 971 ParseCXXMemberSpecification(StartLoc, TagType, TagOrTempResult.get()); 972 else 973 ParseStructUnionBody(StartLoc, TagType, TagOrTempResult.get()); 974 } 975 976 // FIXME: The DeclSpec should keep the locations of both the keyword and the 977 // name (if there is one). 978 SourceLocation TSTLoc = NameLoc.isValid()? NameLoc : StartLoc; 979 980 const char *PrevSpec = 0; 981 unsigned DiagID; 982 bool Result; 983 if (!TypeResult.isInvalid()) { 984 Result = DS.SetTypeSpecType(DeclSpec::TST_typename, TSTLoc, 985 PrevSpec, DiagID, TypeResult.get()); 986 } else if (!TagOrTempResult.isInvalid()) { 987 Result = DS.SetTypeSpecType(TagType, TSTLoc, PrevSpec, DiagID, 988 TagOrTempResult.get(), Owned); 989 } else { 990 DS.SetTypeSpecError(); 991 return; 992 } 993 994 if (Result) 995 Diag(StartLoc, DiagID) << PrevSpec; 996 997 // At this point, we've successfully parsed a class-specifier in 'definition' 998 // form (e.g. "struct foo { int x; }". While we could just return here, we're 999 // going to look at what comes after it to improve error recovery. If an 1000 // impossible token occurs next, we assume that the programmer forgot a ; at 1001 // the end of the declaration and recover that way. 1002 // 1003 // This switch enumerates the valid "follow" set for definition. 1004 if (TUK == Sema::TUK_Definition) { 1005 bool ExpectedSemi = true; 1006 switch (Tok.getKind()) { 1007 default: break; 1008 case tok::semi: // struct foo {...} ; 1009 case tok::star: // struct foo {...} * P; 1010 case tok::amp: // struct foo {...} & R = ... 1011 case tok::identifier: // struct foo {...} V ; 1012 case tok::r_paren: //(struct foo {...} ) {4} 1013 case tok::annot_cxxscope: // struct foo {...} a:: b; 1014 case tok::annot_typename: // struct foo {...} a ::b; 1015 case tok::annot_template_id: // struct foo {...} a<int> ::b; 1016 case tok::l_paren: // struct foo {...} ( x); 1017 case tok::comma: // __builtin_offsetof(struct foo{...} , 1018 ExpectedSemi = false; 1019 break; 1020 // Type qualifiers 1021 case tok::kw_const: // struct foo {...} const x; 1022 case tok::kw_volatile: // struct foo {...} volatile x; 1023 case tok::kw_restrict: // struct foo {...} restrict x; 1024 case tok::kw_inline: // struct foo {...} inline foo() {}; 1025 // Storage-class specifiers 1026 case tok::kw_static: // struct foo {...} static x; 1027 case tok::kw_extern: // struct foo {...} extern x; 1028 case tok::kw_typedef: // struct foo {...} typedef x; 1029 case tok::kw_register: // struct foo {...} register x; 1030 case tok::kw_auto: // struct foo {...} auto x; 1031 case tok::kw_mutable: // struct foo {...} mutable x; 1032 // As shown above, type qualifiers and storage class specifiers absolutely 1033 // can occur after class specifiers according to the grammar. However, 1034 // almost noone actually writes code like this. If we see one of these, 1035 // it is much more likely that someone missed a semi colon and the 1036 // type/storage class specifier we're seeing is part of the *next* 1037 // intended declaration, as in: 1038 // 1039 // struct foo { ... } 1040 // typedef int X; 1041 // 1042 // We'd really like to emit a missing semicolon error instead of emitting 1043 // an error on the 'int' saying that you can't have two type specifiers in 1044 // the same declaration of X. Because of this, we look ahead past this 1045 // token to see if it's a type specifier. If so, we know the code is 1046 // otherwise invalid, so we can produce the expected semi error. 1047 if (!isKnownToBeTypeSpecifier(NextToken())) 1048 ExpectedSemi = false; 1049 break; 1050 1051 case tok::r_brace: // struct bar { struct foo {...} } 1052 // Missing ';' at end of struct is accepted as an extension in C mode. 1053 if (!getLang().CPlusPlus) 1054 ExpectedSemi = false; 1055 break; 1056 } 1057 1058 if (ExpectedSemi) { 1059 ExpectAndConsume(tok::semi, diag::err_expected_semi_after_tagdecl, 1060 TagType == DeclSpec::TST_class ? "class" 1061 : TagType == DeclSpec::TST_struct? "struct" : "union"); 1062 // Push this token back into the preprocessor and change our current token 1063 // to ';' so that the rest of the code recovers as though there were an 1064 // ';' after the definition. 1065 PP.EnterToken(Tok); 1066 Tok.setKind(tok::semi); 1067 } 1068 } 1069} 1070 1071/// ParseBaseClause - Parse the base-clause of a C++ class [C++ class.derived]. 1072/// 1073/// base-clause : [C++ class.derived] 1074/// ':' base-specifier-list 1075/// base-specifier-list: 1076/// base-specifier '...'[opt] 1077/// base-specifier-list ',' base-specifier '...'[opt] 1078void Parser::ParseBaseClause(Decl *ClassDecl) { 1079 assert(Tok.is(tok::colon) && "Not a base clause"); 1080 ConsumeToken(); 1081 1082 // Build up an array of parsed base specifiers. 1083 llvm::SmallVector<CXXBaseSpecifier *, 8> BaseInfo; 1084 1085 while (true) { 1086 // Parse a base-specifier. 1087 BaseResult Result = ParseBaseSpecifier(ClassDecl); 1088 if (Result.isInvalid()) { 1089 // Skip the rest of this base specifier, up until the comma or 1090 // opening brace. 1091 SkipUntil(tok::comma, tok::l_brace, true, true); 1092 } else { 1093 // Add this to our array of base specifiers. 1094 BaseInfo.push_back(Result.get()); 1095 } 1096 1097 // If the next token is a comma, consume it and keep reading 1098 // base-specifiers. 1099 if (Tok.isNot(tok::comma)) break; 1100 1101 // Consume the comma. 1102 ConsumeToken(); 1103 } 1104 1105 // Attach the base specifiers 1106 Actions.ActOnBaseSpecifiers(ClassDecl, BaseInfo.data(), BaseInfo.size()); 1107} 1108 1109/// ParseBaseSpecifier - Parse a C++ base-specifier. A base-specifier is 1110/// one entry in the base class list of a class specifier, for example: 1111/// class foo : public bar, virtual private baz { 1112/// 'public bar' and 'virtual private baz' are each base-specifiers. 1113/// 1114/// base-specifier: [C++ class.derived] 1115/// ::[opt] nested-name-specifier[opt] class-name 1116/// 'virtual' access-specifier[opt] ::[opt] nested-name-specifier[opt] 1117/// class-name 1118/// access-specifier 'virtual'[opt] ::[opt] nested-name-specifier[opt] 1119/// class-name 1120Parser::BaseResult Parser::ParseBaseSpecifier(Decl *ClassDecl) { 1121 bool IsVirtual = false; 1122 SourceLocation StartLoc = Tok.getLocation(); 1123 1124 // Parse the 'virtual' keyword. 1125 if (Tok.is(tok::kw_virtual)) { 1126 ConsumeToken(); 1127 IsVirtual = true; 1128 } 1129 1130 // Parse an (optional) access specifier. 1131 AccessSpecifier Access = getAccessSpecifierIfPresent(); 1132 if (Access != AS_none) 1133 ConsumeToken(); 1134 1135 // Parse the 'virtual' keyword (again!), in case it came after the 1136 // access specifier. 1137 if (Tok.is(tok::kw_virtual)) { 1138 SourceLocation VirtualLoc = ConsumeToken(); 1139 if (IsVirtual) { 1140 // Complain about duplicate 'virtual' 1141 Diag(VirtualLoc, diag::err_dup_virtual) 1142 << FixItHint::CreateRemoval(VirtualLoc); 1143 } 1144 1145 IsVirtual = true; 1146 } 1147 1148 // Parse optional '::' and optional nested-name-specifier. 1149 CXXScopeSpec SS; 1150 ParseOptionalCXXScopeSpecifier(SS, ParsedType(), /*EnteringContext=*/false); 1151 1152 // The location of the base class itself. 1153 SourceLocation BaseLoc = Tok.getLocation(); 1154 1155 // Parse the class-name. 1156 SourceLocation EndLocation; 1157 TypeResult BaseType = ParseClassName(EndLocation, &SS); 1158 if (BaseType.isInvalid()) 1159 return true; 1160 1161 // Find the complete source range for the base-specifier. 1162 SourceRange Range(StartLoc, EndLocation); 1163 1164 // Notify semantic analysis that we have parsed a complete 1165 // base-specifier. 1166 return Actions.ActOnBaseSpecifier(ClassDecl, Range, IsVirtual, Access, 1167 BaseType.get(), BaseLoc); 1168} 1169 1170/// getAccessSpecifierIfPresent - Determine whether the next token is 1171/// a C++ access-specifier. 1172/// 1173/// access-specifier: [C++ class.derived] 1174/// 'private' 1175/// 'protected' 1176/// 'public' 1177AccessSpecifier Parser::getAccessSpecifierIfPresent() const { 1178 switch (Tok.getKind()) { 1179 default: return AS_none; 1180 case tok::kw_private: return AS_private; 1181 case tok::kw_protected: return AS_protected; 1182 case tok::kw_public: return AS_public; 1183 } 1184} 1185 1186void Parser::HandleMemberFunctionDefaultArgs(Declarator& DeclaratorInfo, 1187 Decl *ThisDecl) { 1188 // We just declared a member function. If this member function 1189 // has any default arguments, we'll need to parse them later. 1190 LateParsedMethodDeclaration *LateMethod = 0; 1191 DeclaratorChunk::FunctionTypeInfo &FTI 1192 = DeclaratorInfo.getTypeObject(0).Fun; 1193 for (unsigned ParamIdx = 0; ParamIdx < FTI.NumArgs; ++ParamIdx) { 1194 if (LateMethod || FTI.ArgInfo[ParamIdx].DefaultArgTokens) { 1195 if (!LateMethod) { 1196 // Push this method onto the stack of late-parsed method 1197 // declarations. 1198 getCurrentClass().MethodDecls.push_back( 1199 LateParsedMethodDeclaration(ThisDecl)); 1200 LateMethod = &getCurrentClass().MethodDecls.back(); 1201 LateMethod->TemplateScope = getCurScope()->isTemplateParamScope(); 1202 1203 // Add all of the parameters prior to this one (they don't 1204 // have default arguments). 1205 LateMethod->DefaultArgs.reserve(FTI.NumArgs); 1206 for (unsigned I = 0; I < ParamIdx; ++I) 1207 LateMethod->DefaultArgs.push_back( 1208 LateParsedDefaultArgument(FTI.ArgInfo[I].Param)); 1209 } 1210 1211 // Add this parameter to the list of parameters (it or may 1212 // not have a default argument). 1213 LateMethod->DefaultArgs.push_back( 1214 LateParsedDefaultArgument(FTI.ArgInfo[ParamIdx].Param, 1215 FTI.ArgInfo[ParamIdx].DefaultArgTokens)); 1216 } 1217 } 1218} 1219 1220/// ParseCXXClassMemberDeclaration - Parse a C++ class member declaration. 1221/// 1222/// member-declaration: 1223/// decl-specifier-seq[opt] member-declarator-list[opt] ';' 1224/// function-definition ';'[opt] 1225/// ::[opt] nested-name-specifier template[opt] unqualified-id ';'[TODO] 1226/// using-declaration [TODO] 1227/// [C++0x] static_assert-declaration 1228/// template-declaration 1229/// [GNU] '__extension__' member-declaration 1230/// 1231/// member-declarator-list: 1232/// member-declarator 1233/// member-declarator-list ',' member-declarator 1234/// 1235/// member-declarator: 1236/// declarator pure-specifier[opt] 1237/// declarator constant-initializer[opt] 1238/// identifier[opt] ':' constant-expression 1239/// 1240/// pure-specifier: 1241/// '= 0' 1242/// 1243/// constant-initializer: 1244/// '=' constant-expression 1245/// 1246void Parser::ParseCXXClassMemberDeclaration(AccessSpecifier AS, 1247 const ParsedTemplateInfo &TemplateInfo, 1248 ParsingDeclRAIIObject *TemplateDiags) { 1249 // Access declarations. 1250 if (!TemplateInfo.Kind && 1251 (Tok.is(tok::identifier) || Tok.is(tok::coloncolon)) && 1252 !TryAnnotateCXXScopeToken() && 1253 Tok.is(tok::annot_cxxscope)) { 1254 bool isAccessDecl = false; 1255 if (NextToken().is(tok::identifier)) 1256 isAccessDecl = GetLookAheadToken(2).is(tok::semi); 1257 else 1258 isAccessDecl = NextToken().is(tok::kw_operator); 1259 1260 if (isAccessDecl) { 1261 // Collect the scope specifier token we annotated earlier. 1262 CXXScopeSpec SS; 1263 ParseOptionalCXXScopeSpecifier(SS, ParsedType(), false); 1264 1265 // Try to parse an unqualified-id. 1266 UnqualifiedId Name; 1267 if (ParseUnqualifiedId(SS, false, true, true, ParsedType(), Name)) { 1268 SkipUntil(tok::semi); 1269 return; 1270 } 1271 1272 // TODO: recover from mistakenly-qualified operator declarations. 1273 if (ExpectAndConsume(tok::semi, 1274 diag::err_expected_semi_after, 1275 "access declaration", 1276 tok::semi)) 1277 return; 1278 1279 Actions.ActOnUsingDeclaration(getCurScope(), AS, 1280 false, SourceLocation(), 1281 SS, Name, 1282 /* AttrList */ 0, 1283 /* IsTypeName */ false, 1284 SourceLocation()); 1285 return; 1286 } 1287 } 1288 1289 // static_assert-declaration 1290 if (Tok.is(tok::kw_static_assert)) { 1291 // FIXME: Check for templates 1292 SourceLocation DeclEnd; 1293 ParseStaticAssertDeclaration(DeclEnd); 1294 return; 1295 } 1296 1297 if (Tok.is(tok::kw_template)) { 1298 assert(!TemplateInfo.TemplateParams && 1299 "Nested template improperly parsed?"); 1300 SourceLocation DeclEnd; 1301 ParseDeclarationStartingWithTemplate(Declarator::MemberContext, DeclEnd, 1302 AS); 1303 return; 1304 } 1305 1306 // Handle: member-declaration ::= '__extension__' member-declaration 1307 if (Tok.is(tok::kw___extension__)) { 1308 // __extension__ silences extension warnings in the subexpression. 1309 ExtensionRAIIObject O(Diags); // Use RAII to do this. 1310 ConsumeToken(); 1311 return ParseCXXClassMemberDeclaration(AS, TemplateInfo, TemplateDiags); 1312 } 1313 1314 // Don't parse FOO:BAR as if it were a typo for FOO::BAR, in this context it 1315 // is a bitfield. 1316 ColonProtectionRAIIObject X(*this); 1317 1318 CXX0XAttributeList AttrList; 1319 // Optional C++0x attribute-specifier 1320 if (getLang().CPlusPlus0x && isCXX0XAttributeSpecifier()) 1321 AttrList = ParseCXX0XAttributes(); 1322 1323 if (Tok.is(tok::kw_using)) { 1324 // FIXME: Check for template aliases 1325 1326 if (AttrList.HasAttr) 1327 Diag(AttrList.Range.getBegin(), diag::err_attributes_not_allowed) 1328 << AttrList.Range; 1329 1330 // Eat 'using'. 1331 SourceLocation UsingLoc = ConsumeToken(); 1332 1333 if (Tok.is(tok::kw_namespace)) { 1334 Diag(UsingLoc, diag::err_using_namespace_in_class); 1335 SkipUntil(tok::semi, true, true); 1336 } else { 1337 SourceLocation DeclEnd; 1338 // Otherwise, it must be using-declaration. 1339 ParseUsingDeclaration(Declarator::MemberContext, UsingLoc, DeclEnd, AS); 1340 } 1341 return; 1342 } 1343 1344 SourceLocation DSStart = Tok.getLocation(); 1345 // decl-specifier-seq: 1346 // Parse the common declaration-specifiers piece. 1347 ParsingDeclSpec DS(*this, TemplateDiags); 1348 DS.AddAttributes(AttrList.AttrList); 1349 ParseDeclarationSpecifiers(DS, TemplateInfo, AS, DSC_class); 1350 1351 MultiTemplateParamsArg TemplateParams(Actions, 1352 TemplateInfo.TemplateParams? TemplateInfo.TemplateParams->data() : 0, 1353 TemplateInfo.TemplateParams? TemplateInfo.TemplateParams->size() : 0); 1354 1355 if (Tok.is(tok::semi)) { 1356 ConsumeToken(); 1357 Decl *TheDecl = 1358 Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS, DS); 1359 DS.complete(TheDecl); 1360 return; 1361 } 1362 1363 ParsingDeclarator DeclaratorInfo(*this, DS, Declarator::MemberContext); 1364 1365 if (Tok.isNot(tok::colon)) { 1366 // Don't parse FOO:BAR as if it were a typo for FOO::BAR. 1367 ColonProtectionRAIIObject X(*this); 1368 1369 // Parse the first declarator. 1370 ParseDeclarator(DeclaratorInfo); 1371 // Error parsing the declarator? 1372 if (!DeclaratorInfo.hasName()) { 1373 // If so, skip until the semi-colon or a }. 1374 SkipUntil(tok::r_brace, true); 1375 if (Tok.is(tok::semi)) 1376 ConsumeToken(); 1377 return; 1378 } 1379 1380 // If attributes exist after the declarator, but before an '{', parse them. 1381 if (Tok.is(tok::kw___attribute)) { 1382 SourceLocation Loc; 1383 AttributeList *AttrList = ParseGNUAttributes(&Loc); 1384 DeclaratorInfo.AddAttributes(AttrList, Loc); 1385 } 1386 1387 // function-definition: 1388 if (Tok.is(tok::l_brace) 1389 || (DeclaratorInfo.isFunctionDeclarator() && 1390 (Tok.is(tok::colon) || Tok.is(tok::kw_try)))) { 1391 if (!DeclaratorInfo.isFunctionDeclarator()) { 1392 Diag(Tok, diag::err_func_def_no_params); 1393 ConsumeBrace(); 1394 SkipUntil(tok::r_brace, true); 1395 return; 1396 } 1397 1398 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) { 1399 Diag(Tok, diag::err_function_declared_typedef); 1400 // This recovery skips the entire function body. It would be nice 1401 // to simply call ParseCXXInlineMethodDef() below, however Sema 1402 // assumes the declarator represents a function, not a typedef. 1403 ConsumeBrace(); 1404 SkipUntil(tok::r_brace, true); 1405 return; 1406 } 1407 1408 ParseCXXInlineMethodDef(AS, DeclaratorInfo, TemplateInfo); 1409 return; 1410 } 1411 } 1412 1413 // member-declarator-list: 1414 // member-declarator 1415 // member-declarator-list ',' member-declarator 1416 1417 llvm::SmallVector<Decl *, 8> DeclsInGroup; 1418 ExprResult BitfieldSize; 1419 ExprResult Init; 1420 bool Deleted = false; 1421 1422 while (1) { 1423 // member-declarator: 1424 // declarator pure-specifier[opt] 1425 // declarator constant-initializer[opt] 1426 // identifier[opt] ':' constant-expression 1427 if (Tok.is(tok::colon)) { 1428 ConsumeToken(); 1429 BitfieldSize = ParseConstantExpression(); 1430 if (BitfieldSize.isInvalid()) 1431 SkipUntil(tok::comma, true, true); 1432 } 1433 1434 // pure-specifier: 1435 // '= 0' 1436 // 1437 // constant-initializer: 1438 // '=' constant-expression 1439 // 1440 // defaulted/deleted function-definition: 1441 // '=' 'default' [TODO] 1442 // '=' 'delete' 1443 if (Tok.is(tok::equal)) { 1444 ConsumeToken(); 1445 if (getLang().CPlusPlus0x && Tok.is(tok::kw_delete)) { 1446 ConsumeToken(); 1447 Deleted = true; 1448 } else { 1449 Init = ParseInitializer(); 1450 if (Init.isInvalid()) 1451 SkipUntil(tok::comma, true, true); 1452 } 1453 } 1454 1455 // If a simple-asm-expr is present, parse it. 1456 if (Tok.is(tok::kw_asm)) { 1457 SourceLocation Loc; 1458 ExprResult AsmLabel(ParseSimpleAsm(&Loc)); 1459 if (AsmLabel.isInvalid()) 1460 SkipUntil(tok::comma, true, true); 1461 1462 DeclaratorInfo.setAsmLabel(AsmLabel.release()); 1463 DeclaratorInfo.SetRangeEnd(Loc); 1464 } 1465 1466 // If attributes exist after the declarator, parse them. 1467 if (Tok.is(tok::kw___attribute)) { 1468 SourceLocation Loc; 1469 AttributeList *AttrList = ParseGNUAttributes(&Loc); 1470 DeclaratorInfo.AddAttributes(AttrList, Loc); 1471 } 1472 1473 // NOTE: If Sema is the Action module and declarator is an instance field, 1474 // this call will *not* return the created decl; It will return null. 1475 // See Sema::ActOnCXXMemberDeclarator for details. 1476 1477 Decl *ThisDecl = 0; 1478 if (DS.isFriendSpecified()) { 1479 // TODO: handle initializers, bitfields, 'delete' 1480 ThisDecl = Actions.ActOnFriendFunctionDecl(getCurScope(), DeclaratorInfo, 1481 /*IsDefinition*/ false, 1482 move(TemplateParams)); 1483 } else { 1484 ThisDecl = Actions.ActOnCXXMemberDeclarator(getCurScope(), AS, 1485 DeclaratorInfo, 1486 move(TemplateParams), 1487 BitfieldSize.release(), 1488 Init.release(), 1489 /*IsDefinition*/Deleted, 1490 Deleted); 1491 } 1492 if (ThisDecl) 1493 DeclsInGroup.push_back(ThisDecl); 1494 1495 if (DeclaratorInfo.isFunctionDeclarator() && 1496 DeclaratorInfo.getDeclSpec().getStorageClassSpec() 1497 != DeclSpec::SCS_typedef) { 1498 HandleMemberFunctionDefaultArgs(DeclaratorInfo, ThisDecl); 1499 } 1500 1501 DeclaratorInfo.complete(ThisDecl); 1502 1503 // If we don't have a comma, it is either the end of the list (a ';') 1504 // or an error, bail out. 1505 if (Tok.isNot(tok::comma)) 1506 break; 1507 1508 // Consume the comma. 1509 ConsumeToken(); 1510 1511 // Parse the next declarator. 1512 DeclaratorInfo.clear(); 1513 BitfieldSize = 0; 1514 Init = 0; 1515 Deleted = false; 1516 1517 // Attributes are only allowed on the second declarator. 1518 if (Tok.is(tok::kw___attribute)) { 1519 SourceLocation Loc; 1520 AttributeList *AttrList = ParseGNUAttributes(&Loc); 1521 DeclaratorInfo.AddAttributes(AttrList, Loc); 1522 } 1523 1524 if (Tok.isNot(tok::colon)) 1525 ParseDeclarator(DeclaratorInfo); 1526 } 1527 1528 if (ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list)) { 1529 // Skip to end of block or statement. 1530 SkipUntil(tok::r_brace, true, true); 1531 // If we stopped at a ';', eat it. 1532 if (Tok.is(tok::semi)) ConsumeToken(); 1533 return; 1534 } 1535 1536 Actions.FinalizeDeclaratorGroup(getCurScope(), DS, DeclsInGroup.data(), 1537 DeclsInGroup.size()); 1538} 1539 1540/// ParseCXXMemberSpecification - Parse the class definition. 1541/// 1542/// member-specification: 1543/// member-declaration member-specification[opt] 1544/// access-specifier ':' member-specification[opt] 1545/// 1546void Parser::ParseCXXMemberSpecification(SourceLocation RecordLoc, 1547 unsigned TagType, Decl *TagDecl) { 1548 assert((TagType == DeclSpec::TST_struct || 1549 TagType == DeclSpec::TST_union || 1550 TagType == DeclSpec::TST_class) && "Invalid TagType!"); 1551 1552 PrettyDeclStackTraceEntry CrashInfo(Actions, TagDecl, RecordLoc, 1553 "parsing struct/union/class body"); 1554 1555 // Determine whether this is a non-nested class. Note that local 1556 // classes are *not* considered to be nested classes. 1557 bool NonNestedClass = true; 1558 if (!ClassStack.empty()) { 1559 for (const Scope *S = getCurScope(); S; S = S->getParent()) { 1560 if (S->isClassScope()) { 1561 // We're inside a class scope, so this is a nested class. 1562 NonNestedClass = false; 1563 break; 1564 } 1565 1566 if ((S->getFlags() & Scope::FnScope)) { 1567 // If we're in a function or function template declared in the 1568 // body of a class, then this is a local class rather than a 1569 // nested class. 1570 const Scope *Parent = S->getParent(); 1571 if (Parent->isTemplateParamScope()) 1572 Parent = Parent->getParent(); 1573 if (Parent->isClassScope()) 1574 break; 1575 } 1576 } 1577 } 1578 1579 // Enter a scope for the class. 1580 ParseScope ClassScope(this, Scope::ClassScope|Scope::DeclScope); 1581 1582 // Note that we are parsing a new (potentially-nested) class definition. 1583 ParsingClassDefinition ParsingDef(*this, TagDecl, NonNestedClass); 1584 1585 if (TagDecl) 1586 Actions.ActOnTagStartDefinition(getCurScope(), TagDecl); 1587 1588 if (Tok.is(tok::colon)) { 1589 ParseBaseClause(TagDecl); 1590 1591 if (!Tok.is(tok::l_brace)) { 1592 Diag(Tok, diag::err_expected_lbrace_after_base_specifiers); 1593 1594 if (TagDecl) 1595 Actions.ActOnTagDefinitionError(getCurScope(), TagDecl); 1596 return; 1597 } 1598 } 1599 1600 assert(Tok.is(tok::l_brace)); 1601 1602 SourceLocation LBraceLoc = ConsumeBrace(); 1603 1604 if (TagDecl) 1605 Actions.ActOnStartCXXMemberDeclarations(getCurScope(), TagDecl, LBraceLoc); 1606 1607 // C++ 11p3: Members of a class defined with the keyword class are private 1608 // by default. Members of a class defined with the keywords struct or union 1609 // are public by default. 1610 AccessSpecifier CurAS; 1611 if (TagType == DeclSpec::TST_class) 1612 CurAS = AS_private; 1613 else 1614 CurAS = AS_public; 1615 1616 SourceLocation RBraceLoc; 1617 if (TagDecl) { 1618 // While we still have something to read, read the member-declarations. 1619 while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) { 1620 // Each iteration of this loop reads one member-declaration. 1621 1622 // Check for extraneous top-level semicolon. 1623 if (Tok.is(tok::semi)) { 1624 Diag(Tok, diag::ext_extra_struct_semi) 1625 << DeclSpec::getSpecifierName((DeclSpec::TST)TagType) 1626 << FixItHint::CreateRemoval(Tok.getLocation()); 1627 ConsumeToken(); 1628 continue; 1629 } 1630 1631 AccessSpecifier AS = getAccessSpecifierIfPresent(); 1632 if (AS != AS_none) { 1633 // Current token is a C++ access specifier. 1634 CurAS = AS; 1635 SourceLocation ASLoc = Tok.getLocation(); 1636 ConsumeToken(); 1637 if (Tok.is(tok::colon)) 1638 Actions.ActOnAccessSpecifier(AS, ASLoc, Tok.getLocation()); 1639 else 1640 Diag(Tok, diag::err_expected_colon); 1641 ConsumeToken(); 1642 continue; 1643 } 1644 1645 // FIXME: Make sure we don't have a template here. 1646 1647 // Parse all the comma separated declarators. 1648 ParseCXXClassMemberDeclaration(CurAS); 1649 } 1650 1651 RBraceLoc = MatchRHSPunctuation(tok::r_brace, LBraceLoc); 1652 } else { 1653 SkipUntil(tok::r_brace, false, false); 1654 } 1655 1656 // If attributes exist after class contents, parse them. 1657 llvm::OwningPtr<AttributeList> AttrList; 1658 if (Tok.is(tok::kw___attribute)) 1659 AttrList.reset(ParseGNUAttributes()); 1660 1661 if (TagDecl) 1662 Actions.ActOnFinishCXXMemberSpecification(getCurScope(), RecordLoc, TagDecl, 1663 LBraceLoc, RBraceLoc, 1664 AttrList.get()); 1665 1666 // C++ 9.2p2: Within the class member-specification, the class is regarded as 1667 // complete within function bodies, default arguments, 1668 // exception-specifications, and constructor ctor-initializers (including 1669 // such things in nested classes). 1670 // 1671 // FIXME: Only function bodies and constructor ctor-initializers are 1672 // parsed correctly, fix the rest. 1673 if (TagDecl && NonNestedClass) { 1674 // We are not inside a nested class. This class and its nested classes 1675 // are complete and we can parse the delayed portions of method 1676 // declarations and the lexed inline method definitions. 1677 SourceLocation SavedPrevTokLocation = PrevTokLocation; 1678 ParseLexedMethodDeclarations(getCurrentClass()); 1679 ParseLexedMethodDefs(getCurrentClass()); 1680 PrevTokLocation = SavedPrevTokLocation; 1681 } 1682 1683 if (TagDecl) 1684 Actions.ActOnTagFinishDefinition(getCurScope(), TagDecl, RBraceLoc); 1685 1686 // Leave the class scope. 1687 ParsingDef.Pop(); 1688 ClassScope.Exit(); 1689} 1690 1691/// ParseConstructorInitializer - Parse a C++ constructor initializer, 1692/// which explicitly initializes the members or base classes of a 1693/// class (C++ [class.base.init]). For example, the three initializers 1694/// after the ':' in the Derived constructor below: 1695/// 1696/// @code 1697/// class Base { }; 1698/// class Derived : Base { 1699/// int x; 1700/// float f; 1701/// public: 1702/// Derived(float f) : Base(), x(17), f(f) { } 1703/// }; 1704/// @endcode 1705/// 1706/// [C++] ctor-initializer: 1707/// ':' mem-initializer-list 1708/// 1709/// [C++] mem-initializer-list: 1710/// mem-initializer 1711/// mem-initializer , mem-initializer-list 1712void Parser::ParseConstructorInitializer(Decl *ConstructorDecl) { 1713 assert(Tok.is(tok::colon) && "Constructor initializer always starts with ':'"); 1714 1715 SourceLocation ColonLoc = ConsumeToken(); 1716 1717 llvm::SmallVector<CXXBaseOrMemberInitializer*, 4> MemInitializers; 1718 bool AnyErrors = false; 1719 1720 do { 1721 if (Tok.is(tok::code_completion)) { 1722 Actions.CodeCompleteConstructorInitializer(ConstructorDecl, 1723 MemInitializers.data(), 1724 MemInitializers.size()); 1725 ConsumeCodeCompletionToken(); 1726 } else { 1727 MemInitResult MemInit = ParseMemInitializer(ConstructorDecl); 1728 if (!MemInit.isInvalid()) 1729 MemInitializers.push_back(MemInit.get()); 1730 else 1731 AnyErrors = true; 1732 } 1733 1734 if (Tok.is(tok::comma)) 1735 ConsumeToken(); 1736 else if (Tok.is(tok::l_brace)) 1737 break; 1738 // If the next token looks like a base or member initializer, assume that 1739 // we're just missing a comma. 1740 else if (Tok.is(tok::identifier) || Tok.is(tok::coloncolon)) 1741 Diag(Tok.getLocation(), diag::err_ctor_init_missing_comma) 1742 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(PrevTokLocation), 1743 ", "); 1744 else { 1745 // Skip over garbage, until we get to '{'. Don't eat the '{'. 1746 Diag(Tok.getLocation(), diag::err_expected_lbrace_or_comma); 1747 SkipUntil(tok::l_brace, true, true); 1748 break; 1749 } 1750 } while (true); 1751 1752 Actions.ActOnMemInitializers(ConstructorDecl, ColonLoc, 1753 MemInitializers.data(), MemInitializers.size(), 1754 AnyErrors); 1755} 1756 1757/// ParseMemInitializer - Parse a C++ member initializer, which is 1758/// part of a constructor initializer that explicitly initializes one 1759/// member or base class (C++ [class.base.init]). See 1760/// ParseConstructorInitializer for an example. 1761/// 1762/// [C++] mem-initializer: 1763/// mem-initializer-id '(' expression-list[opt] ')' 1764/// 1765/// [C++] mem-initializer-id: 1766/// '::'[opt] nested-name-specifier[opt] class-name 1767/// identifier 1768Parser::MemInitResult Parser::ParseMemInitializer(Decl *ConstructorDecl) { 1769 // parse '::'[opt] nested-name-specifier[opt] 1770 CXXScopeSpec SS; 1771 ParseOptionalCXXScopeSpecifier(SS, ParsedType(), false); 1772 ParsedType TemplateTypeTy; 1773 if (Tok.is(tok::annot_template_id)) { 1774 TemplateIdAnnotation *TemplateId 1775 = static_cast<TemplateIdAnnotation *>(Tok.getAnnotationValue()); 1776 if (TemplateId->Kind == TNK_Type_template || 1777 TemplateId->Kind == TNK_Dependent_template_name) { 1778 AnnotateTemplateIdTokenAsType(&SS); 1779 assert(Tok.is(tok::annot_typename) && "template-id -> type failed"); 1780 TemplateTypeTy = getTypeAnnotation(Tok); 1781 } 1782 } 1783 if (!TemplateTypeTy && Tok.isNot(tok::identifier)) { 1784 Diag(Tok, diag::err_expected_member_or_base_name); 1785 return true; 1786 } 1787 1788 // Get the identifier. This may be a member name or a class name, 1789 // but we'll let the semantic analysis determine which it is. 1790 IdentifierInfo *II = Tok.is(tok::identifier) ? Tok.getIdentifierInfo() : 0; 1791 SourceLocation IdLoc = ConsumeToken(); 1792 1793 // Parse the '('. 1794 if (Tok.isNot(tok::l_paren)) { 1795 Diag(Tok, diag::err_expected_lparen); 1796 return true; 1797 } 1798 SourceLocation LParenLoc = ConsumeParen(); 1799 1800 // Parse the optional expression-list. 1801 ExprVector ArgExprs(Actions); 1802 CommaLocsTy CommaLocs; 1803 if (Tok.isNot(tok::r_paren) && ParseExpressionList(ArgExprs, CommaLocs)) { 1804 SkipUntil(tok::r_paren); 1805 return true; 1806 } 1807 1808 SourceLocation RParenLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc); 1809 1810 return Actions.ActOnMemInitializer(ConstructorDecl, getCurScope(), SS, II, 1811 TemplateTypeTy, IdLoc, 1812 LParenLoc, ArgExprs.take(), 1813 ArgExprs.size(), CommaLocs.data(), 1814 RParenLoc); 1815} 1816 1817/// ParseExceptionSpecification - Parse a C++ exception-specification 1818/// (C++ [except.spec]). 1819/// 1820/// exception-specification: 1821/// 'throw' '(' type-id-list [opt] ')' 1822/// [MS] 'throw' '(' '...' ')' 1823/// 1824/// type-id-list: 1825/// type-id 1826/// type-id-list ',' type-id 1827/// 1828bool Parser::ParseExceptionSpecification(SourceLocation &EndLoc, 1829 llvm::SmallVectorImpl<ParsedType> 1830 &Exceptions, 1831 llvm::SmallVectorImpl<SourceRange> 1832 &Ranges, 1833 bool &hasAnyExceptionSpec) { 1834 assert(Tok.is(tok::kw_throw) && "expected throw"); 1835 1836 SourceLocation ThrowLoc = ConsumeToken(); 1837 1838 if (!Tok.is(tok::l_paren)) { 1839 return Diag(Tok, diag::err_expected_lparen_after) << "throw"; 1840 } 1841 SourceLocation LParenLoc = ConsumeParen(); 1842 1843 // Parse throw(...), a Microsoft extension that means "this function 1844 // can throw anything". 1845 if (Tok.is(tok::ellipsis)) { 1846 hasAnyExceptionSpec = true; 1847 SourceLocation EllipsisLoc = ConsumeToken(); 1848 if (!getLang().Microsoft) 1849 Diag(EllipsisLoc, diag::ext_ellipsis_exception_spec); 1850 EndLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc); 1851 return false; 1852 } 1853 1854 // Parse the sequence of type-ids. 1855 SourceRange Range; 1856 while (Tok.isNot(tok::r_paren)) { 1857 TypeResult Res(ParseTypeName(&Range)); 1858 if (!Res.isInvalid()) { 1859 Exceptions.push_back(Res.get()); 1860 Ranges.push_back(Range); 1861 } 1862 if (Tok.is(tok::comma)) 1863 ConsumeToken(); 1864 else 1865 break; 1866 } 1867 1868 EndLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc); 1869 return false; 1870} 1871 1872/// \brief We have just started parsing the definition of a new class, 1873/// so push that class onto our stack of classes that is currently 1874/// being parsed. 1875void Parser::PushParsingClass(Decl *ClassDecl, bool NonNestedClass) { 1876 assert((NonNestedClass || !ClassStack.empty()) && 1877 "Nested class without outer class"); 1878 ClassStack.push(new ParsingClass(ClassDecl, NonNestedClass)); 1879} 1880 1881/// \brief Deallocate the given parsed class and all of its nested 1882/// classes. 1883void Parser::DeallocateParsedClasses(Parser::ParsingClass *Class) { 1884 for (unsigned I = 0, N = Class->NestedClasses.size(); I != N; ++I) 1885 DeallocateParsedClasses(Class->NestedClasses[I]); 1886 delete Class; 1887} 1888 1889/// \brief Pop the top class of the stack of classes that are 1890/// currently being parsed. 1891/// 1892/// This routine should be called when we have finished parsing the 1893/// definition of a class, but have not yet popped the Scope 1894/// associated with the class's definition. 1895/// 1896/// \returns true if the class we've popped is a top-level class, 1897/// false otherwise. 1898void Parser::PopParsingClass() { 1899 assert(!ClassStack.empty() && "Mismatched push/pop for class parsing"); 1900 1901 ParsingClass *Victim = ClassStack.top(); 1902 ClassStack.pop(); 1903 if (Victim->TopLevelClass) { 1904 // Deallocate all of the nested classes of this class, 1905 // recursively: we don't need to keep any of this information. 1906 DeallocateParsedClasses(Victim); 1907 return; 1908 } 1909 assert(!ClassStack.empty() && "Missing top-level class?"); 1910 1911 if (Victim->MethodDecls.empty() && Victim->MethodDefs.empty() && 1912 Victim->NestedClasses.empty()) { 1913 // The victim is a nested class, but we will not need to perform 1914 // any processing after the definition of this class since it has 1915 // no members whose handling was delayed. Therefore, we can just 1916 // remove this nested class. 1917 delete Victim; 1918 return; 1919 } 1920 1921 // This nested class has some members that will need to be processed 1922 // after the top-level class is completely defined. Therefore, add 1923 // it to the list of nested classes within its parent. 1924 assert(getCurScope()->isClassScope() && "Nested class outside of class scope?"); 1925 ClassStack.top()->NestedClasses.push_back(Victim); 1926 Victim->TemplateScope = getCurScope()->getParent()->isTemplateParamScope(); 1927} 1928 1929/// ParseCXX0XAttributes - Parse a C++0x attribute-specifier. Currently only 1930/// parses standard attributes. 1931/// 1932/// [C++0x] attribute-specifier: 1933/// '[' '[' attribute-list ']' ']' 1934/// 1935/// [C++0x] attribute-list: 1936/// attribute[opt] 1937/// attribute-list ',' attribute[opt] 1938/// 1939/// [C++0x] attribute: 1940/// attribute-token attribute-argument-clause[opt] 1941/// 1942/// [C++0x] attribute-token: 1943/// identifier 1944/// attribute-scoped-token 1945/// 1946/// [C++0x] attribute-scoped-token: 1947/// attribute-namespace '::' identifier 1948/// 1949/// [C++0x] attribute-namespace: 1950/// identifier 1951/// 1952/// [C++0x] attribute-argument-clause: 1953/// '(' balanced-token-seq ')' 1954/// 1955/// [C++0x] balanced-token-seq: 1956/// balanced-token 1957/// balanced-token-seq balanced-token 1958/// 1959/// [C++0x] balanced-token: 1960/// '(' balanced-token-seq ')' 1961/// '[' balanced-token-seq ']' 1962/// '{' balanced-token-seq '}' 1963/// any token but '(', ')', '[', ']', '{', or '}' 1964CXX0XAttributeList Parser::ParseCXX0XAttributes(SourceLocation *EndLoc) { 1965 assert(Tok.is(tok::l_square) && NextToken().is(tok::l_square) 1966 && "Not a C++0x attribute list"); 1967 1968 SourceLocation StartLoc = Tok.getLocation(), Loc; 1969 AttributeList *CurrAttr = 0; 1970 1971 ConsumeBracket(); 1972 ConsumeBracket(); 1973 1974 if (Tok.is(tok::comma)) { 1975 Diag(Tok.getLocation(), diag::err_expected_ident); 1976 ConsumeToken(); 1977 } 1978 1979 while (Tok.is(tok::identifier) || Tok.is(tok::comma)) { 1980 // attribute not present 1981 if (Tok.is(tok::comma)) { 1982 ConsumeToken(); 1983 continue; 1984 } 1985 1986 IdentifierInfo *ScopeName = 0, *AttrName = Tok.getIdentifierInfo(); 1987 SourceLocation ScopeLoc, AttrLoc = ConsumeToken(); 1988 1989 // scoped attribute 1990 if (Tok.is(tok::coloncolon)) { 1991 ConsumeToken(); 1992 1993 if (!Tok.is(tok::identifier)) { 1994 Diag(Tok.getLocation(), diag::err_expected_ident); 1995 SkipUntil(tok::r_square, tok::comma, true, true); 1996 continue; 1997 } 1998 1999 ScopeName = AttrName; 2000 ScopeLoc = AttrLoc; 2001 2002 AttrName = Tok.getIdentifierInfo(); 2003 AttrLoc = ConsumeToken(); 2004 } 2005 2006 bool AttrParsed = false; 2007 // No scoped names are supported; ideally we could put all non-standard 2008 // attributes into namespaces. 2009 if (!ScopeName) { 2010 switch(AttributeList::getKind(AttrName)) 2011 { 2012 // No arguments 2013 case AttributeList::AT_base_check: 2014 case AttributeList::AT_carries_dependency: 2015 case AttributeList::AT_final: 2016 case AttributeList::AT_hiding: 2017 case AttributeList::AT_noreturn: 2018 case AttributeList::AT_override: { 2019 if (Tok.is(tok::l_paren)) { 2020 Diag(Tok.getLocation(), diag::err_cxx0x_attribute_forbids_arguments) 2021 << AttrName->getName(); 2022 break; 2023 } 2024 2025 CurrAttr = new AttributeList(AttrName, AttrLoc, 0, AttrLoc, 0, 2026 SourceLocation(), 0, 0, CurrAttr, false, 2027 true); 2028 AttrParsed = true; 2029 break; 2030 } 2031 2032 // One argument; must be a type-id or assignment-expression 2033 case AttributeList::AT_aligned: { 2034 if (Tok.isNot(tok::l_paren)) { 2035 Diag(Tok.getLocation(), diag::err_cxx0x_attribute_requires_arguments) 2036 << AttrName->getName(); 2037 break; 2038 } 2039 SourceLocation ParamLoc = ConsumeParen(); 2040 2041 ExprResult ArgExpr = ParseCXX0XAlignArgument(ParamLoc); 2042 2043 MatchRHSPunctuation(tok::r_paren, ParamLoc); 2044 2045 ExprVector ArgExprs(Actions); 2046 ArgExprs.push_back(ArgExpr.release()); 2047 CurrAttr = new AttributeList(AttrName, AttrLoc, 0, AttrLoc, 2048 0, ParamLoc, ArgExprs.take(), 1, CurrAttr, 2049 false, true); 2050 2051 AttrParsed = true; 2052 break; 2053 } 2054 2055 // Silence warnings 2056 default: break; 2057 } 2058 } 2059 2060 // Skip the entire parameter clause, if any 2061 if (!AttrParsed && Tok.is(tok::l_paren)) { 2062 ConsumeParen(); 2063 // SkipUntil maintains the balancedness of tokens. 2064 SkipUntil(tok::r_paren, false); 2065 } 2066 } 2067 2068 if (ExpectAndConsume(tok::r_square, diag::err_expected_rsquare)) 2069 SkipUntil(tok::r_square, false); 2070 Loc = Tok.getLocation(); 2071 if (ExpectAndConsume(tok::r_square, diag::err_expected_rsquare)) 2072 SkipUntil(tok::r_square, false); 2073 2074 CXX0XAttributeList Attr (CurrAttr, SourceRange(StartLoc, Loc), true); 2075 return Attr; 2076} 2077 2078/// ParseCXX0XAlignArgument - Parse the argument to C++0x's [[align]] 2079/// attribute. 2080/// 2081/// FIXME: Simply returns an alignof() expression if the argument is a 2082/// type. Ideally, the type should be propagated directly into Sema. 2083/// 2084/// [C++0x] 'align' '(' type-id ')' 2085/// [C++0x] 'align' '(' assignment-expression ')' 2086ExprResult Parser::ParseCXX0XAlignArgument(SourceLocation Start) { 2087 if (isTypeIdInParens()) { 2088 EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated); 2089 SourceLocation TypeLoc = Tok.getLocation(); 2090 ParsedType Ty = ParseTypeName().get(); 2091 SourceRange TypeRange(Start, Tok.getLocation()); 2092 return Actions.ActOnSizeOfAlignOfExpr(TypeLoc, false, true, 2093 Ty.getAsOpaquePtr(), TypeRange); 2094 } else 2095 return ParseConstantExpression(); 2096} 2097