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